﻿//Checkbox tree
MyChkBoxTree = function() {
    // The configuration for this panel must be set before
    // the superclass constructor is set; otherwise, the collapseMode
    // cannot be applied to the layout.  Hence, we must make sure the
    // configuration for the BorderLayout.Region properties are
    // applied on the Constructor call

    MyChkBoxTree.superclass.constructor.call(this, {
        id: 'tree-panel',
        //title:'Asset Selection',
        title: 'Historic Bridges',
        autoScroll: true,
        animate: true,
        containerScroll: true,
        collapsed: true,
        //Note that this load only works when the page is loaded from a web server NOT
        //from the local file system. Also when using a simple file url need 
        //to use the GET method not POST
        loader: new Ext.tree.TreeLoader()
    });
}

Ext.extend(MyChkBoxTree, Ext.tree.TreePanel, {
    initComponent: function() {
        MyChkBoxTree.superclass.initComponent.call(this);
        // set the root node
        var root = new Ext.tree.AsyncTreeNode({
            text: 'Select Assets Where..',
            draggable: false,
            id: 'source',
            iconCls: 'hide-icon',
            expanded: true,
            children: assetQueryTreeJson
        });

        this.setRootNode(root);
        // Add event handlers
        this.on({
            'checkchange': {
                fn: this.doCheckChange,
                scope: this
            }
        });

        this.on({
            'append': {
                fn: this.doAppend,
                scope: this
            }
        });

        this.on({
            'expandnode': {
                fn: this.doExpandNode,
                scope: this
            }
        });

        this.on({
            'expand': {
                fn: this.doExpandPanel,
                scope: this
            }
        });
    },
    /*
    Make the oncheck logic of the checkbox tree nodes support the following requirements:
    BR.1) If any parent node is checked then ALL immediate child nodes of that parent are checked
    BR.2) If any parent node is cleared then ALL immediate child nodes of the parent are cleared.
    BR.3) If the last cleared child node for a given parent node becomes checked, mark that parent node as checked.
    BR.4) If a child node is cleared and the parent node is checked then the parent should be cleared
    BR.5) The above conditions should hold true for all nodes within the entire tree.
    */
    doCheckChange: function(node, checked) {
        //apply business rules to enforce state of tree
        this.enforceRules(node);
    },
    doExpandPanel: function(p) {
        this.syncUI();
    },
    syncUI: function() {
        var root = this.getRootNode();
        //This method starts at the root of the tree and makes
        //sure all the ui check boxes are checked based on the 
        //status of the node.attributes.checked attribute
        root.cascade(function(n) {
            if (n.attributes) {
                n.getUI().toggleCheck(n.attributes.checked);
            }
        });
    },
    clearSelections: function() {
        var thiz = this;
        var root = this.getRootNode();
        //Cascade down the tree and clear all checked nodes
        root.cascade(function(n) {
            var nUI = n.getUI();
            nUI.toggleCheck(false);
            n.attributes.checked = false;
            if (nUI.clearValue) nUI.clearValue();
        });
        //ensure checkbox rules are enforced
        this.enforceRules(root);
    },

    enforceRules: function(node) {
        var node = node || this.getRootNode();
        //(BR.1/BR.2)Apply rules BR.1 and BR.2 by cascading down the tree and setting child nodes 
        //checked state to its parent nodes checked state. So as we cascade down the tree from the
        //node that has changed the parent nodes current checked state determines the child nodes
        //current state
        node.cascade(function(n) {
            if (!n.attributes) node.attributes = {};
            //Ignore oringinating node. Its checked state is already determined by the user 
            //clicking on the checked box
            if (n.id !== node.id) {
                var p = n.parentNode;
                if ((p) && (p.getUI().checkbox)) {
                    if (!p.attributes) p.attributes = {};
                    var pChecked = p.attributes.checked;
                    n.getUI().toggleCheck(pChecked);
                    n.attributes.checked = pChecked;
                } else if (n.attributes.checked) {
                    n.getUI().toggleCheck(n.attributes.checked);
                }
            }
        });

        //(BR.3/BR.4) Apply rules BR.3 and BR.4 by bubbling up the tree and setting parent nodes 
        //checked state based on the collective checked states of the parents children. 
        //So as we bubble the tree from the node that has changed the parent nodes current checked 
        //is determined by the child nodes current states
        node.bubble(function(n) {
            var p = n.parentNode;
            if ((p) && (p.getUI().checkbox)) {
                var parentChecked = true; //assumed checked unless we find a cleared child
                p.eachChild(function(c) {
                    if (!c.attributes) c.attributes = {};
                    if (!c.attributes.checked) parentChecked = false;
                    if (!parentChecked) return false; //Once we find a cleared child stop processing children
                });
                p.getUI().toggleCheck(parentChecked);
                if (!p.attributes) p.attributes = {};
                p.attributes.checked = parentChecked;
            }
        });
    },
    /*
    Enforce rules BR.1/BR.2 for child nodes that are just being appended.
    */
    doAppend: function(t, pNode, node, index) {
        var pChecked = pNode.getUI().isChecked();
        if (!node.attributes) node.attributes = {};
        node.attributes.checked = pChecked;
    },
    /*
    Enforce rules BR.1/BR.2 when a nodes is expanded.
    */
    doExpandNode: function(node) {
        var p = node.parentNode;
        if ((p) && (p.getUI().checkbox)) {
            var pChecked = p.getUI().isChecked();
            if (!node.attributes) node.attributes = {};
            node.attributes.checked = pChecked;

        }
    },

    toXmlNodes: function() {
        var root = this.getRootNode();
        var xmlNodes = new Array();
        xmlNodes.push('<filters>');
        root.cascade(function(n) {
            var checked = (n.attributes.checked == true) || false;
            var query = n.attributes.query || '';
            xmlNodes.push('<filter query="' + query + '" checked="' + checked + '" />');

        });
        xmlNodes.push('</filters>');
        return xmlNodes;

    },

    isHistoricBridgesSelected: function() {
        var isHistoric = false;
        var root = this.getRootNode();
        root.cascade(function(n) {
            var checked = (n.attributes.checked == true) || false;
            if (checked == true) {
                isHistoric = true;
            }
        });

        return isHistoric;
    }

});

