﻿/*fixing bug 22484 */

Ext.override(Ext.Window.DD, {
    startDrag: function() {
        
        var w = this.win;
        this.proxy = w.ghost();
        w.constrain = true;
        if (w.constrain !== false) {
            var so = w.el.shadowOffset;
            this.constrainTo(w.container, { right: so, left: so, bottom: so });
        } else if (w.constrainHeader !== false) {
            var s = this.proxy.getSize();
            this.constrainTo(w.container, { right: -(s.width - this.headerOffsets[0]), bottom: -(s.height - this.headerOffsets[1]) });
        }
    }

}
);


/**Fixing bug 22235
**/


Ext.override(Ext.grid.RowSelectionModel, {
handleMouseDown : function(g, rowIndex, e){
        if(e.button !== 0 || this.isLocked()){
            return;
        }
        var view = this.grid.getView();
        if(e.shiftKey && !this.singleSelect && this.last !== false){
            var last = this.last;
            this.selectRange(last, rowIndex, e.ctrlKey);
            this.last = last; // reset the last
            if (this.focusRow) view.focusRow(rowIndex);
        }else{
            var isSelected = this.isSelected(rowIndex);
            if(e.ctrlKey && isSelected){
                this.deselectRow(rowIndex);
            }else if(!isSelected || this.getCount() > 1){
                this.selectRow(rowIndex, e.ctrlKey || e.shiftKey);
               if(this.focusRow) view.focusRow(rowIndex);
            }
        }
    }

}
);

/**
fixing bug 19002
**/
Ext.dd.Registry = function() {
    var elements = {};
    var handles = {};
    var autoIdSeed = 0;

    var getId = function(el, autogen) {
        if (typeof el == "string") {
            return el;
        }
        var id = el.id;
        if (!id && autogen !== false) {
            id = "extdd-" + (++autoIdSeed);
            el.id = id;
        }
        return id;
    };

    return {
        /**
        * Resgister a drag drop element
        * @param {String/HTMLElement) element The id or DOM node to register
        * @param {Object} data (optional) An custom data object that will be passed between the elements that are involved
        * in drag drop operations.  You can populate this object with any arbitrary properties that your own code
        * knows how to interpret, plus there are some specific properties known to the Registry that should be
        * populated in the data object (if applicable):
        * <pre>
        Value      Description<br />
        ---------  ------------------------------------------<br />
        handles    Array of DOM nodes that trigger dragging<br />
        for the element being registered<br />
        isHandle   True if the element passed in triggers<br />
        dragging itself, else false
        </pre>
        */
        register: function(el, data) {

            data = data || {};
            if (typeof el == "string") {
                el = document.getElementById(el);
            }
            data.ddel = el;
            elements[getId(el)] = data;
            if (data.isHandle !== false) {
                handles[data.ddel.id] = data;
            }
            if (data.handles) {
                var hs = data.handles;
                for (var i = 0, len = hs.length; i < len; i++) {
                    handles[getId(hs[i])] = data;
                }
            }
        },

        /**
        * Unregister a drag drop element
        * @param {String/HTMLElement) element The id or DOM node to unregister
        */
        unregister: function(el) {
            var id = getId(el, false);
            var data = elements[id];
            if (data) {
                delete elements[id];
                if (data.handles) {
                    var hs = data.handles;
                    for (var i = 0, len = hs.length; i < len; i++) {
                        delete handles[getId(hs[i], false)];
                    }
                }
            }
        },

        /**
        * Returns the handle registered for a DOM Node by id
        * @param {String/HTMLElement} id The DOM node or id to look up
        * @return {Object} handle The custom handle data
        */
        getHandle: function(id) {
            if (typeof id != "string") { // must be element?
                id = id.id;
            }
            return handles[id];
        },

        /**
        * Returns the handle that is registered for the DOM node that is the target of the event
        * @param {Event} e The event
        * @return {Object} handle The custom handle data
        */
        getHandleFromEvent: function(e) {
            var t = Ext.lib.Event.getTarget(e);
            return t ? handles[t.id] : null;
        },

        /**
        * Returns a custom data object that is registered for a DOM node by id
        * @param {String/HTMLElement} id The DOM node or id to look up
        * @return {Object} data The custom data
        */
        getTarget: function(id) {
            if (typeof id != "string") { // must be element?
                id = id.id;
            }
            return elements[id];
        },

        /**
        * Returns a custom data object that is registered for the DOM node that is the target of the event
        * @param {Event} e The event
        * @return {Object} data The custom data
        */
        getTargetFromEvent: function(e, checkMarkup) {

        var t = Ext.lib.Event.getTarget(e);
        if (t != null && t.id == "ext-ddMarkup" && checkMarkup)
            t = t.parentNode;
        
        return t ? elements[t.id] || handles[t.id] : null;
        }
    };
} (); 

/* adding the function getSelection() to ext.grid.gridPanel after the migartin to extjs 3.1.1 */


Ext.override(Ext.grid.GridPanel, {
    getSelections: function() {        
        return this.getSelectionModel().getSelections();
    }

});


/* Bug: correct IE8 to use document.documentMode instead of just IE version (IE8 in Compatibility Mode using IE8 will state 7.00 as the browser version) */
if (Ext.isIE && document.documentMode === 8) {
	Ext.isIE7 = false;
	Ext.isIE8 = true;
}

/* Enhancement: Remove default stateful:true for all components (ExtJS 3.1.1) */
Ext.override(Ext.Component, { stateful: false });

Ext.override(Ext.Element, {
	/*	Bug: Avoid FF error on chrome elements (ExtJS 3.1.1) */
	contains: function(el) {
		if (!el) { return false; }
		try { return Ext.lib.Dom.isAncestor(this.dom, el.dom ? el.dom : el); }
		catch (e) { return false; }
	}
});


/*	Bug: getDom Override to avoid access denied bug (ExtJS 3.1.1) */
Ext.getDom = function(el,strict){
    if(!el || !document) return null;
    if (el.dom) return el.dom;
    if (!Ext.isString(el)) return el;
	/* Change: Fix issue with back button and IFRAME (while unloading page, would get Access Denied otherwise) */
	var e;
    try {
		e = document.getElementById(el);
	} catch(ex) {
		e = null;
	}
    // IE returns elements with the 'name' and 'id' attribute.
    // we do a strict check to return the element with only the id attribute
    if (e && Ext.isIE && strict) return el == e.getAttribute('id')? e: null;
    return e;
};

Ext.override(Ext.tree.TreeNodeUI, {
	//	Enhancement: Add Text Wraping to Tree Nodes (this.node.ownerTree.wrapText) (ExtJS 3.1.1)
	renderElements : function(n, a, targetNode, bulkRender){
        // add some indent caching, this helps performance when rendering a large tree
        this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';

		/* Change: Add wrapText property so white-space:normal */
        var cb = Ext.isBoolean(a.checked),
            nel,
            href = a.href ? a.href : Ext.isGecko ? "" : "#",
            buf = ['<li class="x-tree-node"><div ext:tree-node-id="',n.id,'" class="x-tree-node-el x-tree-node-leaf x-unselectable ', a.cls,'" unselectable="on"', (this.node.ownerTree && this.node.ownerTree.wrapText) ? ' style="white-space:normal"' : '', '>',
            '<span class="x-tree-node-indent">',this.indentMarkup,"</span>",
            '<img src="', this.emptyIcon, '" class="x-tree-ec-icon x-tree-elbow" />',
            '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon',(a.icon ? " x-tree-node-inline-icon" : ""),(a.iconCls ? " "+a.iconCls : ""),'" unselectable="on" />',
            cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : '/>')) : '',
            '<a hidefocus="on" class="x-tree-node-anchor" href="',href,'" tabIndex="1" ',
             a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", '><span unselectable="on">',n.text,"</span></a></div>",
            '<ul class="x-tree-node-ct" style="display:none;"></ul>',
            "</li>"].join('');


        if (bulkRender !== true && n.nextSibling && (nel = n.nextSibling.ui.getEl())) {
            this.wrap = Ext.DomHelper.insertHtml("beforeBegin", nel, buf);
        } else {
            this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf);
        }

        this.elNode = this.wrap.childNodes[0];
        this.ctNode = this.wrap.childNodes[1];
        var cs = this.elNode.childNodes;
        this.indentNode = cs[0];
        this.ecNode = cs[1];
        this.iconNode = cs[2];
        var index = 3;
        if (cb) {
            this.checkbox = cs[3];
            // fix for IE6
            this.checkbox.defaultChecked = this.checkbox.checked;
            index++;
        }
        this.anchor = cs[index];
        this.textNode = cs[index].firstChild;
    }
});

