/**************************************************************************************************************
	TAB TOOLBAR PLUGIN START
**************************************************************************************************************/

Ext.namespace('Ext.ux.InlineToolbarTabPanel');
Ext.ux.InlineToolbarTabPanel = Ext.extend(Ext.TabPanel, {
enableTabScroll:false

,onRender : function(ct, position){
	Ext.TabPanel.superclass.onRender.call(this, ct, position);
	
	if(this.plain){
		var pos = this.tabPosition == 'top' ? 'header' : 'footer';
		this[pos].addClass('x-tab-panel-'+pos+'-plain');
	}

	var st = this[this.stripTarget];
	var stripDom = st.dom;
	var tabs = '<td style="width:100%;border-right:0px;"><div id="td_tabs" style="height:26px;"></div></td>';
	var tbars = this.initialConfig.toolbars;
	var leftTbar, rightTbar;
	for (var i=0, maxi=tbars.length; i<maxi; i++) {
		if (tbars[i].align.toLowerCase() == 'left') {
			leftTbar = tbars[i];
		} else {
			rightTbar = tbars[i];
		}
	}

	var tbarWidth = (leftTbar == undefined ? 0 : leftTbar.width-1) + (rightTbar == undefined ? 0 : rightTbar.width-1)
	var tabWidth = parseInt(stripDom.style.width,10);

//	stripDom.style.width = (this.width-tbarWidth-2).toString() + 'px';
	stripDom.style.width = ((this.width || this.el.getWidth())-tbarWidth-2).toString() + 'px';
   
	var scrolloffset = 0;
	for(var i=0;i<this['header'].dom.childNodes.length;i++){
		if(stripDom.childNodes[i].className.indexOf('x-tab-scroller-right') >= 0 || stripDom.childNodes[i].className.indexOf('x-tab-scroller-left') >= 0){
			scrolloffset = scrolloffset + 19;
		}
	}
    
	var leftTbarId = (leftTbar) ? leftTbar.id : 'leftTbar';
	var rightTbarId = (rightTbar) ? rightTbar.id : 'rightTbar';
	var style = "border-top:0px solid #8DB2E3;height:26px;";
	var leftTool = '<td><div id="'+leftTbarId+'" class="x-tab-toolbar-wrap" style="border-left:0px solid #8DB2E3;'+style+'"></div></td>';
	var rightTool = '<td><div id="'+rightTbarId+'" class="x-tab-toolbar-wrap" style="border-right:0px solid #8DB2E3;'+style+'"></div></td>';
	var tableStart = '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
	var tableEnd = '</tr></table>';
	var table = tableStart + (leftTbar?leftTool:'') + tabs + (rightTbar?rightTool:'') + tableEnd;
	var parentNode = stripDom.parentNode;
	parentNode.removeChild(this[this.stripTarget].dom);
	Ext.DomHelper.insertFirst(parentNode, table);
	var tabs = Ext.get("td_tabs");
	tabs.dom.appendChild(stripDom);
	if (leftTbar) {
		new Ext.Panel({
			renderTo:leftTbarId
			,border:false
			,width:leftTbar.width
			,tbar: leftTbar.tbar
			,height:0
		});
	}
	if (rightTbar) {
			new Ext.Panel({
			renderTo:rightTbarId
			,border:false
			,width:rightTbar.width-1
//			,width:rightTbar.width-5
			,tbar: rightTbar.tbar
			,height:0
		});
	}	   

	this.stripWrap = st.createChild({cls:'x-tab-strip-wrap', cn:{
	  tag:'ul', cls:'x-tab-strip x-tab-strip-'+this.tabPosition}});
//	this['stripWrap'].dom.style.width = (this.width-tbarWidth-scrolloffset-2).toString() + 'px';    	   
	this['stripWrap'].dom.style.width = ((this.width || this.el.getWidth())-tbarWidth-scrolloffset-2).toString() + 'px';    	   
	
	this.stripSpacer = st.createChild({cls:'x-tab-strip-spacer'});
	
	this.strip = new Ext.Element(this.stripWrap.dom.firstChild);
	
	this.edge = this.strip.createChild({tag:'li', cls:'x-tab-edge'});
	this.strip.createChild({cls:'x-clear'});
	
	this.body.addClass('x-tab-panel-body-'+this.tabPosition);
	
	if(!this.itemTpl){
	  var tt = new Ext.Template(
		  '<li class="{cls}" id="{id}"><a class="x-tab-strip-close" onclick="return false;"></a>',
		  '<a class="x-tab-right" href="#" onclick="return false;"><em class="x-tab-left">',
		  '<span class="x-tab-strip-inner"><span class="x-tab-strip-text {iconCls}">{text}</span></span>',
		  '</em></a></li>'
	  );
	  tt.disableFormats = true;
	  tt.compile();
	  Ext.TabPanel.prototype.itemTpl = tt;
	}

	this.items.each(this.initTab, this);
}  

,adjustBodyWidth : function(w){
//	if(this.header){
//		this.header.setWidth(w);
//	}
	if(this.footer){
	  	this.footer.setWidth(w);
	}
	return w;
}	

});
Ext.reg('inlinetoolbartabpanel',Ext.ux.InlineToolbarTabPanel);


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


Ext.namespace('Ext.ux.InlineToolbarTabPanel2');
Ext.ux.InlineToolbarTabPanel2 = function(config) {
    Ext.apply(this, config);
    Ext.ux.InlineToolbarTabPanel2.superclass.constructor.call(this, config);
};
 