//Asset Web Layout components

//Header Panel
var header = {
    xtype: 'box',
    region: 'north',
    el: 'head-panel',
    cls: 'head-panel-cls',
    height: 32
};

//Footer Panel

var footer = {
    xtype: 'box',
    region: 'south',
    el: 'foot-panel',
    cls: 'foot-panel-cls',
    height: 32
};

//Check box tree
var myChkBoxTree = new MyChkBoxTree();

var mainRespStore = new Ext.data.SimpleStore({
    fields: ['code', 'desc'],
    data: majorMainRespCdJson

});
var countyStore = new Ext.data.SimpleStore({
    fields: ['code', 'desc'],
    data: countyJson

});

// Active bridges form panel

ActiveFormPanel = function() {
    ActiveFormPanel.superclass.constructor.call(this, {

        title: 'Active bridges',
        width: 230,
        labelWidth: 75,
        collapsed: false,
        items: [

                        new Ext.form.ComboBox({
                            id: 'MajorMain',
                            fieldLabel: ' Maint Resp',
                            store: mainRespStore,
                            displayField: 'desc',
                            valueField: 'code',
                            typeAhead: true,
                            mode: 'local',
                            hideMode: 'offsets',
                            triggerAction: 'all',
                            emptyText: 'Select a Main Resp...',
                            selectOnFocus: true,
                            forceSelection: true,
                            listWidth: 150
                            
                        }),

                    new Ext.form.ComboBox({
                        id: 'County',
                        fieldLabel: 'County',
                        store: countyStore,
                        displayField: 'desc',
                        valueField: 'code',
                        typeAhead: true,
                        mode: 'local',
                        hideMode: 'offsets',
                        triggerAction: 'all',
                        emptyText: 'Select a county..',
                        selectOnFocus: true,
                        forceSelection: true,
                        listWidth: 150
                    }),

                   new Ext.form.TextField({
                       fieldLabel: 'Fips',
                       name: 'FipsCd',
                       id: 'FipsCd'
                   }),
                  new Ext.form.TextField({
                      fieldLabel: 'Route',
                      name: 'Route',
                      id: 'Route'
                  }),

                   new Ext.form.Checkbox({
                  labelStyle: 'width:220px',
                  fieldLabel: 'Posted Bridges < 100% Legal ',
                       name: 'PostedBridges',
                       id: 'PostedBridges'
                   }),

                    new Ext.form.Radio({
                        labelStyle: 'width:220px',
                        fieldLabel: 'Under Clearance < 13' + "'" + '6" (Cardinal)',
                        name: 'rbGroup',
                        checked: false,
                        id: 'ClearenceLessthan13'
                    }),
                     new Ext.form.Radio({
                         labelStyle: 'width:220px',
                         fieldLabel: 'Under Clearance >=13' + "'" + ' 6' + '" (Cardinal)',
                         name: 'rbGroup',
                         checked: false,
                         id: 'ClearenceGreaterthan13'
                     }),
                      new Ext.form.Radio({
                          labelStyle: 'width:220px',
                          fieldLabel: 'Under Clearance None',
                          name: 'rbGroup',
                          checked: false,
                          id: 'None'
                      })

                ]

    });

}   //end MyFormPanel

