﻿function qbNav(_step) {
    var _section = null;
    if (_step > 0) {
        _section = builder.nextSection();
    } else {
        _section = builder.prevSection();
    }
    if (_section)
        window.PageBus.publish('com.cec.web.QueryBuilder.Wizard.onJump', { state: 'wiz', section: _section });
}

function qbJump(sectionId) {
    window.PageBus.publish('com.cec.web.QueryBuilder.Wizard.onJump', { state: 'wiz', section: sectionId });
}

function pubCheckbox(checkbox) {
    //var checkbox = e.currentTarget;
    window.PageBus.publish('com.cec.web.QueryBuilder.' + checkbox.name + '.onSelect', { name: checkbox.name, element: checkbox, value: checkbox.value });
}
function pubWizState(element) {
    window.PageBus.publish('com.cec.web.QueryBuilder.Wizard.onToggle', { menuItem: element.id });
}
function pubIndustrySort(element) {
    window.PageBus.publish('com.cec.web.QueryBuilder.Industry.onToggle', { sort: element.id });
}

var QbSection = Class.create({
    name: '',
    isInAdvancedView: true,
    isInWizardView: true,
    isDisplayed: false,
    isInTreeView: true,
    pageState: '',
    subscribers: [],
    initialize: function(name, isInWizardView, isInAdvancedView) {
        this.name = name;
        this.isInWizardView = isInWizardView;
        this.isInAdvancedView = isInAdvancedView;

        this.subscribers.push(window.PageBus.subscribe('com.cec.web.QueryBuilder.Wizard.onNav', this, this.display, null));
        this.subscribers.push(window.PageBus.subscribe('com.cec.web.QueryBuilder.Wizard.onJump', this, this.display, null));
    },
    display: function(subj, msg, data) {
        if (msg.state == 'adv' && this.isInAdvancedView) {
            this.show(false);
        } else if (msg.state == 'wiz' && this.isInWizardView && this.name == msg.section) {
            this.show(true);
        } else {
            this.hide();
        }
    },
    hide: function() {
        var sec = $(this.name);
        Element.hide(sec);
        this.toggleHelp(sec, false);
        this.isDisplayed = false;
    },
    show: function(isHelpShowing) {
        var sec = $(this.name);
        Element.show(sec);
        this.toggleHelp(sec, isHelpShowing);

        this.isDisplayed = true;
    },
    toggleHelp: function(section, isHelpShowing) {
        var divs = section.getElementsByTagName('div');
        for (var i = 0; i < divs.length; i++) {
            var div = divs[i];
            if (div.className == 'qbSectionHelp') {
                if (isHelpShowing) {
                    Element.show($(div));
                } else {
                    Element.hide($(div));
                }
            }
        }
    }
});

function CheckboxListItem() { }
CheckboxListItem.prototype = {
    code: '',
    label: '',
    name: '',
    selected: false,
    value: '',
    getNameLabel: function() {
        return this.name + ' [' + this.code + ']';
    },
    getCodeLabel: function() {
        return '[' + this.code + '] ' + this.name;
    }
};