Ext.extend(Ext.ux.InlineToolbarTabPanel2, Ext.TabPanel, {
    inlineToolbar: null
    , toolbar: null
    , headerToolbar: true
    , titleCollapse: false
    , hideCollapseTool: true
    , afterRender: function() {
        Ext.ux.InlineToolbarTabPanel2.superclass.afterRender.call(this);
        if (!Ext.isEmpty(this.toolbar))
            this.setToolbar(this.toolbar);
    }
    , onResize : function() {
        Ext.ux.InlineToolbarTabPanel2.superclass.onResize.apply(this, arguments);
	   
        if (Ext.isEmpty(this.inlineToolbar)) return;
        
        var w = arguments[0]-this.tbContainer.getSize().width;
        var h = this.header.getHeight();
        
//        if (this.headerToolbar) w-=1;
		if (this.headerToolbar) h-=3;
        
        this.header.setWidth(w);
        this.inlineToolbar.setHeight(h);
        this.tbContainer.setHeight(h);
//	   this.body.setWidth(this.adjustBodyWidth(this.getSize().width - this.getFrameWidth()));
    }                
    , getToolbar : function() {
        return this.inlineToolbar;
    }
    , setToolbar : function(obj) {
        var tbStyle = {style: 'border-width:0px;' + (this.headerToolbar? 'padding:0px;padding-top:3px;background:transparent none;': '')};
        var cls;
        this.toolbar = obj;
        
        if (this.headerToolbar)
            cls = 'x-tab-panel-header' + (this.border? '':
                ' x-tab-panel-noborder x-tab-panel-header-noborder');
        else
            cls = 'x-tab-strip-wrap x-tab-strip-top';
        
        this.tbWrap = this.header.insertSibling({
            style: 'float:right;width:auto;z-index:99;border-left-width:0px;'
            , cls: cls
        });
        
        this.tbContainer = this.tbWrap.createChild({
            style: 'border-left-width:0px;border-top-width:0px;border-bottom-width:0px;border-right-width:0px;vertical-align:top;',
             tag: this.headerToolbar? 'ul': 'div'
            , cls: this.headerToolbar? 'x-tab-strip-top': 'x-tab-right x-tab-panel-header'
        });
        
        this.header.setStyle({borderrightwidth:'0px'});
        
        Ext.apply(this.toolbar, tbStyle);
        this.inlineToolbar = new Ext.Toolbar(this.toolbar);
        
        if (!this.headerToolbar) {
            this.inlineToolbar.removeClass('x-toolbar');
            this.inlineToolbar.addClass('x-tab-strip-inner');
        }
	   
        this.inlineToolbar.render(this.tbContainer);

//        this.onResize(this.getSize().width-(this.inlineToolbar.width != undefined ? this.inlineToolbar.width : 0));
	   this.onResize(this.getSize().width);
    }
}); 

/**************************************************************************************************************
	TAB TOOLBAR PLUGIN END
**************************************************************************************************************/



/**************************************************************************************************************
	COLUMNTREE EXTENSION - used for the "edit tabs" window 
	THIS IS ColumnNodeUI & ColumnTree for ext 3.0
**************************************************************************************************************/


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-A',
    
    onRender : function(){
        Ext.tree.ColumnTree.superclass.onRender.apply(this, arguments);
        this.headers = this.header.createChild({cls:'x-tree-headers-A'});
		
        var cols = this.columns, c;
        var totalWidth = 0;
        var scrollOffset = 19; // similar to Ext.grid.GridView default

        for(var i = 0, len = cols.length; i < len; i++){
             c = cols[i];
             totalWidth += c.width;
             this.headers.createChild({
                 cls:'x-tree-A-hd ' + (c.cls?c.cls+'-hd':''),
                 cn: {cls:'x-tree-A-hd-text', html: c.header},
                 style:'width:'+(c.width-this.borderWidth)+'px;'
             });
			test01 = this.headers;
        }
		//var test =  this.headers;
		//alert('innerHTML: ' + test.dom.innerHTML);
		//debugger;
        this.headers.createChild({cls:'x-clear-A'});
        // prevent floats from wrapping when clipped
        this.headers.setWidth(totalWidth+scrollOffset);
        this.innerCt.setWidth(totalWidth);
    }
});

Ext.tree.ColumnNodeUI = Ext.extend(Ext.tree.TreeNodeUI, {
    focus: Ext.emptyFn, // prevent odd scrolling behavior

    renderElements : function(n, a, targetNode, bulkRender){
        this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';

        var t = n.getOwnerTree();
        var cols = t.columns;
        var bw = t.borderWidth;
        var c = cols[0];
		//alert(c.width);
        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,'">',
                '<div class="x-tree-col" style="width:',c.width-bw,'px;">',
                    '<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">',
                    '<a hidefocus="on" class="x-tree-node-anchor" href="',a.href ? a.href : "#",'" tabIndex="1" ',
                    a.hrefTarget ? ' target="'+a.hrefTarget+'"' : "", '>',
                    '<span unselectable="on">', n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]),"</span></a>",
                "</div>"];
         for(var i = 1, len = cols.length; i < len; i++){
             c = cols[i];

            buf.push('<div class="x-tree-col ',(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
                        '<div class="x-tree-col-text">',(c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]),"</div>",
                      "</div>");
			/*buf.push('<div class="x-column-tree-A ',(c.cls?c.cls:''),'" style="width:',c.width-bw,'px;">',
                        '<div class="x-column-tree-A">',(c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex]),"</div>",
                      "</div>");*/
			
         }
         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];
        this.iconNode = cs[2];
        this.anchor = cs[3];
        this.textNode = cs[3].firstChild;
		
    }
});