Ext.override(Ext.grid.CheckboxSelectionModel, {
	/* Enhancement: Full row checkbox selection */
	onMouseDown: function(e, t) {
	
		/* Change: for checksel even row select should keep the existing records */
		if (e.button === 0  || (!this.singleSelect && Ext.fly(t).hasClass('x-grid3-cell-inner'))) {
		
			e.stopEvent();
			var row = e.getTarget('.x-grid3-row');
			if (row) {
				var index = row.rowIndex;
				if (this.isSelected(index)) {
					this.deselectRow(index);
					
					/* Change:deselect checkbox header if selected */
					var hd = Ext.DomQuery.selectNode('.x-grid3-hd-checker', this.grid.view.innerHd);
					if (hd) Ext.fly(hd).removeClass('x-grid3-hd-checker-on');
					
				} else {
					this.selectRow(index, true);
					
					/* Change: Add */
					if (this.getCount() == this.grid.store.getCount()) {
						var hd = Ext.DomQuery.selectNode('.x-grid3-hd-checker', this.grid.view.innerHd);
						if (hd) Ext.fly(hd).addClass('x-grid3-hd-checker-on');
					}
					
				}
			}
		}
	} 
});

Ext.override(Ext.tree.TreeNode, {
	
	/* Bug: If childNodes is destroyed, don't iterate (ExtJS 3.1.1) */
    renderChildren: function(suppressEvent) {
		if (suppressEvent !== false) {
			this.fireEvent("beforechildrenrendered", this);
		}
		
		/* Change: ensure cs is not null */
		var cs = this.childNodes || [];
		
		for(var i = 0, len = cs.length; i < len; i++){
			cs[i].render(true);
		}
		this.childrenRendered = true;
	},
    
    
    /* Enhancement: overridden to provide emptyText feature for the ownerTree (ExtJS 3.1.1) */
    afterAdd : function(node, exists){
        if(this.childrenRendered){
            // bulk render if the node already exists
            node.render(exists);
			
            /* Change */
			if (this.ownerTree.emptyText			//	EmptyText enabled
			&& !(this.ownerTree.rootVisible)		//	Root is not visible
			&& this.childNodes.length == 1			//	A single child node
			&& this == this.ownerTree.root) {		//	This is the root node
				var bDom = this.ownerTree.body.dom;
				var child = Ext.fly(bDom.childNodes[1]).hasClass("x-grid-empty")? bDom.childNodes[1] :
							Ext.fly(bDom.childNodes[0]).hasClass("x-grid-empty")? bDom.childNodes[0] : null;
				if (child) bDom.removeChild(child);	//	remove empty text cell
			}
            
        }else if(exists){
            // make sure we update the indent
            node.renderIndent(true, true);
        }
    },

    /* Enhancement: overridden to support emptyText feature for the ownerTree (ExtJS 3.1.1) */
    removeChild: function(node,destroy) {
        this.ownerTree.getSelectionModel().unselect(node);
        Ext.tree.TreeNode.superclass.removeChild.apply(this, arguments);
        // only update the ui if we're not destroying
        if(!destroy){
            // if it's been rendered remove dom node
            if(node.ui.rendered){
                node.ui.remove();
            }
            if(this.childNodes.length < 1){
            
            /* Change */
            if (this.ownerTree.emptyText) this.ownerTree.applyEmptyText();
            
            this.collapse(false, false);
            } else {
                this.ui.updateExpandIcon();
            }
            if (!this.firstChild && !this.isHiddenRoot()) {
                this.childrenRendered = false;
            }
        }
        return node;
    }
});

Ext.override(Ext.tree.TreePanel,{
	
	/* Enhancement: To implement emptyText feature for Treepanel (3.1.1) */
	applyEmptyText: function() {
		if (this.emptyText && this.root.childNodes.length == 0 && (!this.rootVisible)) {
			this.body.createChild({ tag: 'div', cls: 'x-grid-empty', cn: { html: this.emptyText }, style: '' }, this.innerCt.dom);
		}
	},
    
	/* Enhancement: To implement emptyText feature for Treepanel (3.1.1) */
    renderRoot : function(){
        this.root.render();
        if(!this.rootVisible){
            this.root.renderChildren();
        }
        
		/* Change */
		this.applyEmptyText();
    }
});

Ext.override(Ext.tree.AsyncTreeNode, {
	/* Enhancement: emptyText feature for the ownerTree (ExtJS 3.1.1) */
	loadComplete : function(deep, anim, callback, scope){
        this.loading = false;
        this.loaded = true;
        this.ui.afterLoad(this);
        this.fireEvent("load", this);
        this.expand(deep, anim, callback, scope);
        
        /* Change */
        if (this.ownerTree!=null
        &&	this.ownerTree.emptyText
        &&	!(this.ownerTree.rootVisible)
        &&	this == this.ownerTree.root) {
            this.ownerTree.body.dom.removeChild(this.ownerTree.body.dom.childNodes[1]);
        }
    }
});

/* Resize Panel Component */
Ext.ResizePanel = Ext.extend(Ext.Panel, {
	constructor: function(config) {
		Ext.ResizePanel.superclass.constructor.apply(this, arguments);
		var t = this;
		var up = function() { t.update(); };
		if (window.addEventListener) {
			window.addEventListener("resize", up, false);
			window.addEventListener("unload", function() { window.removeEventListener("resize", up, false); }, false);
		} else if (window.attachEvent) {
			window.attachEvent("onresize", up);
			window.detachEvent("onunload", function() { window.removeEventListener("onresize", up); });
		}
	},
	update: function() {
		this.doLayout(true);
	}
});

