﻿//handles the
var QueryBuilderTree = Class.create({
    name: '',
    container: null,
    isDisplayed: false,
    ChemicalId: 'chemical',
    ChemicalTypeName: 'chemTypeId',
    CountryId: 'country',
    DataSetName: 'dataset',
    DataSetId: 'dataset',
    FormName: 'aspnetForm',
    IndustryId: 'industry',
    ReportName: 'report',
    StateId: 'state',
    YearName: 'year',
    initialize: function(name) {
        this.name = name;
        this.container = document.getElementById(this.name);
        this.updateAll();
        this.setSubscriptions();
    },
    hide: function() {
        if (this.isDisplayed) {
            if (this.container)
                this.container.style.display = 'none';
            else
                $(this.name).hide();
            this.isDisplayed = false;
        }
    },
    show: function() {
        if (!this.isDisplayed) {
            if (this.container)
                this.container.style.display = 'block';
            else
                $(this.name).show();
            this.isDisplayed = true;
        }
    },
    updateAll: function() {
        //initial updates
        this.updateTree(this.ReportName);
        this.updateTree(this.YearName);
        this.updateTree(this.CountryId);
        this.updateTree(this.StateId);
        this.updateTree(this.ChemicalId);
        this.updateTree(this.ChemicalTypeName);
        this.updateTree(this.DataSetName);
        this.updateTree(this.IndustryId);
    },
    setNode: function(tree, selections) {
        $(tree).innerHTML = '';
        for (var i = 0; i < selections.length; i++) {
            var item = document.createElement('li');
            item.appendChild(document.createTextNode(selections[i]));
            $(tree).appendChild(item);
        }
    },
    updateTree: function(n) {
        var elements = document.getElementsByName(n);
        var selections = [];
        for (var i = 0; i < elements.length; i++) {
            if (elements[i].checked) {
                selections.push(elements[i].title);
            }
        }
        if (selections.length == 0) {
            selections.push(elements[0].title);
        }
        var tree = n + 'Tree';
        this.setNode(tree, selections);
    },
    getDefaultTitle: function(elemId) {
        var elements = document.getElementsByName(elemId);
        return elements[0].title;
    },
    update: function(subj, msg, data) {
        var n = msg.name;
        this.updateTree(n);
        if (n == this.ReportName) {
            this.updateTree(this.StateId);
        }
    },
    setSubscriptions: function() {
        var subjectSelect = "com.cec.web.QueryBuilder.*.onSelect";
        var subjectLoad = "com.cec.web.QueryBuilder.*.onLoad";
        this.sub = window.PageBus.subscribe(subjectSelect, this, this.update, null);
        this.sub2 = window.PageBus.subscribe(subjectLoad, this, this.update, null);
    }
});