var CheckboxList = Class.create({
    isDisabled: false,
    container: null,
    name: '',
    subscribers: [],
    hasAllOption: true,
    defaultIndex: 0,
    defaultValue: '0',
    clone: null,
    initialize: function(name, defaultValue) {
        if (defaultValue)
            this.defaultValue = defaultValue;

        this.container = document.getElementById(name + '-panel');
        this.name = name;
        this.addSubscriber(window.PageBus.subscribe('com.cec.web.QueryBuilder.' + this.name + '.onSelect', this, this.handleClick, null));

        if (!this.container)
            return;
        var containerNodes = this.container.getElementsByTagName('label');
        if (containerNodes[0]) {
            this.clone = containerNodes[0].cloneNode(true);
            for (var i = 0; i < containerNodes.length; i++) {
                var inputs = containerNodes[i].getElementsByTagName('input');
                if (inputs[0]) {
                    if (inputs[0].value == this.defaultValue)
                        this.defaultIndex = i;
                }
            }
        }
    },
    load: function(list) {
        if (!this.clone)
            return;
        this.container.innerHTML = '';
        this.container.appendChild(this.clone.cloneNode(true));
        for (var i = 0; i < list.length; ) {
            var obj = list[i++];
            var id = this.name + '-' + i;
            var item = this.createCustomListItem(obj, id);
            this.container.appendChild(item);
        }

        window.PageBus.publish('com.cec.web.QueryBuilder.' + this.name + '.onLoad', { name: this.name });
    },
    createCustomListItem: function(obj, id) {
        var cb = "<input type='checkbox' value='" + obj.value +
            "' name='" + this.name + "' id='" + id + "' onclick='pubCheckbox(this);' " +
            "title='" + obj.label + "' ";
        if (this.isDisabled)
            cb += "disabled='true'  />\n";
        else
            cb += "/>";

        cb += obj.label;

        var div = document.createElement('label');
        div.setAttribute('forName', id);
        div.setAttribute('for', id);
        div.innerHTML = cb;
        return div;
    },
    toggle: function(checkbox) {
        if (!checkbox || checkbox.type != 'checkbox') {
            return;
        }
        if (checkbox.checked) {
            checkbox.parentNode.setAttribute('class', 'selected');
            checkbox.parentNode.style.backgroundColor = '#c4e5f2';
        } else {
            checkbox.parentNode.removeAttribute('class');
            checkbox.parentNode.style.backgroundColor = 'transparent';
        }
    },
    handleClick: function(subj, msg, data) {
        this.toggle(msg.element);

        if (!this.hasAllOption) {
            var checkboxes = this.container.getElementsByTagName('input');
            var selected = 0;
            for (var i = 0; i < checkboxes.length; i++) {
                if (checkboxes[i].checked) {
                    selected++;
                    break;
                }
            }

            if (selected == 0) {
                checkboxes[this.defaultIndex].checked = true;
                this.toggle(checkboxes[this.defaultIndex]);
            }
            return;
        }

        if (msg.value == this.defaultValue) {
            this.reset();
        } else {
            var checkboxes = this.container.getElementsByTagName('input');
            checkboxes[this.defaultIndex].checked = false;
            this.toggle(checkboxes[this.defaultIndex]);
        }
    },
    setBulk: function(listValues) {
        function hasValue(value, list) {
            if (!list || list.length == 0 || !value || value.length == 0)
                return null;
            for (var i = 0; i < list.length; i++) {
                if (list[i] == value)
                    return true;
            }
            return false;
        }
        var actual = [];
        var checkboxes = this.container.getElementsByTagName('input');
        for (var i = 0; i < checkboxes.length; i++) {
            var cb = checkboxes[i];
            cb.checked = hasValue(cb.value, listValues);
            if (cb.checked) {
                actual.push(cb.value);
            }
            this.toggle(cb);
        }
        if (actual.length == 0) {
            var cb = checkboxes[this.defaultIndex];
            actual.push(cb.value);
            cb.checked = true;
            this.toggle(cb);
        }
        return actual;
    },
    reset: function() {
        var checkboxes = this.container.getElementsByTagName('input');
        for (var i = 0; i < checkboxes.length; i++) {
            checkboxes[i].checked = (i === this.defaultIndex);
            this.toggle(checkboxes[i]);
        }
    },
    disable: function() {
        if (this.isDisabled)
            return;
        this.reset();
        var checkboxes = this.container.getElementsByTagName('input');
        for (var i = 0; i < checkboxes.length; i++) {
            checkboxes[i].disabled = true;
        }
        this.isDisabled = true;
    },
    enable: function() {
        if (!this.isDisabled)
            return;
        var checkboxes = this.container.getElementsByTagName('input');
        for (var i = 0; i < checkboxes.length; i++) {
            checkboxes[i].disabled = false;
        }
        this.isDisabled = false;
    },
    addSubscriber: function(sub) {
        this.subscribers.push(sub);
    }
});