/* Row Expander (Ext 3.1.1) */
Ext.ns('Ext.ux.grid');
Ext.ux.grid.RowExpander = Ext.extend(Ext.util.Observable, {
    expandOnEnter : true,
    expandOnDblClick : true,
    header : '',
    width : 20,
    sortable : false,
    fixed : true,
    menuDisabled : true,
    dataIndex : '',
    id : 'expander',
    lazyRender : true,
    enableCaching : true,

    constructor: function(config){
        Ext.apply(this, config);

        this.addEvents({
            beforeexpand: true,
            expand: true,
            beforecollapse: true,
            collapse: true
        });

        Ext.ux.grid.RowExpander.superclass.constructor.call(this);

        if(this.tpl){
            if(typeof this.tpl == 'string'){
                this.tpl = new Ext.Template(this.tpl);
            }
            this.tpl.compile();
        }

        this.state = {};
        this.bodyContent = {};
    },
	
    getRowClass : function(record, rowIndex, p, ds){
        p.cols = p.cols-1;
        var content = this.bodyContent[record.id];
        if(!content && !this.lazyRender){
            content = this.getBodyContent(record, rowIndex);
        }
        if(content){
            p.body = content;
        }
        return this.state[record.id] ? 'x-grid3-row-expanded' : 'x-grid3-row-collapsed';
    },

    init : function(grid){
        this.grid = grid;

        var view = grid.getView();
        view.getRowClass = this.getRowClass.createDelegate(this);

        view.enableRowBody = true;


        grid.on('render', this.onRender, this);
        grid.on('destroy', this.onDestroy, this);
    },

    // @private
    onRender: function() {
        var grid = this.grid;
        var mainBody = grid.getView().mainBody;
        mainBody.on('mousedown', this.onMouseDown, this, {delegate: '.x-grid3-row-expander'});
        if (this.expandOnEnter) {
            this.keyNav = new Ext.KeyNav(this.grid.getGridEl(), {
                'enter' : this.onEnter,
                scope: this
            });
        }
        if (this.expandOnDblClick) {
            grid.on('rowdblclick', this.onRowDblClick, this);
        }
    },
    
    // @private    
    onDestroy: function() {
        if(this.keyNav){
            this.keyNav.disable();
            delete this.keyNav;
        }
        /*
         * A majority of the time, the plugin will be destroyed along with the grid,
         * which means the mainBody won't be available. On the off chance that the plugin
         * isn't destroyed with the grid, take care of removing the listener.
         */
        var mainBody = this.grid.getView().mainBody;
        if(mainBody){
            mainBody.un('mousedown', this.onMouseDown, this);
        }
    },
    // @private
    onRowDblClick: function(grid, rowIdx, e) {
        this.toggleRow(rowIdx);
    },

    onEnter: function(e) {
        var g = this.grid;
        var sm = g.getSelectionModel();
        var sels = sm.getSelections();
        for (var i = 0, len = sels.length; i < len; i++) {
            var rowIdx = g.getStore().indexOf(sels[i]);
            this.toggleRow(rowIdx);
        }
    },

    getBodyContent : function(record, index){
        if(!this.enableCaching){
            return this.tpl.apply(record.data);
        }
        var content = this.bodyContent[record.id];
        if(!content){
            content = this.tpl.apply(record.data);
            this.bodyContent[record.id] = content;
        }
        return content;
    },

    onMouseDown : function(e, t){
        e.stopEvent();
        var row = e.getTarget('.x-grid3-row');
        this.toggleRow(row);
    },

    renderer : function(v, p, record){
        p.cellAttr = 'rowspan="2"';
        return '<div class="x-grid3-row-expander">&#160;</div>';
    },

    beforeExpand : function(record, body, rowIndex){
        if(this.fireEvent('beforeexpand', this, record, body, rowIndex) !== false){
            if(this.tpl && this.lazyRender){
                body.innerHTML = this.getBodyContent(record, rowIndex);
            }
            return true;
        }else{
            return false;
        }
    },

    toggleRow : function(row){
        if(typeof row == 'number'){
            row = this.grid.view.getRow(row);
        }
        this[Ext.fly(row).hasClass('x-grid3-row-collapsed') ? 'expandRow' : 'collapseRow'](row);
    },

    expandRow : function(row){
        if(typeof row == 'number'){
            row = this.grid.view.getRow(row);
        }
        var record = this.grid.store.getAt(row.rowIndex);
        var body = Ext.DomQuery.selectNode('tr:nth(2) div.x-grid3-row-body', row);
        if(this.beforeExpand(record, body, row.rowIndex)){
            this.state[record.id] = true;
            Ext.fly(row).replaceClass('x-grid3-row-collapsed', 'x-grid3-row-expanded');
            this.fireEvent('expand', this, record, body, row.rowIndex);
        }
    },

    collapseRow : function(row){
        if(typeof row == 'number'){
            row = this.grid.view.getRow(row);
        }
        var record = this.grid.store.getAt(row.rowIndex);
        var body = Ext.fly(row).child('tr:nth(1) div.x-grid3-row-body', true);
        if(this.fireEvent('beforecollapse', this, record, body, row.rowIndex) !== false){
            this.state[record.id] = false;
            Ext.fly(row).replaceClass('x-grid3-row-expanded', 'x-grid3-row-collapsed');
            this.fireEvent('collapse', this, record, body, row.rowIndex);
        }
    }
});
Ext.preg('rowexpander', Ext.ux.grid.RowExpander);

//backwards compat
Ext.grid.RowExpander = Ext.ux.grid.RowExpander;

/* File Upload Field (Ext 3.1.1) */
Ext.ns('Ext.ux.form');
/*!
 * Ext JS Library 3.1.1
 * Copyright(c) 2006-2010 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */
/**
 * @class Ext.ux.Spinner
 * @extends Ext.util.Observable
 * Creates a Spinner control utilized by Ext.ux.form.SpinnerField
 */
