var App_Customer_Grid =
{
    rewardDefaults: {
        reward_margine_increase  : 25,
        reward_amount_put_towards: 75
    },

    initForm: function (id)
    {
        $('#' + id + ' input[name="CUSTOMER[reward_is]"]:radio').change(function(){
            if (this.checked) {
                var tr = getParentTag($('#' + id + ' input[name="CUSTOMER[rewards_hq_account_number]"]').get(0), 'TR');
                if (this.value == 'n') {
                    if (tr) {
                        $(tr).hide();
                    }
                    $('input[name="CUSTOMER[rewards_to_price]"]:checkbox').attr('checked', 'checked');
                } else {
                    if (tr) {
                        $(tr).show();
                    }
                }
            }
        }).change().click(function(){this.blur()});
        $('#' + id + ' input[name="CUSTOMER[rewards_to_price]"]:checkbox').change(function(){
            App_Customer_Grid.autoEnableRewards();
        }).click(function(){this.blur()});
    },

    autoEnableRewards: function ()
    {
        var rewards_to_price = $('input[name="CUSTOMER[rewards_to_price]"]:checkbox:checked').size();
        var reward_is = $('input[name="CUSTOMER[reward_is]"]:radio:checked').val();
    }
};

var countryState = new Array();
countryState[40] = new Array();
countryState[40]['Alberta'] = 'Alberta';
countryState[40]['British Columbia'] = 'British Columbia';
countryState[40]['Manitoba'] = 'Manitoba';
countryState[40]['New Brunswick'] = 'New Brunswick';
countryState[40]['Newfoundland'] = 'Newfoundland';
countryState[40]['North West Territory'] = 'North West Territory';
countryState[40]['Nova Scotia'] = 'Nova Scotia';
countryState[40]['Nunavut'] = 'Nunavut';
countryState[40]['Ontario'] = 'Ontario';
countryState[40]['Prince Edward Island'] = 'Prince Edward Island';
countryState[40]['Quebec'] = 'Quebec';
countryState[40]['Saskatchewan'] = 'Saskatchewan';
countryState[40]['Yukon'] = 'Yukon';
countryState[140] = Array();
countryState[140]['Aguascalientes'] = 'Aguascalientes';
countryState[140]['Baja California'] = 'Baja California';
countryState[140]['Baja California Sur'] = 'Baja California Sur';
countryState[140]['Campeche'] = 'Campeche';
countryState[140]['Chiapas'] = 'Chiapas';
countryState[140]['Chihuahua'] = 'Chihuahua';
countryState[140]['Coahuila'] = 'Coahuila';
countryState[140]['Colima'] = 'Colima';
countryState[140]['Durango'] = 'Durango';
countryState[140]['Federal District'] = 'Federal District';
countryState[140]['Guanajuato'] = 'Guanajuato';
countryState[140]['Guerrero'] = 'Guerrero';
countryState[140]['Hidalgo'] = 'Hidalgo';
countryState[140]['Jalisco'] = 'Jalisco';
countryState[140]['Mexico State'] = 'Mexico State';
countryState[140]['Michoacan'] = 'Michoacan';
countryState[140]['Morelos'] = 'Morelos';
countryState[140]['Nayarit'] = 'Nayarit';
countryState[140]['Nuevo Leon'] = 'Nuevo Leon';
countryState[140]['Oaxaca'] = 'Oaxaca';
countryState[140]['Puebla'] = 'Puebla';
countryState[140]['Queretaro'] = 'Queretaro';
countryState[140]['Quintana Roo'] = 'Quintana Roo';
countryState[140]['San Luis Potosi'] = 'San Luis Potosi';
countryState[140]['Sinaloa'] = 'Sinaloa';
countryState[140]['Sonora'] = 'Sonora';
countryState[140]['Tabasco'] = 'Tabasco';
countryState[140]['Tamaulipas'] = 'Tamaulipas';
countryState[140]['Tlaxcala'] = 'Tlaxcala';
countryState[140]['Veracruz'] = 'Veracruz';
countryState[140]['Yucatan'] = 'Yucatan';
countryState[140]['Zacatecas'] = 'Zacatecas';
countryState[234] = new Array();
countryState[234]['Armed Forces Middle East/Africa'] = 'Armed Forces Middle East/Africa';
countryState[234]['Armed Forces Americas'] = 'Armed Forces Americas';
countryState[234]['Armed Forces Pacific'] = 'Armed Forces Pacific';
countryState[234]['Alabama'] = 'Alabama';
countryState[234]['Alaska'] = 'Alaska';
countryState[234]['Arizona'] = 'Arizona';
countryState[234]['Arkansas'] = 'Arkansas';
countryState[234]['California'] = 'California';
countryState[234]['Colorado'] = 'Colorado';
countryState[234]['Connecticut'] = 'Connecticut';
countryState[234]['Delaware'] = 'Delaware';
countryState[234]['District of Columbia'] = 'District of Columbia';
countryState[234]['Florida'] = 'Florida';
countryState[234]['Georgia'] = 'Georgia';
countryState[234]['Hawaii'] = 'Hawaii';
countryState[234]['Idaho'] = 'Idaho';
countryState[234]['Illinois'] = 'Illinois';
countryState[234]['Indiana'] = 'Indiana';
countryState[234]['Iowa'] = 'Iowa';
countryState[234]['Kansas'] = 'Kansas';
countryState[234]['Kentucky'] = 'Kentucky';
countryState[234]['Louisiana'] = 'Louisiana';
countryState[234]['Maine'] = 'Maine';
countryState[234]['Maryland'] = 'Maryland';
countryState[234]['Massachusetts'] = 'Massachusetts';
countryState[234]['Michigan'] = 'Michigan';
countryState[234]['Minnesota'] = 'Minnesota';
countryState[234]['Mississippi'] = 'Mississippi';
countryState[234]['Missouri'] = 'Missouri';
countryState[234]['Montana'] = 'Montana';
countryState[234]['Nebraska'] = 'Nebraska';
countryState[234]['Nevada'] = 'Nevada';
countryState[234]['New Hampshire'] = 'New Hampshire';
countryState[234]['New Jersey'] = 'New Jersey';
countryState[234]['New Mexico'] = 'New Mexico';
countryState[234]['New York'] = 'New York';
countryState[234]['North Carolina'] = 'North Carolina';
countryState[234]['North Dakota'] = 'North Dakota';
countryState[234]['Ohio'] = 'Ohio';
countryState[234]['Oklahoma'] = 'Oklahoma';
countryState[234]['Oregon'] = 'Oregon';
countryState[234]['Pennsylvania'] = 'Pennsylvania';
countryState[234]['Rhode Island'] = 'Rhode Island';
countryState[234]['South Carolina'] = 'South Carolina';
countryState[234]['South Dakota'] = 'South Dakota';
countryState[234]['Tennessee'] = 'Tennessee';
countryState[234]['Texas'] = 'Texas';
countryState[234]['Utah'] = 'Utah';
countryState[234]['Vermont'] = 'Vermont';
countryState[234]['Virginia'] = 'Virginia';
countryState[234]['Washington'] = 'Washington';
countryState[234]['West Virginia'] = 'West Virginia';
countryState[234]['Wisconsin'] = 'Wisconsin';
countryState[234]['Wyoming'] = 'Wyoming';