Ext.tree.TabNodeUI = Ext.extend(Ext.tree.TreeNodeUI, {
    focus: Ext.emptyFn, // prevent odd scrolling behavior
	
    renderElements : function(n, a, targetNode, bulkRender){
		this.indentMarkup = n.parentNode ? n.parentNode.ui.getChildIndent() : '';
		this.emptyIcon = Ext.BLANK_IMAGE_URL;
		
		
		
        var t = n.getOwnerTree();
        var cols = t.columns;
        var bw = t.borderWidth;
        var c = cols[0];

        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 + '" style="height:22px">'
			 ,'<table width="99%" align="center"><tr><td width="100%" style="overflow:hidden;" valign="top">'
			 	,'<div class="x-tree-col" style="width:97%;overflow:hidden;" id="node_' + a.id + '">'					
			 		,'<span ></span>'
			 		,'<img src="' + this.emptyIcon + '" class="">'
			 		,'<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+'"' : "") + (a.onclick ? ' onClick=\''+a.onclick+'\'' : "") + ' style="overflow:hidden;">'
			 			,'<span unselectable="on" style="overflow:hidden;width:100%;overflow-x:hidden;overflow-y:hidden;">'
			 				, n.text || (c.renderer ? c.renderer(a[c.dataIndex], n, a) : a[c.dataIndex])
			 		,"</span></a>"
			 	,"</div></td>"];


			 var isFolder = false;


         for(var i = 1, len = cols.length; i < len; i++){
             c = cols[i];

			if(c.dataIndex == 'canEdit' && a[c.dataIndex] == 'Y'){
				 buf.push('<td><div class="x-tree-col '
						  	,(c.cls?c.cls:'')
							,'" style="width:'
							,c.width-bw
							,'px;">'
							,'<div class="x-tree-col-text" align="left"><img src="' + myRSNApath + 'images/tab_edit.png" '
							,'onclick="Javascript:handleTabEdit('+n.attributes.id+');" id="edit_tab_'+n.attributes.id+'"></div>'
						  	,"</div></td>");				
								
			}
         }
         buf.push(
            '<div class="x-clear"></div></tr></table></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 = document.getElementById('node_' + a.id).childNodes;
//        var cs = this.elNode.firstChild.childNodes;
        this.indentNode = cs[0];
        this.ecNode = cs[1];
        this.iconNode = cs[2];
        this.anchor = cs[3];
        this.textNode = cs[3].firstChild;
    }
});

/**************************************************************************************************************
	EDIT TABS EXTENSION END
**************************************************************************************************************/



/**************************************************************************************************************
	DATAVIEW PLUGINS (DD, drag select, label edit) START
**************************************************************************************************************/

/**
 * Create a DragZone instance for our JsonView
 */
ImageDragZone = function(view, config){
    this.view = view;
    ImageDragZone.superclass.constructor.call(this, view.getEl(), config);
};

Ext.extend(ImageDragZone, Ext.dd.DragZone, {
    // We don't want to register our image elements, so let's 
    // override the default registry lookup to fetch the image 
    // from the event instead
    getDragData : function(e){

        var target = e.getTarget('.thumb-wrap-1');
        if(target){
            var view = this.view;
		  
		  if(e.ctrlKey == false){
			  if(!view.isSelected(target)){
				 view.onClick(e);
			  }
		  }

		  var selIndexes = view.getSelectedIndexes();
		  var selected = false;
		  for(var i=0; i<selIndexes.length; i++){
			  if(selIndexes[i] == target.viewIndex){
				selected = true;  
			  }
		  }
		  
		  if(!selected){
			view.select(target.viewIndex);  
		  }
		  
            var selNodes = view.getSelectedNodes();
		  if(selNodes.length > 1){
			view.select(target.viewIndex);
			selNodes = view.getSelectedNodes();
		  }
		  
            var dragData = {
                nodes: selNodes
            };
		  
		 dragData.ddel = target.firstChild.firstChild; // the img element
		 dragData.single = true;
  
            if(selNodes.length == 1){
                dragData.ddel = target.firstChild.firstChild; // the img element
                dragData.single = true;
            }else{
                var div = document.createElement('div'); // create the multi element drag "ghost"
                div.className = 'multi-proxy';
                for(var i = 0, len = selNodes.length; i < len; i++){
                    div.appendChild(selNodes[i].firstChild.firstChild.cloneNode(true));
                    if((i+1) % 3 == 0){
                        div.appendChild(document.createElement('br'));
                    }
                }
                dragData.ddel = div;
                dragData.multi = true;
            }
		  
            return dragData;
        }
        return false;
    },

    // this method is called by the TreeDropZone after a node drop
    // to get the new tree node (there are also other way, but this is easiest)
    getTreeNode : function(){
        var treeNodes = [];
        var nodeData = this.view.getRecords(this.dragData.nodes);
        for(var i = 0, len = nodeData.length; i < len; i++){
            var data = nodeData[i].data;
		  	var tree = getActiveFileTree();
			var node = (tree.id=='editFilesTree' ? tree.getNodeById(data.mm_key) : tree.getNodeById(data.bm_id));
//			var node = tree.getNodeById(data.mm_key);
			treeNodes.push(node);

        }
        return treeNodes;
    },
 		

    // the default action is to "highlight" after a bad drop
    // but since an image can't be highlighted, let's frame it 
    afterRepair:function(){
        for(var i = 0, len = this.dragData.nodes.length; i < len; i++){
            Ext.fly(this.dragData.nodes[i]).frame('##8db2e3', 1);
        }
        this.dragging = false;    
    },
    
    // override the default repairXY with one offset for the margins and padding
    getRepairXY : function(e){
        if(!this.dragData.multi){
            var xy = Ext.Element.fly(this.dragData.ddel).getXY();
            xy[0]+=3;xy[1]+=3;
            return xy;
        }
        return false;
    }
});




