﻿/// <reference path="scripts.htm" />

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Copyright (c) 2008-2009 OrderBot Software, Inc. All rights reserved.
// orderbot.common.js
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var orderbot = orderbot || {};

Object.extend(orderbot, {

    defaultLoadingImg: { name: 'dots-white.gif', w: 21, h: 5 },
    imagesPath: null, iconsPath: null, buttonsPath: null,

    getImagePath: function(name) { return String.format('{0}{1}', this.imagesPath, name); },
    getIconPath: function(name) { return String.format('{0}Icons/{1}', this.imagesPath, name); },
    getButtonPath: function(name) { return String.format('{0}Buttons/{1}', this.imagesPath, name); },

    parseJSON: function(json) {
        return Try.these(
            function() { return JSON.parse(json); },
            function() { return eval("(" + json + ")"); }
          ) || false;
    },
    // this is more general then backend...
    toogleAjaxButton: function(element, hide, loadingImg) {
        if (element && Object.isElement(element)) {
            var id = String.format('{0}_loading', element.id);
            if (hide) {
                var o = Object.isUndefined(loadingImg) ? this.defaultLoadingImg : loadingImg;
                var w = o.w;
                var h = o.h;
                var dim = element.getDimensions();
                var marginW = ((dim.width - w) / 2);
                var marginH = ((dim.height - h) / 2);
                var imgStyle = String.format('margin:{1}px {0}px {1}px {0}px; width:{2}px; height:{3}px', marginW, marginH, w, h);
                var dom = $.IMG({ id: id, src: this.getImagePath(o.name), style: imgStyle });
                element.insert({ before: dom });
                element.hide();
            }
            else {
                if ($(id)) { $(id).remove(); }
                element.show();
            }
        }
    },

    goToNext: function(input, nextInput, count, container) {
        if (!input || !nextInput || !count) { return; }
        if (!container) { container = $$('body').first(); }
        var selector = String.format('input[id$={0}]', input);
        input = container.down(selector);
        input.observe('keyup', function(e) {
            var isNumberKey = (e.keyCode >= 96 && e.keyCode <= 105) || (e.keyCode >= 48 && e.keyCode <= 57);
            if (!isNumberKey) return;
            if (e.element().value.length == count) {
                var selector = String.format('input[id$={0}]', nextInput);
                container.down(selector).activate();
            }
        });
    },

    cleanCombo: function(ddl) {
        var length = ddl.options.length;
        for (var i = 0; i < length; i++) { ddl.remove(0); }
        var opt = $.OPTION({ text: 'loading...', value: '0' });
        try { ddl.add(opt, null); } catch (ex) { ddl.add(opt); }
    },

    populateStates: function(container, countryId, selectedStateId, sourceddl) {
        if (!countryId || !container) return;

        //alert(container.inspect());
        // get the states list to repopulate
        var ddl = container.down('SELECT[id$=ddlStates]');

        // Clean up current states
        var length = ddl.options.length;
        for (var i = 0; i < length; i++) { ddl.remove(0); }
        var opt = $.OPTION({ text: 'loading...', value: '0' });
        try { ddl.add(opt, null); } catch (ex) { ddl.add(opt); }

        var states = null;

        if (sourceddl) {
            states = sourceddl.select('option');
            this.fillStates(ddl, states, selectedStateId);
        }
        else {
            var context = this;
            StatesHandler.GetStatesByCountry(countryId, function(response) {
                if (response.error) { alert(response.error.Message); return; }
                // get result objects
                states = orderbot.parseJSON(response.value);
                // repopulate dropdown list
                context.fillStates(ddl, states, selectedStateId);
            })
        }
    },

    fillStates: function(ddl, states, selectedStateId) {
        // load states into list
        states.each(function(state) {
            var opt = $.OPTION({ text: state.text || state.Name, value: state.value || state.StateId });
            try { ddl.add(opt, null); /* standards compliant; doesn't work in IE */ }
            catch (ex) { ddl.add(opt); /* IE only */ }
        });
        if (selectedStateId) { ddl.value = selectedStateId; }
        ddl.remove(0); // remove the 'loading...' option
    },

    countryHasStates: function(value) {
        //TODO check db
        var hasStates = value == 226 || value == 38;
        return hasStates;
    },

    //    togglePhoneState: function(container, withValidations) {
    //        var div = container, val, vals = div.down('div[id=validators]');
    //        // Phone required validator
    //        val = vals.down('[id$=rfvPhoneZone]'); val.enabled = withValidations; ValidatorUpdateDisplay(val);
    //        val = vals.down('[id$=rfvPhone1]'); val.enabled = withValidations; ValidatorUpdateDisplay(val);
    //        val = vals.down('[id$=rfvPhone2]'); val.enabled = withValidations; ValidatorUpdateDisplay(val);

    //        // hide everything
    //        var stateddl = div.down('div[id=state-dd]').hide();
    //        var statetxt = div.down('div[id=state-txt]').hide();
    //        var phonevalid = div.down('div[id=phoneWithValidation]').hide();
    //        var phonefree = div.down('div[id=phoneFree]').hide();
    //        var moreControls = div.down('div[id=faxWithValidation]') != null;
    //        if (moreControls) {
    //            var faxvalid = div.down('div[id=faxWithValidation]').hide();
    //            var faxfree = div.down('div[id=faxFree]').hide();
    //            var cellvalid = div.down('div[id=cellWithValidation]').hide();
    //            var cellfree = div.down('div[id=cellFree]').hide();
    //        }
    //        if (!withValidations) {
    //            statetxt.show();
    //            phonefree.show();
    //            if (moreControls) {
    //                faxfree.show();
    //                cellfree.show();
    //            }
    //        }
    //        else {
    //            stateddl.show();
    //            phonevalid.show();
    //            if (moreControls) {
    //                faxvalid.show();
    //                cellvalid.show();
    //            }
    //        }
    //    }

    togglePhoneState: function(container, withValidations) {
        var div = container, val, vals = div.down('div[id=validators]');
        // Phone required validator
        val = vals.down('[id$=rfvPhoneZone]'); val.enabled = withValidations; ValidatorUpdateDisplay(val);
        val = vals.down('[id$=rfvPhone1]'); val.enabled = withValidations; ValidatorUpdateDisplay(val);
        val = vals.down('[id$=rfvPhone2]'); val.enabled = withValidations; ValidatorUpdateDisplay(val);

        // hide everything
        var stateddl = div.down('div[id=state-dd]').hide();
        var statetxt = div.down('div[id=state-txt]').hide();
        var phonevalid = div.down('div[id=phoneWithValidation]').hide();
        var phonefree = div.down('div[id=phoneFree]').hide();
        var faxvalid = div.down('div[id=faxWithValidation]').hide();
        var faxfree = div.down('div[id=faxFree]').hide();
        var cellvalid = div.down('div[id=cellWithValidation]').hide();
        var cellfree = div.down('div[id=cellFree]').hide();

        if (!withValidations) {
            statetxt.show();
            phonefree.show();
            faxfree.show();
            cellfree.show();
        }
        else {
            stateddl.show();
            phonevalid.show();
            faxvalid.show();
            cellvalid.show();
        }
    }

});