/*!
* Ext JS Library 3.1.1
* Copyright(c) 2006-2010 Ext JS, LLC
* licensing@extjs.com
* http://www.extjs.com/license
*/
/**
* @class Ext.ux.Spinner
* @extends Ext.util.Observable
* Creates a Spinner control utilized by Ext.ux.form.SpinnerField
*/
Ext.ux.Spinner = Ext.extend(Ext.util.Observable, {
    incrementValue: 1,
    alternateIncrementValue: 5,
    triggerClass: 'x-form-spinner-trigger',
    splitterClass: 'x-form-spinner-splitter',
    alternateKey: Ext.EventObject.shiftKey,
    defaultValue: 0,
    accelerate: false,

    constructor: function(config) {
        Ext.ux.Spinner.superclass.constructor.call(this, config);
        Ext.apply(this, config);
        this.mimicing = false;
    },

    init: function(field) {
        this.field = field;

        field.afterMethod('onRender', this.doRender, this);
        field.afterMethod('onEnable', this.doEnable, this);
        field.afterMethod('onDisable', this.doDisable, this);
        field.afterMethod('afterRender', this.doAfterRender, this);
        field.afterMethod('onResize', this.doResize, this);
        field.afterMethod('onFocus', this.doFocus, this);
        field.beforeMethod('onDestroy', this.doDestroy, this);
    },

    doRender: function(ct, position) {
        var el = this.el = this.field.getEl();
        var f = this.field;

        if (!f.wrap) {
            f.wrap = this.wrap = el.wrap({
                cls: "x-form-field-wrap"
            });
        }
        else {
            this.wrap = f.wrap.addClass('x-form-field-wrap');
        }

        this.trigger = this.wrap.createChild({
            tag: "img",
            src: Ext.BLANK_IMAGE_URL,
            cls: "x-form-trigger " + this.triggerClass
        });

        if (!f.width) {
            this.wrap.setWidth(el.getWidth() + this.trigger.getWidth());
        }

        this.splitter = this.wrap.createChild({
            tag: 'div',
            cls: this.splitterClass,
            style: 'width:13px; height:2px;'
        });
        this.splitter.setRight((Ext.isIE) ? 1 : 2).setTop(10).show();

        this.proxy = this.trigger.createProxy('', this.splitter, true);
        this.proxy.addClass("x-form-spinner-proxy");
        this.proxy.setStyle('left', '0px');
        this.proxy.setSize(14, 1);
        this.proxy.hide();
        this.dd = new Ext.dd.DDProxy(this.splitter.dom.id, "SpinnerDrag", {
            dragElId: this.proxy.id
        });

        this.initTrigger();
        this.initSpinner();
    },

    doAfterRender: function() {
        var y;
        if (Ext.isIE && this.el.getY() != (y = this.trigger.getY())) {
            this.el.position();
            this.el.setY(y);
        }
    },

    doEnable: function() {
        if (this.wrap) {
            this.wrap.removeClass(this.field.disabledClass);
        }
    },

    doDisable: function() {
        if (this.wrap) {
            this.wrap.addClass(this.field.disabledClass);
            this.el.removeClass(this.field.disabledClass);
        }
    },

    doResize: function(w, h) {
        if (typeof w == 'number') {
            this.el.setWidth(w - this.trigger.getWidth());
        }
        this.wrap.setWidth(this.el.getWidth() + this.trigger.getWidth());
    },

    doFocus: function() {
        if (!this.mimicing) {
            this.wrap.addClass('x-trigger-wrap-focus');
            this.mimicing = true;
            Ext.get(Ext.isIE ? document.body : document).on("mousedown", this.mimicBlur, this, {
                delay: 10
            });
            this.el.on('keydown', this.checkTab, this);
        }
    },

    // private
    checkTab: function(e) {
        if (e.getKey() == e.TAB) {
            this.triggerBlur();
        }
    },

    // private
    mimicBlur: function(e) {
        if (!this.wrap.contains(e.target) && this.field.validateBlur(e)) {
            this.triggerBlur();
        }
    },

    // private
    triggerBlur: function() {
        this.mimicing = false;
        Ext.get(Ext.isIE ? document.body : document).un("mousedown", this.mimicBlur, this);
        this.el.un("keydown", this.checkTab, this);
        this.field.beforeBlur();
        this.wrap.removeClass('x-trigger-wrap-focus');
        this.field.onBlur.call(this.field);
    },

    initTrigger: function() {
        this.trigger.addClassOnOver('x-form-trigger-over');
        this.trigger.addClassOnClick('x-form-trigger-click');
    },

    initSpinner: function() {
        this.field.addEvents({
            'spin': true,
            'spinup': true,
            'spindown': true
        });

        this.keyNav = new Ext.KeyNav(this.el, {
            "up": function(e) {
                e.preventDefault();
                this.onSpinUp();
            },

            "down": function(e) {
                e.preventDefault();
                this.onSpinDown();
            },

            "pageUp": function(e) {
                e.preventDefault();
                this.onSpinUpAlternate();
            },

            "pageDown": function(e) {
                e.preventDefault();
                this.onSpinDownAlternate();
            },

            scope: this
        });

        this.repeater = new Ext.util.ClickRepeater(this.trigger, {
            accelerate: this.accelerate
        });
        this.field.mon(this.repeater, "click", this.onTriggerClick, this, {
            preventDefault: true
        });

        this.field.mon(this.trigger, {
            mouseover: this.onMouseOver,
            mouseout: this.onMouseOut,
            mousemove: this.onMouseMove,
            mousedown: this.onMouseDown,
            mouseup: this.onMouseUp,
            scope: this,
            preventDefault: true
        });

        this.field.mon(this.wrap, "mousewheel", this.handleMouseWheel, this);

        this.dd.setXConstraint(0, 0, 10)
        this.dd.setYConstraint(1500, 1500, 10);
        this.dd.endDrag = this.endDrag.createDelegate(this);
        this.dd.startDrag = this.startDrag.createDelegate(this);
        this.dd.onDrag = this.onDrag.createDelegate(this);
    },

    onMouseOver: function() {
        if (this.disabled) {
            return;
        }
        var middle = this.getMiddle();
        this.tmpHoverClass = (Ext.EventObject.getPageY() < middle) ? 'x-form-spinner-overup' : 'x-form-spinner-overdown';
        this.trigger.addClass(this.tmpHoverClass);
    },

    //private
    onMouseOut: function() {
        this.trigger.removeClass(this.tmpHoverClass);
    },

    //private
    onMouseMove: function() {
        if (this.disabled) {
            return;
        }
        var middle = this.getMiddle();
        if (((Ext.EventObject.getPageY() > middle) && this.tmpHoverClass == "x-form-spinner-overup") ||
        ((Ext.EventObject.getPageY() < middle) && this.tmpHoverClass == "x-form-spinner-overdown")) {
        }
    },

    //private
    onMouseDown: function() {
        if (this.disabled) {
            return;
        }
        var middle = this.getMiddle();
        this.tmpClickClass = (Ext.EventObject.getPageY() < middle) ? 'x-form-spinner-clickup' : 'x-form-spinner-clickdown';
        this.trigger.addClass(this.tmpClickClass);
    },

    //private
    onMouseUp: function() {
        this.trigger.removeClass(this.tmpClickClass);
    },

    //private
    onTriggerClick: function() {
        if (this.disabled || this.el.dom.readOnly) {
            return;
        }
        var middle = this.getMiddle();
        var ud = (Ext.EventObject.getPageY() < middle) ? 'Up' : 'Down';
        this['onSpin' + ud]();
    },

    //private
    getMiddle: function() {
        var t = this.trigger.getTop();
        var h = this.trigger.getHeight();
        var middle = t + (h / 2);
        return middle;
    },

    //private
    //checks if control is allowed to spin
    isSpinnable: function() {
        if (this.disabled || this.el.dom.readOnly) {
            Ext.EventObject.preventDefault(); //prevent scrolling when disabled/readonly
            return false;
        }
        return true;
    },

    handleMouseWheel: function(e) {
        //disable scrolling when not focused
        if (this.wrap.hasClass('x-trigger-wrap-focus') == false) {
            return;
        }

        var delta = e.getWheelDelta();
        if (delta > 0) {
            this.onSpinUp();
            e.stopEvent();
        }
        else
            if (delta < 0) {
            this.onSpinDown();
            e.stopEvent();
        }
    },

    //private
    startDrag: function() {
        this.proxy.show();
        this._previousY = Ext.fly(this.dd.getDragEl()).getTop();
    },

    //private
    endDrag: function() {
        this.proxy.hide();
    },

    //private
    onDrag: function() {
        if (this.disabled) {
            return;
        }
        var y = Ext.fly(this.dd.getDragEl()).getTop();
        var ud = '';

        if (this._previousY > y) {
            ud = 'Up';
        } //up
        if (this._previousY < y) {
            ud = 'Down';
        } //down
        if (ud != '') {
            this['onSpin' + ud]();
        }

        this._previousY = y;
    },

    //private
    onSpinUp: function() {
        if (this.isSpinnable() == false) {
            return;
        }
        if (Ext.EventObject.shiftKey == true) {
            this.onSpinUpAlternate();
            return;
        }
        else {
            this.spin(false, false);
        }
        this.field.fireEvent("spin", this);
        this.field.fireEvent("spinup", this);
    },

    //private
    onSpinDown: function() {
        if (this.isSpinnable() == false) {
            return;
        }
        if (Ext.EventObject.shiftKey == true) {
            this.onSpinDownAlternate();
            return;
        }
        else {
            this.spin(true, false);
        }
        this.field.fireEvent("spin", this);
        this.field.fireEvent("spindown", this);
    },

    //private
    onSpinUpAlternate: function() {
        if (this.isSpinnable() == false) {
            return;
        }
        this.spin(false, true);
        this.field.fireEvent("spin", this);
        this.field.fireEvent("spinup", this);
    },

    //private
    onSpinDownAlternate: function() {
        if (this.isSpinnable() == false) {
            return;
        }
        this.spin(true, true);
        this.field.fireEvent("spin", this);
        this.field.fireEvent("spindown", this);
    },

    spin: function(down, alternate) {
        var v = parseFloat(this.field.getValue());
        var incr = (alternate == true) ? this.alternateIncrementValue : this.incrementValue;
        (down == true) ? v -= incr : v += incr;

        v = (isNaN(v)) ? this.defaultValue : v;
        v = this.fixBoundries(v);
        this.field.setRawValue(v);
    },

    fixBoundries: function(value) {
        var v = value;

        if (this.field.minValue != undefined && v < this.field.minValue) {
            v = this.field.minValue;
        }
        if (this.field.maxValue != undefined && v > this.field.maxValue) {
            v = this.field.maxValue;
        }

        return this.fixPrecision(v);
    },

    // private
    fixPrecision: function(value) {
        var nan = isNaN(value);
        if (!this.field.allowDecimals || this.field.decimalPrecision == -1 || nan || !value) {
            return nan ? '' : value;
        }
        return parseFloat(parseFloat(value).toFixed(this.field.decimalPrecision));
    },

    doDestroy: function() {
        if (this.trigger) {
            this.trigger.remove();
        }
        if (this.wrap) {
            this.wrap.remove();
            delete this.field.wrap;
        }

        if (this.splitter) {
            this.splitter.remove();
        }

        if (this.dd) {
            this.dd.unreg();
            this.dd = null;
        }

        if (this.proxy) {
            this.proxy.remove();
        }

        if (this.repeater) {
            this.repeater.purgeListeners();
        }
    }
});

//backwards compat
Ext.form.Spinner = Ext.ux.Spinner;
    
    /*!
 * Ext JS Library 3.1.1
 * Copyright(c) 2006-2010 Ext JS, LLC
 * licensing@extjs.com
 * http://www.extjs.com/license
 */


/**
 * @class Ext.ux.form.SpinnerField
 * @extends Ext.form.NumberField
 * Creates a field utilizing Ext.ux.Spinner
 * @xtype spinnerfield
 */