function updateCountry4State(counName, stateName, synCont)
{
    var state = document.getElementById(stateName);
    var coun = document.getElementById(counName);
    var id_count = updateCountry4StateGetVal(coun);
    var stateVal = updateCountry4StateGetVal(state);

    if ( 'undefined' == typeof countryState[id_count] ){
        stateNew = document.createElement("input");
        stateNew.setAttribute("type", "text");
        stateNew.setAttribute("name", stateName);
        stateNew.setAttribute("id", stateName);
    }else{
        stateNew = document.createElement("select");
        stateNew.setAttribute("name", stateName);
        stateNew.setAttribute("id", stateName);
        var id_state;
        stateNew.options[stateNew.options.length] = new Option('-------------------', '');
        for(id_state in countryState[id_count]){
            if(id_state != 'indexOf') {
                    //alert(countryState[id_count][id_state]);
                    var a = countryState[id_count][id_state];
                    a = typeof a;
                    if (a == "string") {
                        stateNew.options[stateNew.options.length] = new Option(id_state, countryState[id_count][id_state]);
                    }
            }
        }
    }
    stateNew.name = stateName;
    stateNew.style.width = "118px";

    if(state != null){
       var offsetParent = state.parentNode;
    } else {
        return false;
    }
    if(state != null){
        while(offsetParent.childNodes.length){
            offsetParent.removeChild(offsetParent.childNodes[0]);
        }
    }

    updateCountry4StateSetVal(stateNew, stateVal);
    offsetParent.appendChild(stateNew);
    if ('undefined' != typeof synCont){
        updateCountry4StateSetVal(document.getElementsByName(synCont)[0], id_count);
        document.getElementsByName(synCont)[0].onchange();
    }
    return true;
}

function updateCountry4StateGetVal(obj)
{
    if (obj != null && 'SELECT' == obj.tagName){
        return obj.options[obj.selectedIndex].value;
    }else if(obj != null && 'INPUT' == obj.tagName){
        return obj.value;
    }
}
function updateCountry4StateSetVal(obj, val)
{
    if ('SELECT' == obj.tagName){
        for(var i = 0; i < obj.options.length; i++){
            if (obj.options[i].value == val){
                obj.selectedIndex = i;
            }
        }
    }else if('INPUT' == obj.tagName){
        obj.value = val;
    }
    return true;
}