Ext.DataView.DragSelector = function(cfg){
    cfg = cfg || {};
    var view, regions, proxy, tracker;
    var rs, bodyRegion, dragRegion = new Ext.lib.Region(0,0,0,0);
    var dragSafe = cfg.dragSafe === true;

    this.init = function(dataView){
        view = dataView;
        view.on('render', onRender);
    };

    function fillRegions(){
        rs = [];
        view.all.each(function(el){
            rs[rs.length] = el.getRegion();
        });
        bodyRegion = view.el.getRegion();
    }

    function cancelClick(){
        return false;
    }

    function onBeforeStart(e){
        return !dragSafe || e.target == view.el.dom;
    }

    function onStart(e){
        view.on('containerclick', cancelClick, view, {single:true});
        if(!proxy){
            proxy = view.el.createChild({cls:'x-view-selector'});
        }else{
            proxy.setDisplayed('block');
        }
        fillRegions();
        view.clearSelections();
    }

    function onDrag(e){
        var startXY = tracker.startXY;
        var xy = tracker.getXY();

        var x = Math.min(startXY[0], xy[0]);
        var y = Math.min(startXY[1], xy[1]);
        var w = Math.abs(startXY[0] - xy[0]);
        var h = Math.abs(startXY[1] - xy[1]);

        dragRegion.left = x;
        dragRegion.top = y;
        dragRegion.right = x+w;
        dragRegion.bottom = y+h;

        dragRegion.constrainTo(bodyRegion);
        proxy.setRegion(dragRegion);

        for(var i = 0, len = rs.length; i < len; i++){
            var r = rs[i], sel = dragRegion.intersect(r);
            if(sel && !r.selected){
                r.selected = true;
                view.select(i, true);
            }else if(!sel && r.selected){
                r.selected = false;
                view.deselect(i);
            }
        }
    }

    function onEnd(e){
        if(proxy){
            proxy.setDisplayed(false);
        }
    }

    function onRender(view){
        tracker = new Ext.dd.DragTracker({
            onBeforeStart: onBeforeStart,
            onStart: onStart,
            onDrag: onDrag,
            onEnd: onEnd
        });
        tracker.initEl(view.el);
    }
};



Ext.DataView.LabelEditor = function(cfg, field){
    Ext.DataView.LabelEditor.superclass.constructor.call(this,
        field || new Ext.form.TextField({
            allowBlank: false,
            growMin:90,
            growMax:240,
            grow:true,
            selectOnFocus:true
        }), cfg
    );
}

Ext.extend(Ext.DataView.LabelEditor, Ext.Editor, {
    alignment: "tl-tl",
    hideEl : false,
    cls: "x-small-editor",
    shim: false,
    completeOnEnter: true,
    cancelOnEsc: true,
    labelSelector: 'span.x-editable',

    init : function(view){
        this.view = view;
        view.on('render', this.initEditor, this);
        this.on('complete', this.onSave, this);
    },

    initEditor : function(){
        this.view.getEl().on('mousedown', this.onMouseDown, this, {delegate: this.labelSelector});
    },

    onMouseDown : function(e, target){
        if(!e.ctrlKey && !e.shiftKey){
            var item = this.view.findItemFromChild(target);
            e.stopEvent();
            var record = this.view.store.getAt(this.view.indexOf(item));
            this.startEdit(target, record.data[this.dataIndex]);
            this.activeRecord = record;
        }else{
            e.preventDefault();
        }
    },

    onSave : function(ed, value){
        this.activeRecord.set(this.dataIndex, value);
    }
});





/**************************************************************************************************************
	DATAVIEW DRAG PLUGIN END
**************************************************************************************************************/



/**************************************************************************************************************
	MISC FIELD PLUGIN START
**************************************************************************************************************/

/**
 * @class Ext.form.MiscField
 * @extends Ext.BoxComponent
 * Base class to easily display simple text in the form layout.
 * @constructor
 * Creates a new MiscField Field
 * @param {Object} config Configuration options
 */
Ext.form.MiscField = function(config){
    Ext.form.MiscField.superclass.constructor.call(this, config);
};

Ext.extend(Ext.form.MiscField, Ext.BoxComponent,  {
    /**
     * @cfg {String/Object} autoCreate A DomHelper element spec, or true for a default element spec (defaults to
     * {tag: "div"})
     */
    defaultAutoCreate : {tag: "div"},

    /**
     * @cfg {String} fieldClass The default CSS class for the field (defaults to "x-form-field")
     */
    fieldClass : "x-form-field",

    // private
    isFormField : true,

    /**
     * @cfg {Mixed} value A value to initialize this field with.
     */
    value : undefined,

    /**
     * @cfg {Boolean} disableReset True to prevent this field from being reset when calling Ext.form.Form.reset()
     */
    disableReset: false,

    /**
     * @cfg {String} name The field's HTML name attribute.
     */
    /**
     * @cfg {String} cls A CSS class to apply to the field's underlying element.
     */

    // private ??
    initComponent : function(){
        Ext.form.MiscField.superclass.initComponent.call(this);
    },

    /**
     * Returns the name attribute of the field if available
     * @return {String} name The field name
     */
    getName: function(){
         return this.rendered && this.el.dom.name ? this.el.dom.name : (this.hiddenName || '');
    },

    // private
    onRender : function(ct, position){
        Ext.form.MiscField.superclass.onRender.call(this, ct, position);
        if(!this.el){
            var cfg = this.getAutoCreate();
            if(!cfg.name){
                cfg.name = this.name || this.id;
            }
            this.el = ct.createChild(cfg, position);
        }

        this.el.addClass([this.fieldClass, this.cls]);
        this.initValue();
    },


    // private
    initValue : function(){
        if(this.value !== undefined){
            this.setRawValue(this.value);
        }else if(this.el.dom.innerHTML.length > 0){
            this.setRawValue(this.el.dom.innerHTML);
        }
    },

    /**
     * Returns true if this field has been changed since it was originally loaded.
     */
    isDirty : function() {
        return String(this.getRawValue()) !== String(this.originalValue);
    },

    // private
    afterRender : function(){
        Ext.form.MiscField.superclass.afterRender.call(this);
        this.initEvents();
    },

    /**
     * Resets the current field value to the originally-loaded value
     * @param {Boolean} force Force a reset even if the option disableReset is true
     */
    reset : function(force){
        if(!this.disableReset || force === true){
            this.setRawValue(this.originalValue);
        }
    },

    // private
    initEvents : function(){
        // reference to original value for reset
        this.originalValue = this.getRawValue();
    },

    /**
     * Returns whether or not the field value is currently valid
     * Always returns true, not used in MiscField.
     * @return {Boolean} True
     */
    isValid : function(){
        return true;
    },

    /**
     * Validates the field value
     * Always returns true, not used in MiscField.  Required for Ext.form.Form.isValid()
     * @return {Boolean} True
     */
    validate : function(){
        return true;
    },

    processValue : function(value){
        return value;
    },

    // private
    // Subclasses should provide the validation implementation by overriding this
    validateValue : function(value){
        return true;
    },

    /**
     * Mark this field as invalid
     * Not used in MiscField.  Required for Ext.form.Form.markInvalid()
     */
    markInvalid : function(){
        return;
    },

    /**
     * Clear any invalid styles/messages for this field
     * Not used in MiscField.  Required for Ext.form.Form.clearInvalid()
     */
    clearInvalid : function(){
        return;
    },

    /**
     * Returns the raw field value.
     * @return {Mixed} value The field value
     */
    getRawValue : function(){
        return this.el.dom.innerHTML;
    },

    /**
     * Returns the clean field value - plain text only, strips out HTML tags.
     * @return {Mixed} value The field value
     */
    getValue : function(){
        var f = Ext.util.Format;
        var v = f.trim(f.stripTags(this.getRawValue()));
        return v;
    },

    /**
     * Sets the raw field value.
     * @param {Mixed} value The value to set
     */
    setRawValue : function(v){
        this.value = v;
        if(this.rendered){
            this.el.dom.innerHTML = v;
        }
    },

    /**
     * Sets the clean field value - plain text only, strips out HTML tags.
     * @param {Mixed} value The value to set
     */
    setValue : function(v){
        var f = Ext.util.Format;
	this.setRawValue(f.trim(f.stripTags(v)));
    }
});

