﻿/// <reference path="scripts.htm" />
//-----------------------------------------------------------------------
// Copyright (C) Nearsoft Inc. All rights reserved.
//-----------------------------------------------------------------------
Object.createNamespace('orderbot.myaccount.update');
//-----------------------------------------------------------------------
Object.extend(orderbot.myaccount.update, {
    div: null,
    btnSubmit: null,
    info: null,
    validateAddress: false,
    addressDialog: null,
    hasStates: false,

    init: function() {
        this.div = $('account-update');
        this.info = this.div.down('span#info');

        //set submit observer
        this.btnSubmit = this.div.down('input[id$=btnSubmit]');
        this.btnSubmit.observe('click', function(e) {
            e.stop(); this.submit(e.element());
        } .bind(this));

        //        //set zip code observer
        //        var txt = this.div.down('input[id$=txtZip]');
        //        txt.observe('keyup', function(e) {
        //            var isNumberKey = (e.keyCode >= 96 && e.keyCode <= 105) || (e.keyCode >= 48 && e.keyCode <= 57);
        //            if (!isNumberKey) return;
        //            var element = e.element();
        //            var value = element.value;
        //            if (/[0-9]{5}/.test(value)) {
        //                this.cityStateLookup(value);
        //            }
        //        } .bind(this));

        //orderbot.goToNext('txtZip', 'txtCity', 5, this.div);
        orderbot.goToNext('txtPhoneArea', 'txtPhone1', 3, this.div);
        orderbot.goToNext('txtPhone1', 'txtPhone2', 3, this.div);
        orderbot.goToNext('txtPhone2', 'txtPhoneExt', 4, this.div);

        var firstName = this.div.down('input[id$=txtFirstName]').value.escapeHTML();
        var LastName = this.div.down('input[id$=txtLastName]').value.escapeHTML();
        this.defaultRecipientName = String.format('{0} {1}', firstName, LastName);

        var ddl = this.div.down('SELECT[id$=ddlCountry]');
        ddl.observe('change', function(e) {
            //        if (!this.CountryHasStates(ddl.value)) {
            if (ddl.value != 226 && ddl.value != 38) {
                this.togglePhoneState(false);

            } else {
                this.togglePhoneState(true);
                this.populateStates(ddl.value);
            }
        } .bind(this));
        this.togglePhoneState(this.hasStates);
        this.initDialog();
    },

    togglePhoneState: function(withValidations) {
        var div = this.div;
        var val, vals = $('validators');
        val = vals.down('[id$=rfvPhoneZone]'); val.enabled = withValidations; ValidatorUpdateDisplay(val);
        val = vals.down('[id$=rfvPhone2]'); val.enabled = withValidations; ValidatorUpdateDisplay(val);
        val = vals.down('[id$=rfvPhone1]'); val.enabled = withValidations; ValidatorUpdateDisplay(val);
        val = vals.down('[id$=rfvZip]'); val.enabled = withValidations; ValidatorUpdateDisplay(val);

        if (!withValidations) {
            if (/Safari/.test(navigator.userAgent)) {
                new PeriodicalExecuter(function(pe) {
                    div.down('div[id=state-dd]').hide();
                    div.down('div[id=state-txt]').show();
                    pe.stop();
                }, 0.1);
            } else {
                div.down('div[id=state-dd]').hide();
                div.down('div[id=state-txt]').show();
            }
            div.down('div[id=phoneWithValidation]').hide();
            div.down('div[id=phoneFree]').show();
        }
        else {
            div.down('div[id=state-dd]').show();
            div.down('div[id=state-txt]').hide();
            div.down('div[id$=phoneWithValidation]').show();
            div.down('div[id$=phoneFree]').hide();
        }
    },

    populateStates: function(countryId) {

    
        StatesHandler.GetStatesByCountry(countryId, this.populateStatesResponse.bind(this));
    },
    populateStatesResponse: function(response) {
        if (response.error) { alert(response.error.Message); return; }

        var ddl = this.div.down('SELECT[id$=ddlStates]');

        var length = ddl.options.length;
        for (var i = 0; i < length; i++) { ddl.remove(0); }
        var result = eval(response.value);
        $(result).each(function(state) {
            var opt = $.OPTION({ text: state.Name, value: state.StateId });
            try {
                ddl.add(opt, null); // standards compliant; doesn't work in IE
            }
            catch (ex) {
                ddl.add(opt); // IE only
            }
        } .bind(this));

    },
    //set className to info span
    setClass: function(className) {
        this.info.removeClassName('msg').removeClassName('msg-success').removeClassName('msg-error');
        this.info.addClassName(className);
        return this.info;
    },

    initDialog: function() {
        var btnUse, btnLeave;
        var dialogContent = $.DIV({},
            "We found the following address while USPS validated your address.",
            this.addressElement = $.DIV({ className: "address-usps", style: { 'textAlign': 'left', 'padding': '20px'} },
                "2343 main st"
            ),
            $.DIV({},
                $.BR({}),
                btnUse = $.BUTTON({}, "Use this address"),
                btnLeave = $.BUTTON({}, "I want to use my address")
            )
        );

        this.onUseThisAddress = Prototype.emptyFunction;
        this.onLeaveMyAddress = Prototype.emptyFunction;
        var context = this;

        $(btnUse).observe("click", function() { context.onUseThisAddress(); });
        $(btnLeave).observe("click", function() { context.onLeaveMyAddress(); });

        this.addressDialog = new Dialog({
            title: "Address validation",
            content: dialogContent,
            close:
            {
                link: false,
                overlay: false,
                esc: false
            }
        });
    }
});
//-----------------------------------------------------------------------
Object.extend(orderbot.myaccount.update, {

    cityStateLookup: function(value) {
        var zip = parseInt(value, 10);
        if (Object.isNumber(zip) && zip.toString().length == 5) {
            USPSHandler.CityStateLookup(zip, this.cityStateLookupResponse.bind(this));
        }
    },

    cityStateLookupResponse: function(response) {
        if (!response.error) {
            var result = JSON.parse(response.value);
            var txtCity = this.div.down('input[id$=txtCity]');
            txtCity.value = result.City;
            var ddlStates = this.div.down('SELECT[id$=ddlStates]');
            ddlStates.down('OPTION[value=' + result.StateId + ']').selected = true;
            this.info.update();
        }
    }

});
//-----------------------------------------------------------------------
Object.extend(orderbot.myaccount.update, {

    submit: function(element) {
        
        if (!Page_ClientValidate('AccountUpdate')) { return; }
        orderbot.toogleAjaxButton(element, true);
        if (this.validateAddress) {
            this.setClass('msg').update('validating address...');
            var address = {
                ID: 0,
                Address: this.div.down('input[id$=txtAddress]').value.strip().escapeHTML(),
                Address2: this.div.down('input[id$=txtAddress2]').value.strip().escapeHTML(),
                City: this.div.down('input[id$=txtCity]').value.strip().escapeHTML(),
                Zip: this.div.down('input[id$=txtZip]').value.strip().escapeHTML(),
                StateId: $F(this.div.down('SELECT[id$=ddlStates]'))
            };
            USPSHandler.ValidateAddress(address, this.AddressValidateResponse.bind(this));
        }
        else {
            this.updateCustomer();
        }
    },

    LeaveAddressAsIt: function() {
        this.validateAddress = false;
        this.info.toggleClassName('msg').update();
    },

    AddressValidateResponse: function(response) {

        if (response.error) {
            orderbot.toogleAjaxButton(this.btnSubmit);
            this.setClass('msg-error').update(response.error.Message);
            window.setTimeout(function() { this.setClass('msg').update(); } .bind(this), 3000);
            return;
        }

        var result = JSON.parse(response.value);
        if (result.Error || result.ReturnText) {
            orderbot.toogleAjaxButton(this.btnSubmit);
            var leaveAddress = " (<a href=\"javascript:orderbot.myaccount.update.LeaveAddressAsIt();\">I want to use that address</a>)";
            this.info.toggleClassName('msg-error').update((result.Error ? result.Error.Message : result.ReturnText) + leaveAddress);
            //            window.setTimeout(function() { this.info.toggleClassName('msg').update(); } .bind(this), 3000);
            return;
        }

        var txtAddress = this.div.down('input[id$=txtAddress]');
        var txtAddress2 = this.div.down('input[id$=txtAddress2]');
        var txtZip = this.div.down('input[id$=txtZip]');
        var txtCity = this.div.down('input[id$=txtCity]');
        var ddlStates = this.div.down('SELECT[id$=ddlStates]');

        if (txtAddress.value != result.Address ||
             txtAddress2.value != result.Address2 ||
             txtZip.value != result.Zip ||
             txtCity.value != result.City ||
             $F(ddlStates) != result.StateId) {

            this.addressElement.update(
            result.Address + "<br/>" +
            (result.Address2 ? result.Address2 + "<br/>" : "") +
            //(result.Zip4 ? result.Zip4 + "-" : "") +
            result.Zip + "<br/>" +
            result.City + ", " +
            result.State + "<br/>");

            this.addressDialog.open();

            var context = this;
            this.onUseThisAddress = function() {
                txtAddress.value = result.Address;
                txtAddress2.value = result.Address2;
                txtZip.value = result.Zip;
                txtCity.value = result.City;
                ddlStates.down('OPTION[value=' + result.StateId + ']').selected = true;
                context.addressDialog.close();
                this.updateCustomer();
            };

            this.onLeaveMyAddress = function() {
                context.addressDialog.close();
                this.updateCustomer();
            };
        }
        else {
            this.updateCustomer();
        }


        //        var txt = this.div.down('input[id$=txtAddress]');
        //        txt.value = result.Address;
        //        var txt = this.div.down('input[id$=txtAddress2]');
        //        txt.value = result.Address2;
        //        var txt = this.div.down('input[id$=txtZip]');
        //        txt.value = result.Zip;
        //        var txt = this.div.down('input[id$=txtCity]');
        //        txt.value = result.City;
        //        var ddlStates = this.div.down('SELECT[id$=ddlStates]');
        //        ddlStates.down('OPTION[value=' + result.StateId + ']').selected = true;

        //        var phone = String.format("{0}{1}{2}",
        //            this.div.down('input[id$=txtPhoneArea]').value.strip().escapeHTML(),
        //            this.div.down('input[id$=txtPhone1]').value.strip().escapeHTML(),
        //            this.div.down('input[id$=txtPhone2]').value.strip().escapeHTML()
        //        );


        //        var customer = {
        //            FirstName: this.div.down('input[id$=txtFirstName]').value.strip().escapeHTML(),
        //            LastName: this.div.down('input[id$=txtLastName]').value.strip().escapeHTML(),
        //            Email: this.div.down('input[id$=txtEmail]').value.strip().escapeHTML(),
        //            Address: result.Address,
        //            Address2: result.Address2,
        //            Zip: result.Zip,
        //            City: result.City,
        //            StateId: result.StateId,
        //            Phone: phone,
        //            PhoneExt: this.div.down('input[id$=txtPhoneExt]').value.strip().escapeHTML()

        //        };
        //        this.setClass('msg').update('updating account...');
        //        CustomersHandler.UpdateCustomer(customer, this.updateCustomerResponse.bind(this));

    },
    countryHasStates: function() {
        var ddl = this.div.down('SELECT[id$=ddlCountry]');
        var hasStates = ddl.value == 226 || ddl.value == 38;
        return hasStates;
    },
    updateCustomer: function() {

        var phone, phoneExt, stateId, stateName;
        var hasStates = this.countryHasStates();
        if (hasStates) {
            phone = String.format("{0}{1}{2}",
                this.div.down('input[id$=txtPhoneArea]').value.strip().escapeHTML(),
                this.div.down('input[id$=txtPhone1]').value.strip().escapeHTML(),
                this.div.down('input[id$=txtPhone2]').value.strip().escapeHTML()
            );
            phoneExt = this.div.down('input[id$=txtPhoneExt]').value.strip().escapeHTML();
            var ddlStates = this.div.down('SELECT[id$=ddlStates]');
            stateId = $F(ddlStates);
        } else {
            phone = this.div.down('input[id$=txtPhone]').value.strip().escapeHTML();
            phoneExt = '';
            stateId = null;
            stateName = this.div.down('input[id$=txtState]').value.strip().escapeHTML();
        }

        var txtAddress = this.div.down('input[id$=txtAddress]');
        var txtAddress2 = this.div.down('input[id$=txtAddress2]');
        var txtZip = this.div.down('input[id$=txtZip]');
        var txtCity = this.div.down('input[id$=txtCity]');
        var ddlCountries = this.div.down('SELECT[id$=ddlCountry]');
        var hasStates = this.countryHasStates();
        var customer = {
            firstName: this.div.down('input[id$=txtFirstName]').value.strip().escapeHTML(),
            lastName: this.div.down('input[id$=txtLastName]').value.strip().escapeHTML(),
            email: this.div.down('input[id$=txtEmail]').value.strip().escapeHTML(),
            address: txtAddress.value.strip().escapeHTML(),
            address2: txtAddress2.value.strip().escapeHTML(),
            zip: txtZip.value.strip().escapeHTML(),
            city: txtCity.value.strip().escapeHTML(),
            countryId: $F(ddlCountries),
            stateId: hasStates ? stateId : null,
            stateName: hasStates ? null : stateName,
            phone: phone,
            phoneExt: hasStates ? phoneExt : null
        };


        this.setClass('msg').update('updating account...');
        CustomersHandler.UpdateCustomer(customer, this.updateCustomerResponse.bind(this));
    },

    updateCustomerResponse: function(response) {
        if (response.error) {
            orderbot.toogleAjaxButton(this.btnSubmit);
            this.setClass('msg-error').update(response.error.Message);
            window.setTimeout(function() { this.setClass('msg').update(); } .bind(this), 3000);
            return;
        }

        var result = JSON.parse(response.value);
        if (result) {

            $$('span[id$=LoginName1]').first().update(result.Email);
            var recipients = $$('span[id$=lblRecipient]');
            recipients.each(function(recipient) {
                if (recipient.innerHTML == this.defaultRecipientName) {
                    recipient.innerHTML = result.Name;
                }
            } .bind(this));

        }

        orderbot.toogleAjaxButton(this.btnSubmit);
        this.setClass('msg-success').update('Account Updated.');
        window.setTimeout(function() { this.setClass('msg').update(); } .bind(this), 3000);

    }

});
//-----------------------------------------------------------------------
// Copyright (C) Nearsoft Inc. All rights reserved.
//-----------------------------------------------------------------------
Object.createNamespace('orderbot.myaccount.changepassword');
//-----------------------------------------------------------------------
Object.extend(orderbot.myaccount.changepassword, {

    div: null,
    info: null,
    btnSubmit: null,

    init: function() {
        this.div = $('account-update');
        this.info = this.div.down('span#info');
        this.btnSubmit = this.div.down('input[id$=btnSubmit]');
        //set submit observer
        this.btnSubmit.observe('click', function(e) {
            e.stop();
            if (Page_ClientValidate('ChangePassword')) { this.changePassword(); }
        } .bind(this));
    },
    changePassword: function() {
        this.setClass('msg').update('changing password...');
        var args = {
            currentPassword: this.div.down('input[id$=txtCurrentPassword]').value.strip().escapeHTML(),
            newPassword: this.div.down('input[id$=txtNewPassword]').value.strip().escapeHTML()
        };
        orderbot.toogleAjaxButton(this.btnSubmit, true);
        CustomersHandler.ChangePassword(args, this.changePasswordResponse.bind(this));
    },

    changePasswordResponse: function(response) {
        if (response.error) {
            orderbot.toogleAjaxButton(this.btnSubmit);
            this.setClass('msg-error').update(response.error.Message);
            window.setTimeout(function() {
                this.setClass('msg').update();
            } .bind(this), 3000);
            return;
        }

        orderbot.toogleAjaxButton(this.btnSubmit);
        this.setClass('msg-success').update('Password Changed.');
        window.setTimeout(function() {
            this.setClass('msg').update();
        } .bind(this), 3000);
    },
    //set className to info span
    setClass: function(className) {
        this.info.removeClassName('msg').removeClassName('msg-success').removeClassName('msg-error');
        this.info.addClassName(className);
        return this.info;
    }

});