Ext.ux.form.SpinnerField = Ext.extend(Ext.form.NumberField, {
    actionMode: 'wrap',
    deferHeight: true,
    autoSize: Ext.emptyFn,
    onBlur: Ext.emptyFn,
    adjustSize: Ext.BoxComponent.prototype.adjustSize,

	constructor: function(config) {
		var spinnerConfig = Ext.copyTo({}, config, 'incrementValue,alternateIncrementValue,accelerate,defaultValue,triggerClass,splitterClass');

		var spl = this.spinner = new Ext.ux.Spinner(spinnerConfig);

		var plugins = config.plugins
			? (Ext.isArray(config.plugins)
				? config.plugins.push(spl)
				: [config.plugins, spl])
			: spl;

		Ext.ux.form.SpinnerField.superclass.constructor.call(this, Ext.apply(config, {plugins: plugins}));
	},

    // private
    getResizeEl: function(){
        return this.wrap;
    },

    // private
    getPositionEl: function(){
        return this.wrap;
    },

    // private
    alignErrorIcon: function(){
        if (this.wrap) {
            this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
        }
    },

    validateBlur: function(){
        return true;
    }
});

Ext.reg('spinnerfield', Ext.ux.form.SpinnerField);

//backwards compat
Ext.form.SpinnerField = Ext.ux.form.SpinnerField;

Ext.ux.form.FileUploadField = Ext.extend(Ext.form.TextField,  {
    buttonText: 'Browse...',
    buttonOnly: false,
    buttonOffset: 3,

    // private
    readOnly: true,

    /**
     * @hide
     * @method autoSize
     */
    autoSize: Ext.emptyFn,

    // private
    initComponent: function(){
        Ext.ux.form.FileUploadField.superclass.initComponent.call(this);

        this.addEvents(
            /**
             * @event fileselected
             * Fires when the underlying file input field's value has changed from the user
             * selecting a new file from the system file selection dialog.
             * @param {Ext.ux.form.FileUploadField} this
             * @param {String} value The file value returned by the underlying file input field
             */
            'fileselected'
        );
    },

    // private
    onRender : function(ct, position){
        Ext.ux.form.FileUploadField.superclass.onRender.call(this, ct, position);

        this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});
        this.el.addClass('x-form-file-text');
        this.el.dom.removeAttribute('name');
        this.createFileInput();

        var btnCfg = Ext.applyIf(this.buttonCfg || {}, {
            text: this.buttonText
        });
        this.button = new Ext.Button(Ext.apply(btnCfg, {
            renderTo: this.wrap,
            cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '')
        }));

        if(this.buttonOnly){
            this.el.hide();
            this.wrap.setWidth(this.button.getEl().getWidth());
        }

        this.bindListeners();
        this.resizeEl = this.positionEl = this.wrap;
    },
    
    bindListeners: function(){
        this.fileInput.on({
            scope: this,
            mouseenter: function() {
                this.button.addClass(['x-btn-over','x-btn-focus'])
            },
            mouseleave: function(){
                this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
            },
            mousedown: function(){
                this.button.addClass('x-btn-click')
            },
            mouseup: function(){
                this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
            },
            change: function(){
                var v = this.fileInput.dom.value;
                this.setValue(v);
                this.fireEvent('fileselected', this, v);    
            }
        }); 
    },
    
    createFileInput : function() {
        this.fileInput = this.wrap.createChild({
            id: this.getFileInputId(),
            name: this.name||this.getId(),
            cls: 'x-form-file',
            tag: 'input',
            type: 'file',
            size: 1
        });
    },
    
    reset : function(){
        this.fileInput.remove();
        this.createFileInput();
        this.bindListeners();
        Ext.ux.form.FileUploadField.superclass.reset.call(this);
    },

    // private
    getFileInputId: function(){
        return this.id + '-file';
    },

    // private
    onResize : function(w, h){
        Ext.ux.form.FileUploadField.superclass.onResize.call(this, w, h);

        this.wrap.setWidth(w);

        if(!this.buttonOnly){
            var w = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset;
            this.el.setWidth(w);
        }
    },

    // private
    onDestroy: function(){
        Ext.ux.form.FileUploadField.superclass.onDestroy.call(this);
        Ext.destroy(this.fileInput, this.button, this.wrap);
    },
    
    onDisable: function(){
        Ext.ux.form.FileUploadField.superclass.onDisable.call(this);
        this.doDisable(true);
    },
    
    onEnable: function(){
        Ext.ux.form.FileUploadField.superclass.onEnable.call(this);
        this.doDisable(false);

    },
    
    // private
    doDisable: function(disabled){
        this.fileInput.dom.disabled = disabled;
        this.button.setDisabled(disabled);
    },


    // private
    preFocus : Ext.emptyFn,

    // private
    alignErrorIcon : function(){
        this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
    }

});

Ext.reg('fileuploadfield', Ext.ux.form.FileUploadField);

// backwards compat
Ext.form.FileUploadField = Ext.ux.form.FileUploadField;

/* SEARCH FIELD (ExtJS 3.1.1) */
Ext.app.SearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent: function() {
        Ext.app.SearchField.superclass.initComponent.call(this);
        this.on('specialkey', function(f, e) {
            if (e.getKey() == e.ENTER) {
                this.onTrigger2Click();
            }
        }, this);
    },

    validationEvent: false,
    validateOnBlur: false,
    trigger1Class: 'x-form-clear-trigger',
    trigger2Class: 'x-form-search-trigger',
    hideTrigger1: true,
    width: 180,
    hasSearch: false,
    paramName: 'query',
    defaultParams: { limit: 50 },

    getStore: function() {
        return this.store;
    },

    reconfigure: function(store) {
        this.store = store;
    },

    onTrigger1Click: function() {	//	Clear Results
        if (this.hasSearch) {
            this.el.dom.value = '';
            var o = this.store.lastOptions.params || this.defaultParams;
            o.start = 0;
            this.store.baseParams = this.store.baseParams || {};
            this.store.baseParams[this.paramName] = '';
            o[this.paramName] = '';
            this.fireEvent('onClear', this);
            this.store.reload({ params: o });
            this.triggers[0].hide();
            this.hasSearch = false;
        }
    },

    onTrigger2Click: function() {	//	Search
        var v = this.getRawValue();
        if (v.length < 1) {
            this.onTrigger1Click();
            return;
        }
        var o = this.store.lastOptions.params || this.defaultParams;
        o.start = 0;
        this.store.baseParams = this.store.baseParams || {};        
        this.store.baseParams[this.paramName] = v;
        o[this.paramName] = v;
        this.fireEvent('onSearch', this, v);
        this.store.reload({ params: o });
        this.hasSearch = true;
        this.triggers[0].show();
    }
});

/* Check Column: Grid Plugin (ExtJS 3.1.1) */
Ext.grid.CheckColumn = function(config) {
	Ext.apply(this, config);
	if (!this.id) this.id = Ext.id();
	this.renderer = this.renderer.createDelegate(this);
};
Ext.grid.CheckColumn.prototype = {
	init: function(grid) {
		this.grid = grid;
		this.grid.on('render', function() {
			var view = this.grid.getView();
			view.mainBody.on('mousedown', this.onMouseDown, this);
		}, this);
	},

	onMouseDown: function(e, t) {
		if (t.className && t.className.indexOf('x-grid3-cc-' + this.id) != -1) {
			e.stopEvent();
			var index = this.grid.getView().findRowIndex(t);
			var record = this.grid.store.getAt(index);
			if (!this.readonly) {
			    record.set(this.dataIndex, !record.data[this.dataIndex]);
			} else {
			    record.reject(false);
			}			
		}
	},

	renderer: function(v, p, record) {
	    p.css += ' x-grid3-check-col-td';
	    if (v != null) {
	        return '<div class="x-grid3-check-col' + (v ? '-on' : '') + ' x-grid3-cc-' + this.id + '">&#160;</div>';
	    }
	    else return '<div>&#160;</div>';
	}
};