Ext.ComponentMgr.registerType('miscfield', Ext.form.MiscField);

/**************************************************************************************************************
	MISC FIELD PLUGIN END
**************************************************************************************************************/



/**************************************************************************************************************
	COMBOBOX PLUGINS START
**************************************************************************************************************/


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
	,paramName:'query'

    ,onTrigger1Click : function(theevent){
		this.triggers[0].hide();
		this.el.dom.value = '';
		if(this.el.dom.id == 'bm_search'){
			document.getElementById('my_bookmarks_div').innerHTML = '';
			create_my_bookmarks();		
		}else if(this.el.dom.id.substring(0,18) == 'radlex_searchfield'){
			var winid = this.el.dom.id.substring(18);
			var treepanel = Ext.getCmp('radlex_browser'+winid);
			var loader = treepanel.getLoader();
			var root = treepanel.getRootNode();
			loader.baseParams.ACTION = '';
			loader.baseParams.q = '';
			loader.load(root);
		}else if(this.el.dom.id == 'mf_search'){
			editFilesTree.getLoader().search_term = '';
			editFilesTree.getEl().mask('Loading myFiles...','ext-el-mask-msg x-mask-loading');
			editFilesTree.getRootNode().reload(function(){
											    if(editFilesTree.getRootNode().childNodes.length > 0){
													editFilesTree.getRootNode().childNodes[0].select();
											    }
											    editFilesTree.getEl().unmask();}
										);
		}
	}

    ,onTrigger2Click : function(theevent){
        var v = this.getRawValue();
	   if(v.length == 0){
			this.onTrigger1Click();
			return;
	   }else if(v.length > 0 && v.length < 3){
//			Ext.Msg.alert('Search','Please enter a search term.');
			Ext.Msg.show({
					title: 'Search'
					,msg:'<div align="center">Search terms must be at least 3 characters.</div>'
					,minWidth:250
					,buttons: Ext.MessageBox.OK
			});
            return;
        }
		var o = {start: 0};

//		this.triggers[0].show();
		var w = this.wrap.getWidth();
		this.triggers[0].dom.style.display = '';
//		this.el.setWidth(w-this.trigger.getWidth());
		this.el.setWidth(w-(this.triggers[0].getWidth()*2));
		
		
		if(this.el.dom.id == 'bm_search'){
			document.getElementById('my_bookmarks_div').innerHTML = '';
			create_my_bookmarks(v);		
		}else if(this.el.dom.id.substring(0,18) == 'radlex_searchfield'){
			var winid = this.el.dom.id.substring(18);
			var treepanel = Ext.getCmp('radlex_browser'+winid);
			var loader = treepanel.getLoader();
			var root = treepanel.getRootNode();
			loader.baseParams.ACTION = 'SEARCH';
			loader.baseParams.q = v;
			loader.load(root);
//			this.store.load({params:{start:0, limit:10, query:v}});
		}else if(this.el.dom.id == 'mf_search'){
			editFilesTree.getLoader().search_term = v;
			editFilesTree.getEl().mask('Loading myFiles...','ext-el-mask-msg x-mask-loading');
			editFilesTree.getRootNode().reload(function(){
											    if(editFilesTree.getRootNode().childNodes.length > 0){
													editFilesTree.getRootNode().childNodes[0].select();
											    }
											    editFilesTree.getEl().unmask();}
										);
		}
	}
});

Ext.app.FavoriteSearchField = 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-favorite-trigger',
    trigger2Class:'x-form-search-trigger',
	hideTrigger1:false

    ,onTrigger1Click : function(theevent){
        var v = this.getRawValue();
        if(v.length < 1){
//			Ext.Msg.alert('Search','Enter a search term to add to myFavorites.');
			Ext.Msg.show({
					title: 'Search'
					,msg:'<div align="center">Enter a search term to add to myFavorites.</div>'
					,minWidth:250
					,buttons: Ext.MessageBox.OK
			});
            return;
        }
		
		handleRecentSearch('ADD','FAVORITE','0',v);
		var searchtab = myrsnatabs.find('tab_type','SEARCH')[0];
		
		var rs_id = recent_searches_store.find('searchterm',v);
		if(rs_id == -1 || (rs_id != -1 && searchtab.searchterm != v)){
			
			if (myrsnatabs.getActiveTab().id != searchtab.id){
				myrsnatabs.setActiveTab(searchtab.id);
			}
			searchtab.load({url: myRSNApath + 'yottalook/index.cfm?q=' + v, text: 'Loading...', scripts:true});				
		}
	}

    ,onTrigger2Click : function(theevent){
        var v = this.getRawValue();
        if(v.length < 1){
//			Ext.Msg.alert('Search','Please enter a search term.');
			Ext.Msg.show({
					title: 'Search'
					,msg:'<div align="center">Please enter a search term.</div>'
					,minWidth:250
					,buttons: Ext.MessageBox.OK
			});
            return;
        }
		var searchtab = myrsnatabs.find('tab_type','SEARCH')[0];
		if (myrsnatabs.getActiveTab().id != searchtab.id){
			myrsnatabs.setActiveTab(searchtab.id);
		}
		searchtab.load({url: myRSNApath + 'yottalook/index.cfm?q=' + v, text: 'Loading...', scripts:true});
	}
});