var QueryBuilder = Class.create({
    subscribers: [],
    Chemical: '',
    ChemicalDefault: '-1',
    ChemicalList: null,
    ChemicalName: 'chemical',
    ChemicalType: '',
    ChemicalTypeDefault: 'a',
    ChemicalTypeList: null,
    ChemicalTypeName: 'chemTypeId',
    ChemicalQuery: {},
    ChemicalQueryCounter: 0,
    Country: '',
    CountryName: 'country',
    CountryDefault: '-1',
    CountryList: null,
    DataSet: '',
    DataSetList: null,
    DataSetDefault: '0',
    DataSetName: 'dataset',
    Industries: null,
    Industry: null,
    IndustryList: null,
    IndustryName: 'industry',
    IndustryDefault: '0',
    IndustryOrderAlpha: false,
    Menu: 'wiz',
    Report: '',
    ReportName: 'report',
    ReportDefault: 'Facility',
    ReportList: null,
    States: [],
    State: '',
    StateDefault: '0',
    StateList: null,
    StateName: 'state',
    Storer: null,
    Tree: null,
    Year: '',
    YearDefault: '2005',
    YearList: null,
    YearName: 'year',
    Sections: [],
    Wiz: '',
    initialize: function() {
        this.Storer = new Storage();
        this.recentHash = 'mxyzptlk'; //to force a poll at start
        this.Tree = new QueryBuilderTree('qbParamTreeSection');
        this.ReportList = new CheckboxList(this.ReportName, this.ReportDefault);
        this.YearList = new CheckboxList(this.YearName, this.YearDefault);
        this.YearList.hasAllOption = false;
        this.CountryList = new CheckboxList(this.CountryName, this.CountryDefault);
        this.StateList = new CheckboxList(this.StateName, this.StateDefault);
        this.DataSetList = new CheckboxList(this.DataSetName, this.DataSetDefault);
        this.ChemicalTypeList = new CheckboxList(this.ChemicalTypeName, this.ChemicalTypeDefault);
        this.ChemicalList = new CheckboxList(this.ChemicalName, this.ChemicalDefault);
        this.IndustryList = new CheckboxList(this.IndustryName, this.IndustryDefault);

        //name, isInWizardView, isInAdvancedView
        this.Sections.push(new QbSection('qbWelcomeSection', true, false, false));
        this.Sections.push(new QbSection('qbReportSection', true, true));
        this.Sections.push(new QbSection('qbYearSection', true, true));
        this.Sections.push(new QbSection('qbLocationSection', true, true));
        this.Sections.push(new QbSection('qbChemicalSection', true, true));
        this.Sections.push(new QbSection('qbScopeSection', true, true));


        this.addSubcribers();
    },
    addSubcribers: function() {
        var ns = 'com.cec.web.QueryBuilder.';
        //window.PageBus.subscribe('com.cec.web.QueryBuilder.' + this.ReportName + '.onSelect', this, this.updateReportType, null);
        this.subscribers.push(window.PageBus.subscribe(ns + '*.onSelect', this, this.updateHash, null));
        this.subscribers.push(window.PageBus.subscribe(ns + this.StateName + '.onLoad', this, this.setStateAfterLoad, null));
        this.subscribers.push(window.PageBus.subscribe(ns + this.IndustryName + '.onLoad', this, this.setIndustryAfterLoad, null));
        this.subscribers.push(window.PageBus.subscribe(ns + this.ChemicalName + '.onLoad', this, this.setChemicalAfterLoad, null));
        this.subscribers.push(window.PageBus.subscribe('com.cec.web.QueryBuilder.Wizard.onToggle', this, this.setView, null));
        this.subscribers.push(window.PageBus.subscribe('com.cec.web.QueryBuilder.Industry.onToggle', this, this.sortIndustry, null));
        this.subscribers.push(window.PageBus.subscribe('com.cec.web.QueryBuilder.Wizard.onJump', this, this.resetViewButtons, null));
        this.subscribers.push(window.PageBus.subscribe('com.cec.web.QueryBuilder.Wizard.*', this, this.resetNavButtons, null));
    },
    prevSection: function() {
        for (var i = 1; i < this.Sections.length; i++) {
            if (this.Sections[i].isDisplayed && this.Sections[i].isInWizardView) {
                var other = this.Sections[i - 1];
                this.Wiz = other.name;
                this.setHashValue("wizPage", this.Wiz);
                return this.Wiz;
            }
        }
        return null;
    },
    nextSection: function() {
        for (var i = 0; i < this.Sections.length - 1; i++) {
            if (this.Sections[i].isDisplayed && this.Sections[i].isInWizardView) {
                var other = this.Sections[i + 1];
                this.Wiz = other.name;
                this.setHashValue("wizPage", this.Wiz);
                return this.Wiz;
            }
        }
        return null;
    },
    resetNavButtons: function(subj, msg, data) {
        if (msg.menuItem) {
            this.Menu = msg.menuItem;
        }
        if (msg.section) {
            this.Wiz = msg.section;
        }
        var showers = [];
        var hiders = [];
        switch (this.Menu) {
            case 'adv':
                hiders = ['qbStartButton', 'qbPrevButton', 'qbNextButton'];
                showers = ['qbSubmitButton', 'qbResetButton'];
                break;
            case 'wiz':
            default:
                if (!this.Wiz || this.Wiz.length == 0 || this.Wiz == 'qbWelcomeSection') {
                    showers = ['qbStartButton']
                    hiders = ['qbSubmitButton', 'qbResetButton', 'qbPrevButton', 'qbNextButton'];
                    //Element.hide($('qbParamTreeSection'));
                } else if (this.Wiz && this.Wiz == 'qbScopeSection') {
                    showers = ['qbPrevButton', 'qbSubmitButton', 'qbResetButton']
                    hiders = ['qbStartButton', 'qbNextButton'];
                } else {
                    showers = ['qbSubmitButton', 'qbResetButton', 'qbPrevButton', 'qbNextButton'];
                    hiders = ['qbStartButton'];
                    //Element.show($('qbParamTreeSection'));
                }
                break;
        }
        this.syncTree();

        this.showAll(showers);
        this.hideAll(hiders);
    },
    resetViewButtons: function(subj, msg, data) {
        this.Wiz = msg.section;
        this.setHashValue("wizPage", this.Wiz);
        this.Menu = "wiz";
        this.toggleMenuSelect(this.Menu);
        this.setHashValue("menu", this.Menu);
    },
    setView: function(subj, msg, data) {
        this.Menu = msg.menuItem;
        this.setHashValue('menu', this.Menu);
        this.toggleMenuSelect(this.Menu);

        for (var i = 0; i < this.Sections.length; i++) {
            this.Sections[i].isDisplayed = (this.Sections[i].name == this.Wiz);
        }
        this.syncTree();
        //get menu view and state view
        window.PageBus.publish('com.cec.web.QueryBuilder.Wizard.onNav', { state: this.Menu, section: this.Wiz });

    },
    setStateAfterLoad: function(subj, msg, data) {
        var actual = this.StateList.setBulk(this.State.split(',')).join();
        if (this.State != actual) {
            this.State = actual;
            this.setHashValue(this.StateName, this.State);
        }
        this.loadChemicals();
    },
    setIndustryAfterLoad: function(subj, msg, data) {
        this.IndustryList.setBulk(this.Industry.split(','));
    },
    setChemicalAfterLoad: function(subj, msg, data) {
        var actual = this.ChemicalList.setBulk(this.Chemical.split(',')).join();
        if (this.Chemical != actual) {
            this.Chemical = actual;
            this.setHashValue(this.ChemicalName, this.Chemical);
        }
    },
    updateHash: function(subj, msg, data) {
        var values = getValuesFromGroupName(msg.name);
        var v = values.join();
        this.setHashValue(msg.name, v);
        if (msg.name == this.CountryName) {
            this.Country = v;
            this.loadStates();
        } else if (msg.name == this.StateName) {
            this.State = v;
            this.loadChemicals();
        } else if (msg.name == this.YearName) {
            this.Year = v;
            this.loadChemicals();
        } else if (msg.name == this.DataSetName) {
            this.DataSet = v;
            this.loadChemicals();
        } else if (msg.name == this.ChemicalTypeName) {
            this.ChemicalType = v;
            this.loadChemicals();
        } else if (msg.name == this.ChemicalName) {
            this.Chemical = v;
        } else if (msg.name == this.IndustryName) {
            this.Industry = v;
        } else if (msg.name == this.ReportName) {
            this.Report = v;
            if (v === 'Country') {
                this.disableStates();
            } else {
                this.StateList.enable();
            }
        }
    },
    init: function() {
        this.poll();
        this.loadStates();
        this.initIndustries();
        //this.loadChemicals();
        this.Tree.updateAll();
    },
    poll: function() {
        if (builder.pollHash()) {
            builder.syncForm();
        }
    },
    hideAll: function(elemIds) {
        if (elemIds && elemIds.length > 0) {
            for (var i = 0; i < elemIds.length; i++) {
                var elemId = elemIds[i];
                if (elemId && elemId.length > 0) {
                    Element.hide($(elemId));
                }
            }
        }
    },
    showAll: function(elemIds) {
        if (elemIds && elemIds.length > 0) {
            for (var i = 0; i < elemIds.length; i++) {
                var elemId = elemIds[i];
                if (elemId && elemId.length > 0) {
                    Element.show($(elemId));
                }
            }
        }
    },

    setHashValue: function(key, value) {
        this.Storer.setHashValue(key, value);
        this.recentHash = window.location.hash;
    },
    syncTree: function() {
        if (this.Menu == 'wiz') {
            if (this.Wiz == 'qbWelcomeSection') {
                this.Tree.hide();
            } else {
                this.Tree.show();
            }
        } else {
            this.Tree.show();
        }
    },
    syncMenu: function() {
        if (!this.Menu || this.Menu.length == 0) {
            this.Menu = 'wiz';
        }
        if (!this.Wiz || this.Wiz.length == 0) {
            this.Wiz = 'qbWelcomeSection';
        }

        window.PageBus.publish('com.cec.web.QueryBuilder.Wizard.onToggle', { menuItem: this.Menu });
    },
    syncReport: function() {
        if (!this.Report || this.Report.length == 0) {
            this.Report = this.ReportDefault;
        }
        resetGroupByName(this.ReportName, this.Report);
    },
    syncYear: function() {
        if (!this.Year || this.Year.length == 0) {
            this.Year = this.YearDefault;
        }
        this.YearList.setBulk(this.Year.split(','));
    },
    syncCountry: function() {
        if (!this.Country || this.Country.length == 0) {
            this.Country = this.CountryDefault;
        }
        this.CountryList.setBulk(this.Country.split(','));
    },
    syncState: function() {
        if (!this.State || this.State.length == 0) {
            this.State = this.StateDefault;
        }
        this.StateList.setBulk(this.State.split(','));
    },
    syncChemical: function() {
        //dataset
        if (!this.DataSet || this.DataSet.length == 0) {
            this.DataSet = this.DataSetDefault;
        }
        this.DataSetList.setBulk(this.DataSet.split(','));
        //group
        if (!this.ChemicalType || this.ChemicalType.length == 0) {
            this.ChemicalType = this.ChemicalTypeDefault;
        }
        this.ChemicalTypeList.setBulk(this.ChemicalType.split(','));

        //chemicals
        if (!this.Chemical || this.Chemical.length == 0) {
            this.Chemical = this.ChemicalDefault;
        }
        this.ChemicalList.setBulk(this.Chemical.split(','));
    },
    syncIndustry: function() {
        if (!this.Industry || this.Industry.length == 0) {
            this.Industry = this.IndustryDefault;
        }
        this.IndustryList.setBulk(this.Industry.split(','));
    },
    syncForm: function() {
        this.syncMenu();
        this.syncTree();
        this.syncReport();
        this.syncYear();
        this.syncState();
        this.syncCountry();
        this.syncChemical();
        this.syncIndustry();
        if (this.Report == 'Country') {
            this.disableStates();
        }
    },
    disableStates: function() {
        this.StateList.disable();
        this.State = this.StateDefault;
        this.setHashValue(this.StateName, this.State);
        this.Tree.updateTree(this.StateName);
    },
    getProperty: function(hashes, key, defaultProperty) {
        //set chemicalType
        var property = "";
        if (hashes[key] && hashes[key].length > 0) {
            property = hashes[key];
        } else {
            property = getValuesFromGroupName(key)[0];
            if ((!property || property.length == 0) && defaultProperty)
                property = defaultProperty;
            this.setHashValue(key, property);
        }
        return property;
    },

    pollHash: function() {
        if (window.location.hash == this.recentHash) {
            return false;
        }
        this.recentHash = window.location.hash;
        var hashes = this.Storer.getHashes();

        //set menuItem;
        if (hashes['menu'] && hashes['menu'].length > 0) {
            this.Menu = hashes['menu'];
        }

        //set wizard page
        if (hashes['wizPage'] && hashes['wizPage'].length > 0) {
            this.Wiz = hashes['wizPage'];
        }
        if (!this.Wiz || (this.Wiz.length == 0)) {
            this.Wiz = 'qbWelcomeSection';
        }

        this.Report = this.getProperty(hashes, this.ReportName, this.ReportDefault);
        this.Year = this.getProperty(hashes, this.YearName, this.YearDefault);
        this.Country = this.getProperty(hashes, this.CountryName, this.CountryDefault);
        this.State = this.getProperty(hashes, this.StateName, this.StateDefault);
        this.DataSet = this.getProperty(hashes, this.DataSetName, this.DataSetDefault);
        this.ChemicalType = this.getProperty(hashes, this.ChemicalTypeName, this.ChemicalTypeDefault);
        this.Chemical = this.getProperty(hashes, this.ChemicalName, this.ChemicalDefault);
        this.Industry = this.getProperty(hashes, this.IndustryName, this.IndustryDefault);

        // URL has changed, update the UI accordingly.
        return true;
    },
    reset: function() {
        window.location.href = 'QueryBuilder.aspx';
    },
    run: function() {
        var hash = window.location.hash;
        hash = hash.replace('#', '?');
        hash = hash.gsub(/\|/, '&');
        
        //reset cookie values for the new report
        setCookie('pageNumber', 0);
        setCookie('sortCol', 'Name');
        setCookie('sortDir', 0);
        window.location = 'Results.aspx' + hash, 'QueryResult';
    },
    toggleMenuSelect: function(menu) {
        if (menu == 'adv') {
            $('adv').className = 'disabled';
            $('wiz').className = 'enabled';
        } else {
            $('wiz').className = 'disabled';
            $('adv').className = 'enabled';
        }

        this.toggleStepNumbers();
    },
    toggleStepNumbers: function() {
        var steps = ['qbStep1', 'qbStep2', 'qbStep3', 'qbStep4', 'qbStep5'];
        if ($('adv').className.include('disabled')) {
            this.hideAll(steps);
        }
        else {
            this.showAll(steps);
        }
    },
    updateChemicalQuery: function() {
        this.ChemicalQuery = {};
        if (this.Country && this.Country.length > 0) {
            this.ChemicalQuery.ViewAgencyIDs = this.Country.split(',');
        }
        if (this.DataSet && this.DataSet.length > 0) {
            this.ChemicalQuery.FilterAgencyIDs = this.DataSet.split(',');
        }
        if (this.State && this.State.length > 0) {
            this.ChemicalQuery.StateProvinceIDs = this.State.split(',');
        }
        if (this.ChemicalType && this.ChemicalType.length > 0) {
            this.ChemicalQuery.TypeCharsInclude = this.ChemicalType.split(',');
        }
        if (this.ChemicalType && this.ChemicalType.length > 0) {
            this.ChemicalQuery.TypeCharsExclude = ['a', 'g'];
        }
        if (this.Year && this.Year.length > 0) {
            this.ChemicalQuery.Years = this.Year.split(',');
        }
        this.ChemicalQuery.ID = this.ChemicalQueryCounter;
    },
    loadChemicals: function() {
        this.ChemicalQueryCounter++;
        $('chemicalCount').innerHTML = "<img alt='loading' src='./includes/img/throbber.gif' /> ";
        function onGetChemicalListCompleted(results) {
            if (results.Query.ID < builder.ChemicalQueryCounter) {
                return;
            }

            var chemicalCount = $('chemicalCount');
            if (chemicalCount) {
                chemicalCount.innerHTML = " (" + results.Count + ")";
            }

            var list = [];
            for (var i = 0; i < results.Chemicals.length; ) {
                var obj = results.Chemicals[i++];
                var id = builder.ChemicalName + '-' + i;
                var o = new CheckboxListItem();
                o.code = obj.Code;
                o.label = obj.Name;
                o.name = obj.Name;
                o.value = obj.ID;
                list.push(o);
            }
            builder.ChemicalList.load(list);
        }
        this.updateChemicalQuery();
        CEC.Service.IService1.GetChemicalList(this.Storer.getCulture(), this.ChemicalQuery, onGetChemicalListCompleted);
    },
    loadStates: function() {
        function load() {
            var list = [];
            var selectedCountries = [];
            var c = builder.Country;
            var isAllStates = false;
            if (!c || c.length == 0 || c.indexOf(builder.CountryDefault) > -1) {
                isAllStates = true;
            } else {
                selectedCountries = c.split(',');
            }

            for (var i = 0; i < builder.States.length; i++) {
                var obj = builder.States[i];
                if (isAllStates || builder.hasValue(selectedCountries, obj.CountryID)) {
                    var o = new CheckboxListItem();
                    o.label = obj.Name;
                    o.value = obj.ID;
                    list.push(o);
                }
            }
            builder.StateList.load(list);
        }
        function callback(results) {
            builder.States = results.States;
            load();
        }
        if (builder.States.length > 0) {
            load();
        } else {
            CEC.Service.IService1.GetStateList(this.Storer.getCulture(), {}, callback);
        }
    },
    hasValue: function(arrayOfValues, value) {
        if (!arrayOfValues || arrayOfValues.length == 0 || !value) {
            return false;
        }
        for (var i = 0; i < arrayOfValues.length; i++) {
            if (arrayOfValues[i].toString() == value.toString())
                return true;
        }
        return false;
    },
    sortIndustry: function(subj, msg, data) {
        if (this.Industries == null)
            return;
        var sortAlpha = (msg.sort.indexOf('Name') >= 0);
        builder.bindIndustryList(sortAlpha);
        builder.toggleButtons();
    },
    initIndustries: function() {
        this.loadIndustries();
        $('NameSort').className = 'disabled';
        $('CodeSort').className = 'enabled';
    },
    toggleButtons: function() {
        if (this.IndustryOrderAlpha) {
            $('NameSort').className = 'disabled';
            $('CodeSort').className = 'enabled';
        } else {
            $('NameSort').className = 'enabled';
            $('CodeSort').className = 'disabled';
        }
    },
    loadIndustries: function() {
        if (this.Industries != null)
            return;

        $('industryCount').innerHTML = "<img alt='loading' src='./includes/img/throbber.gif' /> ";
        function onCompleted(results) {
            var industryCount = $('industryCount');
            if (industryCount) {
                industryCount.innerHTML = " (" + results.Count + ")";
            }

            builder.Industries = new Array();
            for (var i = 0; i < results.Industries.length; ) {
                var obj = results.Industries[i++];
                var o = new CheckboxListItem();
                o.code = obj.Code;
                o.name = obj.Name;
                o.label = obj.Name;
                o.value = obj.ID;
                builder.Industries.push(o);
            }
            builder.bindIndustryList(true);
        }
        CEC.Service.IService1.GetIndustryList(this.Storer.getCulture(), { "Level": "3" }, onCompleted);
    },
    bindIndustryList: function(orderAlpha) {
        if (!this.Industries)
            return;

        if (this.IndustryOrderAlpha == orderAlpha)
            return;

        this.IndustryOrderAlpha = orderAlpha;

        if (orderAlpha) {
            this.Industries.sort(function(a, b) { return a.name.localeCompare(b.name); });
            for (var i = 0; i < this.Industries.length; i++) {
                this.Industries[i].label = this.Industries[i].getNameLabel();
            }
        } else {
            this.Industries.sort(function(a, b) { return a.code.localeCompare(b.code); });
            for (var i = 0; i < this.Industries.length; i++) {
                this.Industries[i].label = this.Industries[i].getCodeLabel();
            }
        }
        builder.IndustryList.load(builder.Industries);
    }
});