Ext.override(Ext.grid.GridView, {

	/* Enhancement: Allow Wrap Text (ExtJS 3.1.1) */
        initTemplates: function() {
        var ts = this.templates || {};
        if (!ts.master) {
            ts.master = new Ext.Template(
                    '<div class="x-grid3" hidefocus="true">',
                        '<div class="x-grid3-viewport">',
                            '<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{ostyle}">{header}</div></div><div class="x-clear"></div></div>',
                            '<div class="x-grid3-scroller"><div class="x-grid3-body" style="{bstyle}">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>',
                        '</div>',
                        '<div class="x-grid3-resize-marker">&#160;</div>',
                        '<div class="x-grid3-resize-proxy">&#160;</div>',
                    '</div>'
                );
        }
        if (!ts.header) {
            ts.header = new Ext.Template(
                '<table border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
                '<thead><tr class="x-grid3-hd-row">{cells}</tr></thead>',
                '</table>'
            );
        }

        if (!ts.hcell) {
            ts.hcell = new Ext.Template(
                '<td class="x-grid3-hd x-grid3-cell x-grid3-td-{id} {css}" style="{style}"><div {tooltip} {attr} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">', this.grid.enableHdMenu ? '<a class="x-grid3-hd-btn" href="#"></a>' : '',
                '{value}<img class="x-grid3-sort-icon" src="', Ext.BLANK_IMAGE_URL, '" />',
                '</div></td>'
            );
        }

        if (!ts.body) {
            ts.body = new Ext.Template('{rows}');
        }

        if (!ts.row) {
            ts.row = new Ext.Template(
                '<div class="x-grid3-row {alt}" style="{tstyle}"><table class="x-grid3-row-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
                '<tbody><tr>{cells}</tr>',
                (this.enableRowBody ? '<tr class="x-grid3-row-body-tr" style="{bodyStyle}"><td colspan="{cols}" class="x-grid3-body-cell" tabIndex="0" hidefocus="on"><div class="x-grid3-row-body">{body}</div></td></tr>' : ''),
                '</tbody></table></div>'
            );
        }
        if (!ts.cell) {
			
			/* Change */
            ts.cell = new Ext.Template(
				'<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} ',
				this.selectable ? 'x-selectable' : '',
				' {css}" style="{style}" tabIndex="0" {cellAttr}>',
				this.wrapText ?
				'<div class="x-grid3-cell-inner x-grid3-col-{id}"  style="white-space:normal;"'
				: '<div class="x-grid3-cell-inner x-grid3-col-{id}" ',
				' unselectable="on" {attr}>{value}</div>',
				'</td>'
			);
			
        }
        for (var k in ts) {
            var t = ts[k];
            if (t && Ext.isFunction(t.compile) && !t.compiled) {
                t.disableFormats = true;
                t.compile();
            }
        }

        this.templates = ts;
        this.colRe = new RegExp('x-grid3-td-([^\\s]+)', '');
    }
});

/* PANEL */
Ext.override(Ext.Panel, {

    /* Bug: Compatibility with PNGfix (firstChild returned VML tag instead of proper div) */
    getFrameWidth: function() {

        var w = this.el.getFrameWidth('lr') + this.bwrap.getFrameWidth('lr');

        if (this.frame) {
            /* Change: get elements by class name */
            var l = this.bwrap.first('.x-window-ml');
            if (l == null) {
                return w;
            }
            var r = l.first('.x-window-mr');
          



            w += (Ext.fly(l).getFrameWidth('l') + Ext.fly(r).getFrameWidth('r'));
            w += this.mc.getFrameWidth('lr');
        }
        return w;
    },
    
    /* Enchancement 3.1.1: Add autoWidthToolbars (bool) property */
    autoWidthToolbars:true,
    onResize : function(w, h){
        if(Ext.isDefined(w) || Ext.isDefined(h)){
            if(!this.collapsed){
                // First, set the the Panel's body width.
                // If we have auto-widthed it, get the resulting full offset width so we can size the Toolbars to match
                // The Toolbars must not buffer this resize operation because we need to know their heights.

                if(Ext.isNumber(w)){
                    this.body.setWidth(w = this.adjustBodyWidth(w - this.getFrameWidth()));
                } else if (w == 'auto') {
                    w = this.body.setWidth('auto').dom.offsetWidth;
                } else {
                    w = this.body.dom.offsetWidth;
                }
                
				if (!this.autoWidthToolbars) { //	Edit
				
					if(this.tbar){
						this.tbar.setWidth(w);
						if(this.topToolbar){
							this.topToolbar.setSize(w);
						}
					}
					if(this.bbar){
						this.bbar.setWidth(w);
						if(this.bottomToolbar){
							this.bottomToolbar.setSize(w);
							// The bbar does not move on resize without this.
							if (Ext.isIE) {
								this.bbar.setStyle('position', 'static');
								this.bbar.setStyle('position', '');
							}
						}
					}
					if(this.footer){
						this.footer.setWidth(w);
						if(this.fbar){
							this.fbar.setSize(Ext.isIE ? (w - this.footer.getFrameWidth('lr')) : 'auto');
						}
					}
                } //	Edit

                // At this point, the Toolbars must be layed out for getFrameHeight to find a result.
                if(Ext.isNumber(h)){
                    h = Math.max(0, this.adjustBodyHeight(h - this.getFrameHeight()));
                    this.body.setHeight(h);
                }else if(h == 'auto'){
                    this.body.setHeight(h);
                }

                if(this.disabled && this.el._mask){
                    this.el._mask.setSize(this.el.dom.clientWidth, this.el.getHeight());
                }
            }else{
                // Adds an event to set the correct height afterExpand.  This accounts for the deferHeight flag in panel
                this.queuedBodySize = {width: w, height: h};
                if(!this.queuedExpand && this.allowQueuedExpand !== false){
                    this.queuedExpand = true;
                    this.on('expand', function(){
                        delete this.queuedExpand;
                        this.onResize(this.queuedBodySize.width, this.queuedBodySize.height);
                    }, this, {single:true});
                }
            }
            this.onBodyResize(w, h);
        }
        this.syncShadow();
        Ext.Panel.superclass.onResize.call(this);
    }
});










/* CHECK BOX */ // Can we just use setValue? *Is this used?*
Ext.override(Ext.form.Checkbox,{
	/* Enhancement: adding a method to setChecked similar to Ext.menu.CheckItem */
	setChecked: function(state, suppressEvent) {
		if (window.console) console.log('Ext-Extension::Ext.form.CheckBox::setChecked', arguments);
		var checked = this.checked;
		this.checked = (state === true || state === 'true' || state == '1' || String(state).toLowerCase() == 'on');
		if(this.rendered){
			this.el.dom.checked = this.checked;
			this.el.dom.defaultChecked = this.checked;
			this.wrap[this.checked? 'addClass' : 'removeClass'](this.checkedCls);
		}
		this.checked = state;
		if (suppressEvent !== true) {
			this.fireEvent("checkchange", this, state);
		}
	}
});

/* COLUMN TREE (ExtJS 2.1.1) */
Ext.tree.ColumnTree = Ext.extend(Ext.tree.TreePanel, {
	lines: false,
	borderWidth: Ext.isBorderBox ? 0 : 2, // the combined left/right border for each cell
	cls: 'x-column-tree',

	onRender: function() {
	Ext.tree.ColumnTree.superclass.onRender.apply(this, arguments);
	
	this.root.on({
	    scope: this.el
                  , beforeload: this.el.mask.createDelegate(this.el, ['Loading...', 'x-mask-loading'])
                  , load: this.el.unmask
                  , loadexception: this.el.unmask
	});
		this.headers = this.body.createChild({ cls: 'x-tree-headers', style: '' }, this.innerCt.dom);

		var cols = this.columns, c;
		var colW = this.getColWidths();

		for (var i = 0, len = cols.length; i < len; i++) {
			c = cols[i];
			var el = this.headers.createChild({
				tag: 'span',
				cls: 'x-tree-hd ' + (c.cls ? c.cls + '-hd' : ''),
				cn: {
					cls: 'x-tree-hd-text',
					html: c.header
				},
				style: 'width:' + (colW[i] - this.borderWidth) + 'px;'
			});
		}
		this.headers.createChild({ cls: 'x-clear' });
	},

	getColWidths: function() {
		var cols = this.columns;
		var w, ws = [];
		var t = 0;
		var c = 0;
		for (var i = 0, iL = cols.length; i < iL; i++) {
			w = cols[i].width;
			if (!isNaN(w)) t += w;
			else c++;
			ws.push(w);
		}
		var m, tL = this.getInnerWidth() - t - this.borderWidth;
		var rL = tL;
		for (var i = ws.length; i-- > 0; ) {
			if (isNaN(ws[i])) {
				m = (/(\d+)\%/).exec(cols[i].width);
				w = m != null && !isNaN(m[1]) ? Math.min((m[1] / 100) * tL, rL) : rL / (c || 1);
				ws[i] = w;
				rL -= w;
				c--;
			}
		}
		return ws;
	}
});