Ext.extend(ActiveFormPanel, Ext.FormPanel, {
    initComponent: function() {
        ActiveFormPanel.superclass.initComponent.call(this);
    },
    isActiveBridgesSelected: function() {
        var isActive = false;

        this.getForm().items.each(function(item) {
            if ('MajorMain' == item.getId() && item.getValue().trim().length > 0) {
                isActive = true;
            }
            if ('County' == item.getId() && item.getValue().trim().length > 0) {
                isActive = true;
            }

            if ('PostedBridges' == item.getId() && item.getValue() == true) {
                isActive = true;
            }
            if ('ClearenceLessthan13' == item.getId() && item.getValue() == true) {
                isActive = true;
            }
            if ('ClearenceGreaterthan13' == item.getId() && item.getValue() == true) {
                isActive = true;
            }
            if ('FipsCd' == item.getId() && item.getValue().length > 0) {
                isActive = true;
            }
            if ('Route' == item.getId() && item.getValue().length > 0) {
                isActive = true;
            }

        });

        return isActive;
    },
    createActiveXmlNodes: function() {

        var activeXmlNodes = new Array();

        activeXmlNodes.push('<activefilters>');
        this.getForm().items.each(function(item) {
            activeXmlNodes.push('<activefilter key=' + '"' + item.getId() + '" value="' + item.getValue() + '" />');
        });
        activeXmlNodes.push('</activefilters>');

        return activeXmlNodes;

    },
    clearActiveSelections: function() {

        this.getForm().items.each(function(item) {
            if ('MajorMain' == item.getId() && item.getValue().trim().length > 0) {
                item.setValue('');
            }
            if ('County' == item.getId() && item.getValue().trim().length > 0) {
                item.setValue('');
            }

            if ('PostedBridges' == item.getId() && item.getValue() == true) {
                item.setValue(false);
            }
            if ('ClearenceLessthan13' == item.getId() && item.getValue() == true) {
                item.setValue(false);
            }
            if ('ClearenceGreaterthan13' == item.getId() && item.getValue() == true) {
                item.setValue(false);
            }
            if ('None' == item.getId() && item.getValue() == true) {
                item.setValue(false);
            }
            if ('FipsCd' == item.getId() && item.getValue().trim().length > 0) {
                item.setValue('');
            }
            if ('Route' == item.getId() && item.getValue().trim().length > 0) {
                item.setValue('');
            }

        });

    }

}); //end  

// FormPanel

var myPanel = new ActiveFormPanel();

var accordionMenus = new Ext.Panel({
    region: 'center',
    layout: 'accordion',
    layoutConfig: {
        animate: true
    },
    items: [myChkBoxTree, myPanel]
});


var navBtnPanel = new Ext.Panel({
    region: 'south',
    height: 30,
    items: [
				{
				    xtype: 'button',
				    region: 'center',
				    text: 'Update Map',
				    minWidth: 50,
				    handler: function() { if (ASSETSWEB.AssetsMap) ASSETSWEB.AssetsMap.updateMap(); }
				}
			]
});

//TitlePanel (added to top of NavPanel)
var titlePanel = {
    xtype: 'panel',
    region: 'north',
    cls: 'app-title-cls',
    height: 88
};

//NavPanel
var navPanel = new Ext.Panel({ // raw
    region: 'west',
    layout: 'border',
    el: 'nav-panel',
    //width: 230,
    width: 250,
    minSize: 100,
    maxSize: 400,
    cls: 'nav-panel-cls',
    margins: '0 0 0 0',
    cmargins: '0 0 0 0',
    items: [
					titlePanel,
					accordionMenus
				    ],
    buttons: [
				        {
				            xtype: 'button',
				            text: 'Update Map',
				            minWidth: 50,
				            handler: function() { if (ASSETSWEB.AssetsMap) ASSETSWEB.AssetsMap.updateMap(); }
				        },
	                    {
	                        xtype: 'button',
	                        text: 'Clear',
	                        minWidth: 50,
	                        handler: function() {
	                            if (ASSETSWEB.AssetsMap) ASSETSWEB.AssetsMap.cleanup();
	                            myChkBoxTree.clearSelections();
	                            myPanel.clearActiveSelections();
	                        }
	                    }
					]
});


//Main Panel
var mainPanel = { // raw
    xtype: 'box',
    region: 'center',
    el: 'main-panel',
    cls: 'main-panel-cls',
    height: 400
};                 
