var md = {}; // This is the setup for the webtools namespace

(function() { // This is where jQuery code can safely go without foobarring prototype
	var $ = jQuery
	
    $(document).ready(function() { 
        // These functions get called on DOM ready
        $('a').click(function() { $(this).blur() }) // prevents outlines on links for IE
        
        // I don't think we're using the tabSelector right now.
        md.tabSelector();
        
        if($('div.date_picker.backward').size()) {
            Date.firstDayOfWeek = 0;
            Date.format = 'mm/dd/yyyy';
        	$('div.date_picker.backward input').datePicker({clickInput:true,startDate: '01/01/1970', endDate: (new Date()).asString()}).dpSetPosition($.dpConst.POS_BOTTOM, $.dpConst.POS_LEFT);
        }
        
        if($('div.date_picker.forward').size()) {
            Date.firstDayOfWeek = 0;
            Date.format = 'mm/dd/yyyy';
        	$('div.date_picker.forward input').datePicker({clickInput:true,startDate: (new Date()).asString()}).dpSetPosition($.dpConst.POS_BOTTOM, $.dpConst.POS_LEFT);
        }

        if($('div.date_picker.forward.twodays').size()) {
            Date.firstDayOfWeek = 0;
            Date.format = 'mm/dd/yyyy';
            var today = new Date();
            today.setDate(today.getDate() + 2)
            $('div.date_picker.forward input').val(today.asString())
        	$('div.date_picker.forward input').datePicker({clickInput:true,startDate: today.asString()}).dpSetPosition($.dpConst.POS_BOTTOM, $.dpConst.POS_LEFT);
        }
        
        if($('div.jspin input').size()) {
            $.spin.imageBasePath = '/media/js/jquery_spin/img/';
            $('div.jspin input[type="text"]').spin({min: 0});
        }
        if($("select#current_customer")){
            md.currentCustomer();
        }
        if ($("select[name=acct_type]")) {
            $("select[name=acct_type]").change(function(){
                var acct_type = $(this).val();
                md.toggleNewAccountForm(acct_type);
            });
        }
    });
	
    $(window).load(function() { 
        // These functions get called when everything has loaded
        $('div.equalize div.these').equalizeCols();
    });
	
	
	md.tabSelector = function() {
	   // NOT USED YET ... 
	    if(!$('div.tabs').size()) {return}
	    
	    var tabGroup = $('div.tabs_group')
	    
	    tabGroup.each(function() {
	        var groupItem = $(this);
	        var tabs = $(this).find('div.tabs li a');

    	    tabs.each(function() {
    	        $(this).click(function(c) {
    	            c.preventDefault();
    	            var linkClass = $(this).attr('class');

                    $(groupItem).find('.selected').removeClass('selected');
                    $(this).parent().addClass('selected');
                    $(groupItem).find('div.table').each(function() { 
                        if($(this).hasClass(linkClass)) {
                            $(this).addClass('selected');
                        }
                    });
    	        });
    	    });
    	    
	    });	
	}
	
    md.updateReps = function(s) {
        //Gets list of sales reps for provided divisions & creates select options
        $.getJSON('/get_division_reps/' + s, {}, function(data) {
            var options = '';
            $.each(data.values, function(i, item){
               options += '<option value="' + item.value + '">' + item.name + '</option>';
            });
            // Set our options
            $("select[name=sales_rep]").html(options);
        });
    }
    
    md.selectAccountReps = function(u) {
        // Takes a username & gets list of associated reps, then selects them
        $.getJSON('/get_account_reps/' + u, {}, function(data) {
            var reps = Array();
            $.each(data.values, function(i, item){
                reps[i] = item.value;
            });
            // multi-select all applicable values
            //$("select[name=sales_rep]").val(reps);
        });
    }
    
    md.getSelectedDivs = function() {        
        // Grabs all multi-select choices & asks for list of sales reps
        $("select[name=divs]").change(function(){
            s = $(this).val();
            md.updateReps(s);
        });
    }
    
    md.toggleNewAccountForm = function(t, edit) {
        // Handles showing/hiding form elements per acct_type
        if (t == 'rep') {
            // Show filters & rep results
            $("#account_filters").show()
            $("#customer_results").hide();
            $("#rep_results").show();
            md.hidePerms();
        }
        
        if ((t == 'cust') || (t == 'srep')) {
            // Show filters & customer results
            $("#account_filters").show()
            $("#customer_results").show();
            $("#rep_results").hide();
            md.hidePerms();
        }
        
        if (t == 'admin') {
            // Hide filters
            $("#account_filters").hide();
            md.hidePerms();
        }
        
        if (t == 'scust') {
            // Hide filters
            $("#account_filters").hide();
        }
                
        if (edit) {
            $("select[name=acct_type]").attr("disabled",true);
        }
        md.setupAjaxSearchSubmit();
        md.setupSingleCheckboxes();
    }
    
    md.setupAjaxSearchSubmit = function() {
        /* Captures 'Enter' key on query_value input
         * Prevents submitting user form & instead 
         * submits to Ajax customer search.
         */
        $("input[name=query_value]").live("keydown", function(e) {
            if (e.keyCode == 13) {
                e.preventDefault();
                $("#filter_submit").click();
                return false;
            }
        });
    }
    
    md.hidePerms = function() {
        // Hides Permissions checkboxes for all but subcustomers
        $("div#permissions").hide();
    }
    
    md.addFilter = function(s) {
        // Adds a new filter set to Customer/Rep search
        var filter = s.parent().parent(".match_filter_set");
        filter.clone(true).insertAfter(filter);
    }
    
    md.delFilter = function(s) {
        // Removes a filter set from Customer/Rep search
        // Ensures we always have one filter set
        var l = s.parent().parent().parent().children(".match_filter_set").size();
        if (l > 1) {
            var el = s.parent().parent(".match_filter_set");
            if (el.attr("id") != undefined) {
                $(el).remove();
            }
        }
        else {
            alert("You cannot remove the base filter.");
        }
    }
    
    md.clearCustomerResults = function() {
        /* 
            Helper to clear Ajax customer results
            We only want to clear unchecked results
            because sometimes we have existing items
            i.e., when editing an account
        */
        $(".customer_results input:checkbox").each(function(i) {
            if (this.checked==false) {
                $(this).parent().parent().remove()
            };
        });
    }
    
    md.clearRepResults = function() {
        /* 
            Helper to clear Ajax customer results
            We only want to clear unchecked results
            because sometimes we have existing items
            i.e., when editing an account
        */
        $(".rep_results input:checkbox").each(function(i) {
            if (this.checked==false) {
                $(this).parent().parent().remove()
            };
        });
    }
    
    md.resultExists = function(id) {
        this.exists = $("tr[id=" + id + "]").size() > 0;
        return this.exists;
    }
    
    md.displayCustomers = function(msg) {
        // Displays Customer results from filters
        
        // Clear all unchecked results
        md.clearCustomerResults();
        // Make sure we actually have results
        if ($(msg).size() > 0) {
            // Loop over results & add to form
            $(msg).each(function(i){
                var id = $(this).attr("pk").toString();
                // Make sure we don't add more than one copy of each Customer match
                if (!md.resultExists(id)) {                   
                    x = '<tr class="customer_results" id="' + id + '"><td class="checkbox"><input type="checkbox" name="customer_choice" value="' + id +'"></td><td class="company_num">' + id + '</td><td class="company">' + $(this.fields).attr("name") + '</td><td class="city">' + $(this.fields).attr("city") + '</td><td class="state">' + $(this.fields).attr("state") + '</td><td class="empty"></td></tr>';
                    $(x).insertBefore($(".customer_select_all"));
                };
            });
            // Show our 'Select All' checkbox
            if ($("select[name=acct_type]").val() == 'srep') {
                $(".customer_select_all").show();
            }
            else if ($("select[name=acct_type]").val() == 'cust') {
                md.activateSingleCheckOnly($("input:checkbox[name=customer_choice]"));
            }
        }
        else {
            // No results = clear everything that is unchecked
            md.clearCustomerResults();
            // Hide our 'Select All' checkbox if no results remain
            if ($(".customer_results").size() == 0) {
                $(".customer_select_all").hide();
            };
        }
    }
    
    md.displayReps = function(msg) {
        // Displays Customer results from filters
        
        // Clear all unchecked results
        md.clearRepResults();
        
        // Make sure we actually have results
        if ($(msg).size() > 0) {
            // Loop over results & add to form
            $(msg).each(function(i){
                var id = $(this).attr("pk");
                // Make sure we don't add more than one copy of each Customer match
                if (!md.resultExists(id)) {
                    x = '<tr class="rep_results" id="' + id + '"><td class="checkbox"><input type="checkbox" name="rep_choice" value="' + id +'"></td><td class="number">' + id + '</td><td class="name">' + $(this.fields).attr("name") + '</td><td class="empty"></td></tr>';
                    $(x).insertBefore($(".rep_select_all"));
                };
            });
            // Show our 'Select All' checkbox
            md.activateSingleCheckOnly($("input:checkbox[name=rep_choice]"));
            $(".rep_select_all").show();
        }
        else {
            // No results = clear everything that is unchecked
            md.clearCustomerResults();
            // Hide our 'Select All' checkbox if no results remain
            if ($(".rep_results").size() == 0) {
                $(".rep_select_all").hide();
            };
        }
    }
    
    md.activateFilters = function() {
        // Sets up our handlers for filter adding & removing
        $(".add_match_filter").click(function(e){
            e.preventDefault();
            md.addFilter($(this));
        });
        $(".remove_match_filter").click(function(e){
            e.preventDefault();
            md.delFilter($(this));
        });
        $("#filter_submit").click(function(e){
            e.preventDefault();
            md.showAjaxLoad();
            var acct_type = $("select[name=acct_type]").val();
            var data = $("select[name=all_any]").serialize();
            data += "&" + $("select[name=query_field]").serialize();
            data += "&" + $("select[name=query_type]").serialize();
            data += "&" + $("input[name=query_value]").serialize();
            if (acct_type == 'cust') {
                $.ajax({
                    url: "/account/get_customers/", 
                    type: "POST", 
                    data: data,
                    dataType: "json",
                    success: function(msg) {
                        md.hideAjaxLoad();
                        md.displayCustomers(msg);
                    }
                });
                return false;
            }
            else if (acct_type == 'rep') {
                $.ajax({
                    url: "/account/get_reps/", 
                    type: "POST", 
                    data: data,
                    dataType: "json",
                    success: function(msg) {
                        md.hideAjaxLoad();
                        md.displayReps(msg);
                    }
                });
                return false;
            }
            else {
                return;
            }        
        });
        $("#customer_select_all").click(function(){
            var c = this.checked;
            $(".customer_results input:checkbox").each(function(i){
                this.checked = c;
            });
        });
        
        if (!$(".customer_results input:checkbox").size() > 0) {
            $(".customer_select_all").hide();
        }
    }
    
    md.hideAjaxLoad = function() {
        $("img.ajax_loader").hide();
        $("#filter_submit").show();
    }
    
    md.showAjaxLoad = function() {
        $("#filter_submit").hide();
        $("img.ajax_loader").show();
    }
    
    md.setupSingleCheckboxes = function() {
        /* Helper func for forcing single checkbox values
         * The plan is to only use this on page load,
         * otherwise, the funcs that write out choices will
         * trigger the call themselves as last step.
         */
        var acct_type = $("select[name=acct_type]").val()
        
        if (acct_type == 'rep') {
            md.activateSingleCheckOnly($("input:checkbox[name=rep_choice]"));
        }
        else if (acct_type == 'cust') {
            md.activateSingleCheckOnly($("input:checkbox[name=customer_choice]"));
        }
        else {
            // Only reps & customers have limits
            return;
        }
    }
    
    md.activateSingleCheckOnly = function(el) {
        // Prevent more than one checkbox from being selected
        el.unbind();
        el.click(function() {
            el.not(this).removeAttr("checked");
        });
    }
    
    md.currentCustomer = function() {
        // This changes the current session customer
        // Confirm with the user that cart will be destroyed.
        $("select#current_customer").change(function(event){
            event.preventDefault();
            var okay = confirm("If you have an open Cart it will be removed if you change your customer now. Are you sure?")
            if (okay) {
                $(this).parent("form#customer_selector").submit();
            }
            else {
                return false;
            }
        });
    }
    
    md.adminEditOnly = function() {
        // Hides admin-only fields
        $("#admin_edit_only").hide();
    }
    
    md.accountEditMode = function() {
        // Hides create-only fields
        $("div.create_only_fields").hide()
    }
})();