/* COLUMN NODE UI (ExtJS 2.1.1) */
Ext.tree.ColumnNodeUI = Ext.extend(Ext.tree.TreeNodeUI, {
    focus: Ext.emptyFn, // prevent odd scrolling behavior

    onCheckChange: function(e) {
        
        //check/uncheck children
        var node, checked = this.isChecked();
        for (var i = this.node.childNodes.length; i-- > 0; ) {
            node = this.node.childNodes[i];
            if (node.ui) node.ui.toggleCheck(checked);
        }

        Ext.tree.ColumnNodeUI.superclass.onCheckChange.apply(this, arguments);
    },
    
    onClick: function(e)
    {var target=e.target;
    
    if(Ext.fly(target).hasClass('x-grid3-check-col-on'))
      {  Ext.fly(target).removeClass('x-grid3-check-col-on');
        Ext.fly(target).addClass('x-grid3-check-col')
        
        }
    else
    
    if(Ext.fly(target).hasClass('x-grid3-check-col'))
    {
        Ext.fly(target).removeClass('x-grid3-check-col');
        Ext.fly(target).addClass('x-grid3-check-col-on');
        
     }   
    else
    Ext.tree.ColumnNodeUI.superclass.onClick.apply(this, arguments);
  
    
    
    },

    renderElements: function(n, a, targetNode, bulkRender) {
        this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';

        var t = n.getOwnerTree();
        var cols = t.columns;
        var colW = t.getColWidths();
        var bw = t.borderWidth;
        var c = cols[0];
        var cb = typeof a.checked == 'boolean';


        var buf = [
             '<li class="x-tree-node"><div ext:tree-node-id="', n.id, '" class="x-tree-node-el x-tree-node-leaf ', a.cls, ' ', (c.cls ? c.cls : ''), '">',
                '<span class="x-tree-col" style="width:', colW[0] - bw, this.node.ownerTree.wrapText ? 'px;white-space:normal">' : 'px;">',
                    '<span class="x-tree-node-indent">', this.indentMarkup, "</span>",
                    '<img src="', this.emptyIcon, '" class="x-tree-ec-icon x-tree-elbow">',
                    cb ? ('<input class="x-tree-node-cb" type="checkbox" ' + (a.checked ? 'checked="checked" />' : '/>')) : '',
                    '<img src="', a.icon || this.emptyIcon, '" class="x-tree-node-icon', (a.icon ? " x-tree-node-inline-icon" : ""), (a.iconCls ? " " + a.iconCls : ""), '" unselectable="on">',
                    '<a hidefocus="on" class="x-tree-node-anchor" href="', a.href ? a.href : "#", '" tabIndex="1" ',
                    a.hrefTarget ? ' target="' + a.hrefTarget + '"' : "", '>',
                    '<span unselectable="on" class="', (c.cls ? c.cls : ''), '">', n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]), "</span></a>",
                "</span>"];

        for (var i = 1, len = cols.length; i < len; i++) {
            c = cols[i];

            buf.push('<span class="x-tree-col ', (c.cls ? c.cls : ''), '" style="width:', colW[i] - bw, 'px;">',
                        '<span class="x-tree-col-text">', (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]), "</span>",
                      "</span>");
        }
        buf.push(
            '<div class="x-clear"></div></div>',
            '<ul class="x-tree-node-ct" style="display:none;"></ul>',
            "</li>");

        if (bulkRender !== true && n.nextSibling && n.nextSibling.ui.getEl()) {
            this.wrap = Ext.DomHelper.insertHtml("beforeBegin", n.nextSibling.ui.getEl(), buf.join(""));
        } else {
            this.wrap = Ext.DomHelper.insertHtml("beforeEnd", targetNode, buf.join(""));
        }

        this.elNode = this.wrap.childNodes[0];
        this.ctNode = this.wrap.childNodes[1];
        var cs = this.elNode.firstChild.childNodes;
        this.indentNode = cs[0];
        this.ecNode = cs[1];
        var index = 2;
        if (cb) {
            this.checkbox = cs[2];
            //var node = this;
            //this.checkbox.onchange = function(e) {
            //console.log(node);
            //	if (node.hasChildren)
            //}
            // fix for IE6
            this.checkbox.defaultChecked = this.checkbox.checked;
            index++;
        }
        this.iconNode = cs[index++];
        this.anchor = cs[index];
        this.textNode = cs[index].firstChild;
    }
});

/* Enhancement: Used to redirect when AJAX request is sent to login page */
Ext.Ajax.on('requestcomplete', function(event, response) {

    // HTTP Status: 301, 302, 303, 307 = Redirect to "Location" field
    //	if (response.status == 301) window.top.location = response.getResponseHeader('Location');
    if (response.responseText.indexOf("View_root_Login_Index") > -1) { // the timeout message that should have been printed the page
        window.parent.location.replace("/Login"); // to the page which showed the timeout alert and then sent it to logon page
    }

    if (response.responseText.indexOf("View_Ondemand_Home_Index") > -1) { 
        window.parent.location.replace("/OnDemand/Home"); 
    }
    
}, this);

Ext.override(Ext.form.Action.Submit, {
	
	/* Enhancement: try catch to fix js error when decode syntax exception */
    handleResponse: function(response) {
        if (this.form.reader) {
            var rs = this.form.reader.read(response);
            var data = rs.records && rs.records[0] ? rs.records[0].data : null;
            return {
                success: rs.success,
                data: data
            };
        }
        var result;
        try {
            result = Ext.decode(response.responseText);
        } catch (e) {
            result = response.responseText;
        }

        return result;
    }
});