// Designed to be a TwinTriggerField that uses one trigger as a combobox for dropdown lists.
Ext.form.TwinTriggerComboBox = Ext.extend(Ext.form.ComboBox, {
    initComponent : function(){
        Ext.form.ComboBox.superclass.initComponent.call(this);
        this.addEvents(
            'expand',
            'collapse',
            'beforeselect',
            'select',
            'beforequery'
        );
	   
	   //This is the only statement added from the TwinTrigger definition, everything else is from ComboBox
        this.triggerConfig = {
            tag:'span', cls:'x-form-twin-triggers', cn:[
            {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
            {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
        ]};
	   
        if(this.transform){
            this.allowDomMove = false;
            var s = Ext.getDom(this.transform);
            if(!this.hiddenName){
                this.hiddenName = s.name;
            }
            if(!this.store){
                this.mode = 'local';
                var d = [], opts = s.options;
                for(var i = 0, len = opts.length;i < len; i++){
                    var o = opts[i];
                    var value = (Ext.isIE ? o.getAttributeNode('value').specified : o.hasAttribute('value')) ? o.value : o.text;
                    if(o.selected) {
                        this.value = value;
                    }
                    d.push([value, o.text]);
                }
                this.store = new Ext.data.SimpleStore({
                    'id': 0,
                    fields: ['value', 'text'],
                    data : d
                });
                this.valueField = 'value';
                this.displayField = 'text';
            }
            s.name = Ext.id();             if(!this.lazyRender){
                this.target = true;
                this.el = Ext.DomHelper.insertBefore(s, this.autoCreate || this.defaultAutoCreate);
                Ext.removeNode(s);                 this.render(this.el.parentNode);
            }else{
                Ext.removeNode(s);             }

        }
        this.selectedIndex = -1;
        if(this.mode == 'local'){
            if(this.initialConfig.queryDelay === undefined){
                this.queryDelay = 10;
            }
            if(this.initialConfig.minChars === undefined){
                this.minChars = 0;
            }
        }
    },
    
    getTrigger : function(index){
        return this.triggers[index];
    },

    initTrigger : function(){
        var ts = this.trigger.select('.x-form-trigger', true);
        this.wrap.setStyle('overflow', 'hidden');
        var triggerField = this;
        ts.each(function(t, all, index){
            t.hide = function(){
                var w = triggerField.wrap.getWidth();
                this.dom.style.display = 'none';
                triggerField.el.setWidth(w-triggerField.trigger.getWidth());
            };
            t.show = function(){
                var w = triggerField.wrap.getWidth();
                this.dom.style.display = '';
                triggerField.el.setWidth(w-triggerField.trigger.getWidth());
            };
            var triggerIndex = 'Trigger'+(index+1);

            if(this['hide'+triggerIndex]){
                t.dom.style.display = 'none';
            }
            t.on("click", this['on'+triggerIndex+'Click'], this, {preventDefault:true});
            t.addClassOnOver('x-form-trigger-over');
            t.addClassOnClick('x-form-trigger-click');
        }, this);
        this.triggers = ts.elements;
    },

    	onTrigger1Click : Ext.emptyFn,
    
	onTrigger2Click : function(){
		if(this.disabled){
			return;
		}
		if(this.isExpanded()){
			this.collapse();
			this.el.focus();
		}else {
			this.onFocus({});
/*			if(this.triggerAction == 'all') {
		 		this.doQuery(this.allQuery, true);
			} else {
		 		this.doQuery(this.getRawValue());
			}*/
			this.doQuery(this.allQuery, true);
			this.el.focus();
		}
	}
});
Ext.reg('twintriggercombox', Ext.form.TwinTriggerComboBox);



/**************************************************************************************************************
	COMBOBOX PLUGINS END
**************************************************************************************************************/


Ext.override(Ext.PagingToolbar, {

	onClear : function(store) {
	   this.cursor = 0;

	   this.afterTextEl.el.innerHTML = String.format(this.afterPageText, 1);
	   this.field.dom.value = 1;
	   this.first.setDisabled(true);
	   this.prev.setDisabled(true);
	   this.next.setDisabled(true);
	   this.last.setDisabled(true);
	   this.loading.enable();
	   this.updateInfo();
    },

    unbind : function(store){
        store = Ext.StoreMgr.lookup(store);
        store.un("beforeload", this.beforeLoad, this);
        store.un("load", this.onLoad, this);
        store.un("loadexception", this.onLoadError, this);
        store.un("clear", this.onClear, this);
        this.store = undefined;
    },
    
    bind : function(store){
        store = Ext.StoreMgr.lookup(store);
        store.on("beforeload", this.beforeLoad, this);
        store.on("load", this.onLoad, this);
        store.on("loadexception", this.onLoadError, this);
        store.on("clear", this.onClear, this);
        this.store = store;
    },
    
    doLoad : function(start){
//        var o = {}, 
	   var pn = this.paramNames;
	   var o = (this.store.lastOptions.params != null ? this.store.lastOptions.params : {}) 
        o[pn.start] = start;
        o[pn.limit] = this.pageSize;
        this.store.load({params:o});
    }
});


Ext.override(Ext.Panel, {

	setRSNAlogo : function() {
		debugger;
    }
    
    ,setTitle : function(title, iconCls){
//	    debugger;
//	    if(title == 'myRSNA'){debugger;}
        this.title = title;
        if(this.header && this.headerAsText){
            this.header.child('span').update(title);
        }
        if(iconCls){
            this.setIconClass(iconCls);
        }
        this.fireEvent('titlechange', this, title);
        return this;
    }
});



/**************************************************************************************************************
	CHECKBOXGROUP & RADIOGROUP CLASSES
**************************************************************************************************************/

Ext.form.CheckboxGroup = Ext.extend(Ext.form.Field, {
    
    
    columns : 'auto',
    
    vertical : false,
    
    allowBlank : true,
    
    blankText : "You must select at least one item in this group",
    
    // private
    defaultType : 'checkbox',
    
    // private
    groupCls: 'x-form-check-group',
    
    // private
    onRender : function(ct, position){
        if(!this.el){
            var panelCfg = {
                cls: this.groupCls,
                layout: 'column',
                border: false,
                renderTo: ct
            };
            var colCfg = {
                defaultType: this.defaultType,
                layout: 'form',
                border: false,
                defaults: {
                    hideLabel: true,
                    anchor: '100%'
                }
            }
            
            if(this.items[0].items){
                
                // The container has standard ColumnLayout configs, so pass them in directly
                
                Ext.apply(panelCfg, {
                    layoutConfig: {columns: this.items.length},
                    defaults: this.defaults,
                    items: this.items
                })
                for(var i=0, len=this.items.length; i<len; i++){
                    Ext.applyIf(this.items[i], colCfg);
                };
                
            }else{
                
                // The container has field item configs, so we have to generate the column
                // panels first then move the items into the columns as needed.
                
                var numCols, cols = [];
                
                if(typeof this.columns == 'string'){ // 'auto' so create a col per item
                    this.columns = this.items.length;
                }
                if(!Ext.isArray(this.columns)){
                    var cs = [];
                    for(var i=0; i<this.columns; i++){
                        cs.push((100/this.columns)*.01); // distribute by even %
                    }
                    this.columns = cs;
                }
                
                numCols = this.columns.length;
                
                // Generate the column configs with the correct width setting
                for(var i=0; i<numCols; i++){
                    var cc = Ext.apply({items:[]}, colCfg);
                    cc[this.columns[i] <= 1 ? 'columnWidth' : 'width'] = this.columns[i];
                    if(this.defaults){
                        cc.defaults = Ext.apply(cc.defaults || {}, this.defaults)
                    }
                    cols.push(cc);
                };
                
                // Distribute the original items into the columns
                if(this.vertical){
                    var rows = Math.ceil(this.items.length / numCols), ri = 0;
                    for(var i=0, len=this.items.length; i<len; i++){
                        if(i>0 && i%rows==0){
                            ri++;
                        }
                        if(this.items[i].fieldLabel){
                            this.items[i].hideLabel = false;
                        }
                        cols[ri].items.push(this.items[i]);
                    };
                }else{
                    for(var i=0, len=this.items.length; i<len; i++){
                        var ci = i % numCols;
                        if(this.items[i].fieldLabel){
                            this.items[i].hideLabel = false;
                        }
                        cols[ci].items.push(this.items[i]);
                    };
                }
                
                Ext.apply(panelCfg, {
                    layoutConfig: {columns: numCols},
                    items: cols
                });
            }
            
            this.panel = new Ext.Panel(panelCfg);
            this.el = this.panel.getEl();
            
            if(this.forId && this.itemCls){
                var l = this.el.up(this.itemCls).child('label', true);
                if(l){
                    l.setAttribute('htmlFor', this.forId);
                }
            }
            
            var fields = this.panel.findBy(function(c){
                return c.isFormField;
            }, this);
            
            this.items = new Ext.util.MixedCollection();
            this.items.addAll(fields);
        }
        Ext.form.CheckboxGroup.superclass.onRender.call(this, ct, position);
    },
    
    // private
    validateValue : function(value){
        if(!this.allowBlank){
            var blank = true;
            this.items.each(function(f){
                if(f.checked){
                    return blank = false;
                }
            }, this);
            if(blank){
                this.markInvalid(this.blankText);
                return false;
            }
        }
        return true;
    },
    
    // private
    onDisable : function(){
        this.items.each(function(item){
            item.disable();
        })
    },

    // private
    onEnable : function(){
        this.items.each(function(item){
            item.enable();
        })
    },
    
    // private
    onResize : function(w, h){
        this.panel.setSize(w, h);
        this.panel.doLayout();
    },
    
    // inherit docs from Field
    reset : function(){
        Ext.form.CheckboxGroup.superclass.reset.call(this);
        this.items.each(function(c){
            if(c.reset){
                c.reset();
            }
        }, this);
    },
    
    
    
    initValue : Ext.emptyFn,
    
    getValue : Ext.emptyFn,
    
    getRawValue : Ext.emptyFn,
    
    setValue : Ext.emptyFn,
    
    setRawValue : Ext.emptyFn
    
});

Ext.reg('checkboxgroup', Ext.form.CheckboxGroup);



Ext.form.RadioGroup = Ext.extend(Ext.form.CheckboxGroup, {
    
    allowBlank : true,
    
    blankText : "You must select one item in this group",
    
    // private
    defaultType : 'radio',
    
    // private
    groupCls: 'x-form-radio-group'
});

Ext.reg('radiogroup', Ext.form.RadioGroup);



/*****************************************************************************************************************************
	FILE UPLOAD EXTENSION
*****************************************************************************************************************************/


Ext.form.FileUploadField = Ext.extend(Ext.form.TextField,  {
    /**
     * @cfg {String} buttonText The button text to display on the upload button (defaults to
     * 'Browse...').  Note that if you supply a value for {@link #buttonCfg}, the buttonCfg.text
     * value will be used instead if available.
     */
    buttonText: 'Browse...',
    /**
     * @cfg {Boolean} buttonOnly True to display the file upload field as a button with no visible
     * text field (defaults to false).  If true, all inherited TextField members will still be available.
     */
    buttonOnly: false,
    /**
     * @cfg {Number} buttonOffset The number of pixels of space reserved between the button and the text field
     * (defaults to 3).  Note that this only applies if {@link #buttonOnly} = false.
     */
    buttonOffset: 3,
    /**
     * @cfg {Object} buttonCfg A standard {@link Ext.Button} config object.
     */

    // private
    readOnly: true,
    
    /**
     * @hide 
     * @method autoSize
     */
    autoSize: Ext.emptyFn,
    
    // private
    initComponent: function(){
        Ext.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.form.FileUploadField} this
             * @param {String} value The file value returned by the underlying file input field
             */
            'fileselected'
        );
    },
    
    // private
    onRender : function(ct, position){
        Ext.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.fileInput = this.wrap.createChild({
            id: this.getFileInputId(),
            name: this.name||this.getId(),
            cls: 'x-form-file',
            tag: 'input', 
            type: 'file',
            size: 1
        });
        
        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.fileInput.on('change', function(){
            var v = this.fileInput.dom.value;
            this.setValue(v);
            this.fireEvent('fileselected', this, v);
        }, this);
    },
    
    // private
    getFileInputId: function(){
        return this.id+'-file';
    },
    
    // private
    onResize : function(w, h){
        Ext.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
    preFocus : Ext.emptyFn,
    
    // private
    getResizeEl : function(){
        return this.wrap;
    },

    // private
    getPositionEl : function(){
        return this.wrap;
    },

    // private
    alignErrorIcon : function(){
        this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
    }
    
});
Ext.reg('fileuploadfield', Ext.form.FileUploadField);



/*****************************************************************************************************************************
	ROW EXPANDER EXTENSION
*****************************************************************************************************************************/

Ext.grid.RowExpander = function(config){
    Ext.apply(this, config);

    this.addEvents({
        beforeexpand : true,
        expand: true,
        beforecollapse: true,
        collapse: true
    });

    Ext.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 = {};
};

Ext.extend(Ext.grid.RowExpander, Ext.util.Observable, {
    header: "",
    width: 20,
    sortable: false,
    fixed:true,
    menuDisabled:true,
    dataIndex: '',
    id: 'expander',
    lazyRender : true,
    enableCaching: true,

    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', function(){
            view.mainBody.on('mousedown', this.onMouseDown, this);
        }, this);
    },

    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){
        if(t.className == 'x-grid3-row-expander'){
            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('beforcollapse', 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);
        }
    }
});