function handleBillingCountry(contObj)
{
    var cppDiscountTr =	document.getElementById('cppdiscount').parentNode.parentNode;
    var can_cpp_disc_perc = document.getElementsByName('CUSTOMER[can_cpp_disc_perc]')[0];
    var can_cpp_disc = document.getElementsByName('CUSTOMER[can_cpp_disc]')[0];
    if (40 == contObj.value ){
        cppDiscountTr.style.display = 'table-row';
        can_cpp_disc_perc.disabled = false;
        can_cpp_disc.disabled = false;
    }else{
        cppDiscountTr.style.display = 'none';
        can_cpp_disc_perc.disabled = true;
        can_cpp_disc.disabled = true;
    }
}

function InitMyForm()
{
    updateCountry4State('billing_country', 'billing_state');
    updateCountry4State('shipping_country', 'shipping_state');
    copyBillingToShipping(document.getElementById('shipping_address'));
}

function copyBillingToShipping(chk)
{
    try {
        if(chk.checked){
            document.getElementById('shipping_state').parentNode.parentNode.parentNode.style.display = 'none';
        } else {
            document.getElementById('shipping_state').parentNode.parentNode.parentNode.style.display = '';
        }
    } catch (e) {

    }
}

function hideCpp(val)
{
    if(val == 40){
        document.getElementById('cppdiscount').parentNode.parentNode.style.display = '';
    } else {
        document.getElementById('cppdiscount').parentNode.parentNode.style.display = 'none';
    }
}

function initHideCpp()
{
    var val = document.getElementById('billing_country').value;
    hideCpp(val);
    var chk_val = document.getElementById('ship_as_bill');
    copyBillingToShipping(chk_val)
}

function setCustomerDefaultsAdm(el)
{
    setDefMakersAdm(el);
    setDefaultTermsAdm(el);
}

var fl_maker_clicked = false;
var fl_terms_clicked = false;
var fl_shipping_clicked = false;
var fl_freight_clicked = false;

function setDefaultTermsAdm(el)
{
    try {
        var cust_type = el.value;
        switch(cust_type) {
            case '4': // Dealer
                if (!fl_terms_clicked) {
                    document.getElementById('freight_terms_id').value = 1; // Net 10th
                }
                if (!fl_freight_clicked) {
                    document.getElementById('freight_id').value = document.getElementById('billing_country').value == 40 ? 4 : 1; // Prepaid @ $250 for canadian, Prepaid @ $100 for all other
                }
                break;
            default:
                if (!fl_terms_clicked) {
                    document.getElementById('freight_terms_id').value = 9; // credit card
                }
                if (!fl_freight_clicked) {
                    document.getElementById('freight_id').value = 2; // Collect
                }
        }
        if (!fl_shipping_clicked) {
            id_country = document.getElementById('ship_as_bill').checked ? document.getElementById('billing_country').value : document.getElementById('shipping_country').value;
            document.getElementById('shipping_via_id').value = id_country == 40 ? 8 : 1; // DHL for Canadian, Fed-Ex Ground - for all other
        }
    } catch (e) {

    }
}

function setDefMakersAdm(el)
{
    if (fl_maker_clicked) {
        //user already clicked on makers
        return;
    }
    try {
        var form = el.form;
        var cust_type = el.value;
        switch (cust_type) {
            case '1': // Retail
            case '4': // Dealer
            case '5': // Jobber
            case '6': // WD

                moveSelections(form.elements['__maker_id[]'], form.elements['_maker_id[]'], form.elements['maker_id[]'], 'none');  // remove all from selected
                for (var i = 0; i < makers_arr.length; i++) {
                    for (var j = 0; j < s_makers_arr.length; j++) {
                        if (s_makers_arr[j] == form.elements['__maker_id[]'].options[i].value) {
                            form.elements['__maker_id[]'].options[i].selected = true; //set selected for some makers (11, 42, 44)
                            break;
                        }
                    }
                }

                moveSelections(form.elements['__maker_id[]'], form.elements['_maker_id[]'], form.elements['maker_id[]'], 'add');  // move selection
                break;
            case '2': // Installer
            case '3': //BodyShop
                moveSelections(form.elements['__maker_id[]'], form.elements['_maker_id[]'], form.elements['maker_id[]'], 'all');  // select all
                break;
        }
    } catch(e) {

    }

}

function customerMailTo(idGroup)
{
    var regex = /^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/;
    var email = $('#' + idGroup + '-email').val();
    var idTemplate = $('#' + idGroup + '-idTemplate').val();
    if (email == '') {
        alert('Email is required');
        return false;
    }
    if (!regex.test(email)) {
        alert('Email is in wrong format');
        return false;
    }
    if (idTemplate == '') {
        window.open('mailto:' + email, '_self');
    } else {
        var url = BASE_URL + '/admin/maillist?action=emailTemplate&idTemplate=' + idTemplate + '&email=' + encodeURIComponent(email)
                + '&idCustomer=' + $('input:hidden[name=id]').val();
        window.open(url, '_blank');
    }
    return false;
}