Ext.History = (function() {
    var iframe, hiddenField,
        ready = false,
        currentToken,
        ignoreNext = false;

    function getHash() {
        var href = top.location.href, i = href.indexOf("#");
        return i >= 0 ? href.substr(i + 1) : null;
    }

    function doSave() {
        hiddenField.value = currentToken;
    }

    function handleStateChange(token) {
        currentToken = token;
        if (!(token == ignoreNext)) {
            Ext.History.fireEvent('change', token);
        }
        ignoreNext = false;
    }

    function updateIFrame(token) {
        var html = ['<html><body><div id="state">', Ext.util.Format.htmlEncode(token), '</div></body></html>'].join('');
        try {
            var doc = iframe.contentWindow.document;
            doc.open();
            doc.write(html);
            doc.close();
            return true;
        } catch (e) {
            return false;
        }
    }

    function checkIFrame() {
        if (!iframe.contentWindow || !iframe.contentWindow.document) {
            setTimeout(checkIFrame, 10);
            return;
        }

        var doc = iframe.contentWindow.document,
            elem = doc.getElementById("state"),
            token = elem ? elem.innerText : null,
            hash = getHash();

        setInterval(function() {

            doc = iframe.contentWindow.document;
            elem = doc.getElementById("state");

            var newtoken = elem ? elem.innerText : null,
                newHash = getHash();

            if (newtoken !== token) {
                token = newtoken;
                handleStateChange(token);
                top.location.hash = token;
                hash = token;
                doSave();
            } else if (newHash !== hash) {
                hash = newHash;
                updateIFrame(newHash);
            }

        }, 50);

        ready = true;

        Ext.History.fireEvent('ready', Ext.History);
    }

    function startUp() {
        currentToken = hiddenField.value ? hiddenField.value : getHash();

        if (Ext.isIE && !Ext.isIE8) {
            checkIFrame();
        } else {
            var hash = getHash();
            setInterval(function() {
                var newHash = getHash();
                if (newHash !== hash) {
                    hash = newHash;
                    handleStateChange(hash);
                    doSave();
                }
            }, 50);
            ready = true;
            Ext.History.fireEvent('ready', Ext.History);
        }
    }

    return {

        /**
        * The id of the hidden field required for storing the current history token.
        * @type String
        * @property
        */
        fieldId: 'x-history-field',

        /**
        * The id of the iframe required by IE to manage the history stack.
        * @type String
        * @property
        */
        iframeId: 'x-history-frame',

        events: {},


        /**
        * Initialize the global History instance.
        * @param {Boolean} onReady (optional) A callback function that will be called once the history
        * component is fully initialized.
        * @param {Object} scope (optional) The scope (this reference) in which the callback is executed. Defaults to the browser window.
        */
        init: function(onReady, scope) {
            if (ready) {
                Ext.callback(onReady, scope, [this]);
                return;
            }
            if (!Ext.isReady) {
                Ext.onReady(function() {
                    Ext.History.init(onReady, scope);
                });
                return;
            }
            hiddenField = Ext.getDom(Ext.History.fieldId);
            if (Ext.isIE && !Ext.isIE8) {
                iframe = Ext.getDom(Ext.History.iframeId);
            }
            this.addEvents(

            /**
            * @event ready
            * Fires when the Ext.History singleton has been initialized and is ready for use.
            * @param {Ext.History} The Ext.History singleton.
            */
                'ready',

            /**
            * @event change
            * Fires when navigation back or forwards within the local page's history occurs.
            * @param {String} token An identifier associated with the page state at that point in its history.
            */
                'change'
            );
            if (onReady) {
                this.on('ready', onReady, scope, { single: true });
            }
            startUp();
        },


        /**
        * Add a new token to the history stack. This can be any arbitrary value, although it would
        * commonly be the concatenation of a component id and another id marking the specifc history
        * state of that component.  Example usage:
        * 

// Handle tab changes on a TabPanel
        tabPanel.on('tabchange', function(tabPanel, tab){
        Ext.History.add(tabPanel.id + ':' + tab.id);
        });

         * @param {String} token The value that defines a particular application-specific history state
        * @param {Boolean} preventDuplicates When true, if the passed token matches the current token
        * it will not save a new history step. Set to false if the same state can be saved more than once
        * at the same history stack location (defaults to true).
        */
        add: function(token, preventDup, suppressEvent) {
            if (preventDup !== false) {
                if (this.getToken() == token) {
                    return true;
                }
            }
            if (suppressEvent) {
                ignoreNext = token;
            }
            if (Ext.isIE && !Ext.isIE8) {
                return updateIFrame(token);
            } else {
                top.location.hash = token;
                return true;
            }
        },


        /**
        * Programmatically steps back one step in browser history (equivalent to the user pressing the Back button).
        */
        back: function() {
            history.go(-1);
        },


        /**
        * Programmatically steps forward one step in browser history (equivalent to the user pressing the Forward button).
        */
        forward: function() {
            history.go(1);
        },


        /**
        * Retrieves the currently-active history token.
        * @return {String} The token
        */
        getToken: function() {
            return ready ? currentToken : getHash();
        }
    };
})();
Ext.apply(Ext.History, new Ext.util.Observable());

Ext.override(Ext.data.Store, {
    sort: function(fieldName, dir) {
        var f = this.fields.get(fieldName);
        if (!f) {
            return false;
        }
        if (!dir) {
            if (this.sortInfo && this.sortInfo.field == f.name) { // toggle sort dir
                dir = (this.sortToggle[f.name] || 'ASC').toggle('ASC', 'DESC');
            } else {
                dir = f.sortDir;
            }
        }
        var st = (this.sortToggle) ? this.sortToggle[f.name] : null;
        var si = (this.sortInfo) ? this.sortInfo : null;

        this.sortToggle[f.name] = dir;
        this.sortInfo = { field: f.name, direction: dir };
        this.fireEvent('beforesort', this, this.sortInfo);
        if (!this.remoteSort) {
            this.applySort();
            this.fireEvent('datachanged', this);
        } else {
            if (!this.load(this.lastOptions)) {
                if (st) {
                    this.sortToggle[f.name] = st;
                }
                if (si) {
                    this.sortInfo = si;
                }
            }
        }
    }
    
});

Ext.override(Ext.grid.GridView, {
    updateHeaderSortState : function(){
        var state = this.ds.getSortState();
        if(!state){
            return;
        }
        if(!this.sortState || (this.sortState.field != state.field || this.sortState.direction != state.direction)){
            this.grid.fireEvent('sortchange', this.grid, state);
        }
        this.sortState = state;
        var sortColumn = this.cm.findColumnIndex(state.field);
        if(sortColumn != -1){
            var sortDir = state.direction;
            this.updateSortIcon(sortColumn, sortDir);
        }
    },
    
    updateSortIcon: function(col, dir) {
        var sc = this.sortClasses;
        var hds = this.mainHd.select('td').removeClass(sc);
        hds.item(col).addClass(sc[dir == 'DESC' ? 1 : 0]);
    }
});

Ext.override(Ext.form.HtmlEditor, {
    defaultLinkErrorMessage: 'The link is not valid.',

    createLink: function() {
        var url = prompt(this.createLinkText, this.defaultLinkValue);
        if (url && url != 'http:/' + '/' && url != 'https:/' + '/') {
            if (!this.urlCheck(url))
                url = 'http:/' + '/' + url;

            if (!this.urlCheck(url))
                alert(this.defaultLinkErrorMessage);
            else
                this.relayCmd('createlink', ("javascript:void%20window.open('" + url + "');"));
        }
    },

    urlCheck: function(str) {
        var v = new RegExp();
        v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
        if (!v.test(str)) {
            return false;
        }

        return true;
    }
});

/* Bug (Ext 3.1): IE, getBoundingClientRect called on an orphan element throws an error.  */
(function() {
	var libFlyweight,
		doc = document,	
        ROUND = Math.round,
		PARSEINT = parseInt;
	
	function fly(el) {
        if (!libFlyweight) {
            libFlyweight = new Ext.Element.Flyweight();
        }
        libFlyweight.dom = el;
        return libFlyweight;
    }
	
	Ext.lib.Dom.getXY = function(el) {
        var p, 
        	pe, 
        	b,
        	bt, 
        	bl,     
        	dbd,       	
        	x = 0,
        	y = 0, 
        	scroll,
        	hasAbsolute, 
        	bd = (doc.body || doc.documentElement),
        	ret = [0,0];
        	
        el = Ext.getDom(el);

        if(el != bd){
            if (el.getBoundingClientRect) {
                //	Edit: use (0,0) if exception occurs
                try {
					b = el.getBoundingClientRect();
				} catch(e) {
					b = { left:0, top:0 };
				}
				//	End Edit
                scroll = fly(document).getScroll();
                ret = [ROUND(b.left + scroll.left), ROUND(b.top + scroll.top)];
            } else {  
	            p = el;		
	            hasAbsolute = fly(el).isStyle("position", "absolute");
	
	            while (p) {
		            pe = fly(p);		
	                x += p.offsetLeft;
	                y += p.offsetTop;
	
	                hasAbsolute = hasAbsolute || pe.isStyle("position", "absolute");
	                		
	                if (Ext.isGecko) {		                    
	                    y += bt = PARSEINT(pe.getStyle("borderTopWidth"), 10) || 0;
	                    x += bl = PARSEINT(pe.getStyle("borderLeftWidth"), 10) || 0;	
	
	                    if (p != el && !pe.isStyle('overflow','visible')) {
	                        x += bl;
	                        y += bt;
	                    }
	                }
	                p = p.offsetParent;
	            }
	
	            if (Ext.isSafari && hasAbsolute) {
	                x -= bd.offsetLeft;
	                y -= bd.offsetTop;
	            }
	
	            if (Ext.isGecko && !hasAbsolute) {
	                dbd = fly(bd);
	                x += PARSEINT(dbd.getStyle("borderLeftWidth"), 10) || 0;
	                y += PARSEINT(dbd.getStyle("borderTopWidth"), 10) || 0;
	            }
	
	            p = el.parentNode;
	            while (p && p != bd) {
	                if (!Ext.isOpera || (p.tagName != 'TR' && !fly(p).isStyle("display", "inline"))) {
	                    x -= p.scrollLeft;
	                    y -= p.scrollTop;
	                }
	                p = p.parentNode;
	            }
	            ret = [x,y];
            }
     	}
        return ret
    }
})();