/*****************************************************************************************************************************
	XML tree loader
*****************************************************************************************************************************/

// This utility class is primarily made to use with JSON objects that have been converted from XML
//	using shared_code/util/XMLUtil.cfc.ConvertXMLToJSON.
// It will take any of the attributes found in the XML tag and assign them as properties of the 
//	resulting treenode.
// Also gives an opportunity to do some additional processing with the processAttributes function
//	if you care to add more conditional data to the node.
Ext.tree.UtilTreeLoader = Ext.extend(Ext.tree.TreeLoader, {
	processAttributes: Ext.emptyFn
	
    	,createNode : function(attr){

        if(this.baseAttrs){
            Ext.applyIf(attr, this.baseAttrs);
        }
        if(this.applyLoader !== false){
            attr.loader = this;
        }
        if(typeof attr.uiProvider == 'string'){
           attr.uiProvider = this.uiProviders[attr.uiProvider] || eval(attr.uiProvider);
        }
//if(attr.attributes.id == 'RID6299'){debugger;}
	   if(typeof attr.attributes == 'object'){
			for (var j in attr.attributes){
				attr[j] = attr.attributes[j];
			}    
			delete attr.attributes;

			if(attr.children != undefined && (!Ext.isArray(attr.children) || attr.children.length == 0))
				delete attr.children;
	   }

	   this.processAttributes(attr);
	   
        return(attr.leaf ?
                        new Ext.tree.TreeNode(attr) :
                        new Ext.tree.AsyncTreeNode(attr));
    }
});
Ext.reg('utiltreeloader', Ext.tree.UtilTreeLoader);


Ext.tree.RadlexTreeLoader = Ext.extend(Ext.tree.UtilTreeLoader, {
    	processAttributes : function(attr){
		attr.iconCls = 'tree-TAG';
		attr.text = Ext.util.Format.capitalize(attr.text);
		attr.leaf = (attr.childIsParent != undefined && attr.childIsParent == 1 ? false:true);
		attr.radlexID = (attr.preferredid != undefined ? attr.preferredid : attr.id);
		attr.id = attr.radlexID;
    	}
});


Ext.override(Ext.tree.TreeLoader, {
    requestData : function(node, callback){
        if(this.fireEvent("beforeload", this, node, callback) !== false){
            this.transId = Ext.Ajax.request({
                method:this.requestMethod,
                url: this.dataUrl||this.url,
                success: this.handleResponse,
                failure: this.handleFailure,
                scope: this,
			 timeout:600000,
                argument: {callback: callback, node: node},
                params: this.getParams(node)
            });
        }else{
            
            
            if(typeof callback == "function"){
                callback();
            }
        }
    }
});


Ext.override(Ext.Window, {
	resizable:false
});



Ext.grid.PagingRowNumberer = Ext.extend(Ext.grid.RowNumberer, {
    
    renderer : function(v, p, record, rowIndex){
	    
        if(this.rowspan){
            p.cellAttr = 'rowspan="'+this.rowspan+'"';
        }
	   var params = Ext.value(record.store.lastOptions.params,{});
	   var start = Ext.value(params.start,0);
        return rowIndex+start+1;
    }
});



//Ext.override(Ext.DataView, {
//    onContextMenu : function(e){
//	    debugger;
//        var item = e.getTarget(this.itemSelector, this.el);
//        if(item){
//            this.fireEvent("contextmenu", this, this.indexOf(item), item, e);
//        }
//    }
//});


























