Ext.nd.DominoPagingToolbar = function(el, ds, config){
    Ext.nd.DominoPagingToolbar.superclass.constructor.call(this, el, ds, config);
    this.previousCursor = 1;
    this.previousStart = [];
};

Ext.extend(Ext.nd.DominoPagingToolbar, Ext.PagingToolbar, {
 	// private
	onClick : function(which){
		var ds = this.ds;
		var d = this.getPageData();
		var start;
		this.which = which;
			
		switch(which){
			case 'first':
				ds.load({params: Ext.apply(ds.lastOptions.params, {start: 1,count: this.pageSize})});
				this.activePagePrev = d.activePage;
				break;
			case 'prev':
				// if the previous page exists in cache, use it
				if (this.previousStart[d.activePage - 1]) {
					start = this.previousStart[d.activePage - 1];
				} else {
					start = Math.max(1,this.cursor-this.pageSize);
				}
				ds.load({params: Ext.apply(ds.lastOptions.params, {start: start,count: this.pageSize})});
				this.activePagePrev = d.activePage;
				break;
			case 'next':
				if (ds.data.length > 0) {
					start = parseInt(ds.data.last().node.attributes.getNamedItem('position').value,10);
				} else {
					start = 1;
				}
				ds.load({params: Ext.apply(ds.lastOptions.params, {start: start,count: this.pageSize})});
      			this.activePagePrev = d.activePage;
				break;
			case 'last':
				var total = ds.getTotalCount();
				var extra = total % this.pageSize;
				var lastStart = extra ? (total - extra) : total-this.pageSize
				ds.load({params: Ext.apply(ds.lastOptions.params, {start: lastStart, count: this.pageSize})});
				this.activePagePrev = d.activePage;
				break;
			case 'refresh':
				ds.load({params: Ext.apply(ds.lastOptions.params, {start: this.cursor, count: this.pageSize})});
				break;
		}
	},

  // private
	onLoad : function(ds, r, o){
		this.cursor = o.params ? (o.params.start ? o.params.start : 1) : 1;
		var d = this.getPageData(), ap = d.activePage, ps = d.pages;
		
		// reset activePage if no start param
		// start param is removed when user clicks on a column to resort
		// this is so that the paging will start over since we are taking the user back to the top of the view (sorted by the column they clicked)
		if (!o.params.start) {
			d.activePage = 1;
			ap = 1;
		}
		
		// update our paging cache if the current active page is greater that the previous active page
		if (d.activePage == 1 || d.activePage > this.activePagePrev) {
			if (ds.data.length > 0) {
				this.previousStart[d.activePage] = parseInt(ds.data.first().node.attributes.getNamedItem('position').value,10);
				this.previousStart[d.activePage + 1] = parseInt(ds.data.last().node.attributes.getNamedItem('position').value,10);
			}
		} else {
			// not sure if we should doing anything with cache if we are paging backwards....
		}	
		this.afterTextEl.el.innerHTML = String.format(this.afterPageText, d.pages);
		this.field.dom.value = ap;
		this.first.setDisabled(ap == 1);
		this.prev.setDisabled(ap == 1);
		this.next.setDisabled(ap == ps);
		this.last.setDisabled(ap == ps);
		this.loading.enable();
	},

  // private
	getPageData : function(){
		var total = this.ds.getTotalCount();
		var activePage;
		if (this.which == 'next') {
			activePage = this.activePagePrev ? this.activePagePrev + 1 : 1;
		} else if (this.which == 'prev') {
			activePage = this.activePagePrev ? this.activePagePrev - 1 : 1;
		} else if (this.cursor == 1) {
			activePage = 1;
		} else {
			activePage = Math.ceil((this.cursor+this.pageSize)/this.pageSize)
		}

		// reset this.which
		this.which = "";

		return {
			total : total,
			activePage : activePage,
			pages : total < this.pageSize ? 1 : Math.ceil(total/this.pageSize)
		};
	}
	
});

//change the function called on double click for all uiviews
Ext.nd.UIView.prototype.openDocument = function(grid, rowIndex, e, bEditMode) {
   var mode = (bEditMode) ? '?EditDocument' : '?OpenDocument';
   var title = "Opening...";
   var ds = grid.dataSource;
   var row = grid.selModel.getSelected();
   var node = row.node;
   var unid = node.attributes.getNamedItem('unid');
   
   if (!unid) { 
      return;
   } else {
      unid = unid.value;
   }
   var viewUrl = this.getViewUrl(grid);   
   var link = viewUrl + '/' + unid + mode;
   updatePanel( link, 'center', 'center-iframe-panel');
   
   // cleanup
   ds = null;
   row = null;
     
}

/* /Change the click of the outline entries to use updatePanel
Ext.nd.UIOutline.prototype.openEntry = function(node, e) {
    var attributes, extndType, extndHref, extndPosition, entryId, title;
	attributes = node.attributes;
    extndHref = attributes.extndHref;
	
    var viewUrl = (extndHref.indexOf('?') > 0) ? extndHref.split('?')[0] : extndHref.split('!')[0];       
    updatePanel( viewUrl, 'center', 'center-content-panel');
	
	// cleanup
	attributes, extndHref, viewUrl = null;
};*/

//Customized to refresh only when it's a single cat view or when a portal is selected.
Ext.nd.UIOutline.prototype.openEntry = function(node, e) {
     var attributes, extndType, extndHref, extndPosition, entryId, isExpandable, isExpanded, refuseSelection, title;
    attributes = node.attributes;
    extndHref = attributes.extndHref;
    extndType = attributes.extndType;
    extndPosition = attributes.extndPosition;
    entryId = "id-" + extndPosition;
	isExpandable = attributes.isExpandable;
	isExpanded = attributes.isExpanded;
	refuseSelection = attributes.refuseSelection;
	frameSetName = attributes.frameSetName;
    title = node.text;
		
	if (extndType == "2" || extndType == "20") {
	  var viewUrl = (extndHref.indexOf('?') > 0) ? extndHref.split('?')[0] : extndHref.split('!')[0];
	  
	  //If there is a value in framesSetName check for single category types
	  var showSingleCategory;
	  if ( frameSetName != "" ) {
	  	switch (frameSetName) {
         
         case "Division" :
            showSingleCategory = Ext.nd.Session.trmsUserDivision;
            break;
         
         case "UserName" :
            showSingleCategory = Ext.nd.Session.trmsUserName;
            break;
         default :
            showSingleCategory = "";
      };
       //(showSingleCategory != "") ? viewUrl += "?OpenView&RestrictToCategory=" + showSingleCategory : null ;
	  }

	  	//set the ViewName cookie so that they return to this view after they leave.
		if (typeof rightBack == "function"){var viewName = rightBack( viewUrl, "/" )};
		if (typeof setCookie == "function"){
			if(typeof viewName == "string" || typeof WebFilePathRel == "string" ) {setCookie( WebFilePathRel + "/:ViewName", viewName, false, "/", false, false, true );}
		};
//Custom refresh if its ie6
	  //if (navigator.appName == "Microsoft Internet Explorer") { alert(navigator.appName)};
	  //if (navigator.appVersion.split(";")[1] == " MSIE 6.0") { alert( navigator.appVersion.split(";")[1])};
	  if (navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.split(";")[1] == " MSIE 6.0"){
	  	//return updatePanel( 'Refresh', 'center');
		return window.top.location.href = "/";
		};
		
//Custom refresh if its a parent level element or if it's in the first section or if its ie6
//	  if ( extndPosition.charAt(0)== "1" || extndPosition.length== 1 ){
//	  	return updatePanel( viewUrl, 'center', 'center-content-panel');
//	    };

//Custom refresh if 'Does not keep selection focus' is selected in the outline entry poperties
	  if ( refuseSelection ){
	  	return updatePanel( viewUrl, 'center', 'center-content-panel');
	  };
	  
       // delete the current grid
       if (this.uiView.grid) {
		
        if (this.viewPanel.setContent) {
          this.viewPanel.setContent("");
        } else {
          Ext.get(this.viewPanel).update("");
        }
         try {
           this.uiView.grid.destroy();
         } catch(e) {}
		 
      }

      this.uiView = new Ext.nd.UIView({
        layout : this.layout,
        viewUrl : viewUrl,
        viewParams : "",
		container : this.viewPanel,
        statusPanel : this.statusPanel,
		showSearch : true,
		showSingleCategory : (showSingleCategory != "") ? showSingleCategory : null,
		showCategoryComboBox : false
       });
     
	 //custom update title on the viewtemplate
	 if( typeof Ext.get('View-Title') == "object" ) {
	 	var title = attributes.text;
		if( extndPosition.indexOf(".") != -1 ){title = node.parentNode.text + " - " + title;};
	 	Ext.get('View-Title').update('<h3 style="margin-bottom: 5px;">' + title + ' </h3>');};
	 
      if (typeof this.viewPanel != "string") {
        this.viewPanel.setTitle(title);
        this.layout.showPanel(this.viewPanel);
      };
     } else if (extndHref != "") {
       var entry = this.layout.getRegion('center').getPanel(entryId);
       
      if(!entry){ 
        var iframe = Ext.DomHelper.append(document.body, {
          tag: 'iframe', 
          frameBorder: 0, 
          src: extndHref,
          id : entryId
        });
        var panel = new Ext.ContentPanel(iframe, {
          title: Ext.util.Format.ellipsis(title,16),
          fitToFrame:true, 
          closable:true
        });
        this.layout.add('center', panel);
      } else { 
        this.layout.showPanel(entry);
      }
    }
	
  };


// change the context menu ( right click) in UIViews
Ext.nd.UIView.prototype.gridHandleRowContextMenu= function(grid, rowIndex, e) {
   e.stopEvent();
   
   var menu = new Ext.menu.Menu({
      id : 'xnd-context-menu'
   });
   
   //menu.add({text : 'Document Properties', handler : this.gridContextMenuShowDocumentPropertiesDialog, scope: this});
   //menu.addSeparator();
   menu.add({editMode : false, text : 'Open', handler : this.gridContextMenuOpenDocument, scope: this});
   menu.add({editMode : true, text : 'Edit', handler : this.gridContextMenuOpenDocument, scope: this});
   menu.addSeparator();
   menu.add({text : 'Search This View', handler : this.gridContextMenuSearchView, scope: this});
      
   menu.grid = grid;
   menu.rowIndex = rowIndex;

   var coords = e.getXY();
   menu.showAt([coords[0], coords[1]]);

   // cleanup   
   menu = null;
   coords = null;
};
Ext.nd.UIView.prototype.gridContextMenuSearchView = function() {
    if (!this.showSearch) {
      Ext.MessageBox.alert('Search View', 'showSearch must be enabled for the view');
    } else {
      Ext.MessageBox.prompt('Search View', 'Query:', this.handleContextMenuSearch,this);
    }
  };

Ext.nd.UIView.prototype.handleContextMenuSearch = function(btn, text) {
    if(btn == "ok" && text) {
      this.searchField.setValue(text);
      this.handleViewSearch();
    }
  };
// change various keypress actions in UiViews
Ext.nd.UIView.prototype.gridHandleKeyDown = function(e) {
   //var node, row, rowIndex, unid, target;
   var row, rowIndex, target;
   var keyCode = e.browserEvent.keyCode;
   var charCode = e.charCode;
   var doContinue = true;
   
   target = e.getTarget();
   row = this.grid.selModel.getSelected();
   rowIndex = this.grid.dataSource.indexOf(row);

   
   if (e.altKey) { 
      doContinue = false;
   }

   
   if (e.ctrlKey && keyCode == 69) {
      if(row){
         this.openDocument(this.grid, rowIndex, e, true);
      }
      doContinue = false;
   }
   
   
   if (e.ctrlKey) { 
      doContinue = false;
   }
   
   
   if (e.shiftKey && keyCode == 16) {
      doContinue = false;
   }
   
   
   if ( doContinue ) switch (keyCode) {   
      case e.RETURN :
         if(row){
            this.openDocument(this.grid, rowIndex, e);
         }
         break;
      case e.DELETE :
         if(row){
            //this.deleteDocument(this.grid, row, e);
         }
         break;
         
      case e.BACKSPACE :
      case e.DOWN :
      case e.ESC :
      case e.F5 :
      case e.HOME :
      case e.LEFT :
      case e.PAGEDOWN :
      case e.PAGEUP :
      case e.RIGHT :
      case e.UP :
      case e.TAB :
   
         break;
      
      case e.SPACE :
         //Ext.MessageBox.alert("Coming Soon","In a future release, the space bar will toggle the selection of the document.");
         break;
      default :
         if (row) { 
            //Ext.MessageBox.prompt( 'Search Text', 'Starts with...', this.quickSearch, this)
            

         }
   }
   
   // cleanup
   target = null;
   row = null;
   rowIndex = null;
   keyCode = null;
   charCode = null;
  };
 



/* change how viewsearch is handled
  Ext.nd.UIView.prototype.handleViewSearch = function() {
    var qry = this.searchField.getValue();
	var ds = this.grid.dataSource;
    
    //delete ds.lastOptions.params.start;
	
	//alert( this.viewName.replace(" ", "+") );
	var searchURL = this.viewUrl.slice(0, this.viewUrl.lastIndexOf("/")) + "/(SearchViewEntries)?OpenAgent&vw="+ this.viewName.replace(" ", "+") + "&q=" + qry; 
    this.readerSearch = new Ext.nd.data.DominoViewXmlReader( this.dominoView.meta, this.dominoView.recordConfig);
	
    var searchds = new Ext.nd.data.DominoViewStore({
        proxy: new Ext.data.HttpProxy({
            url: searchURL,
            method: "GET"
        }),
        baseParams: this.baseParams,
        //reader: viewEntryReader,
		reader: this.readerSearch,
		remoteSort:  true
    });
	this.grid.dataSource = searchds;
	this.grid.dataSource.load();
	this.grid.render()
	//TODO: refresh the grid or set the new datastore
    
  };*/

  
  
/*  Previous working copy 
  Ext.nd.UIView.prototype.handleViewSearch = function() {
    var ds = this.grid.dataSource;
    var searchBox = this.searchField;
    var cm = this.cm;
    
    //var onFilteringBeforeQuery = function(e) {
         var value = searchBox.getValue();
         if (value.length==0) {
           ds.clearFilter();
         }else{
           value = value.replace(/^\s+|\s+$/g, "");
           if (value=="") return;
    	     var aux1=[];
    			for (var j=0; j<cm.config.length; j++){
  			  aux1[aux1.length] = cm.config[j].dataIndex;
    			}
           ds.filterBy(function(r) {
           	//valueArr = value.split(/\ +/);
            //for (var i=0; i<valueArr.length; i++) {
            //re = new RegExp(Ext.escapeRe(valueArr[i]), "i");
    		var aux2 = false;
    		for (var j=0; j<aux1.length; j++){
    			//if (re.test(r.data[aux1[j]]) == false){
	    		//if ( r.data[aux1[j]].data[0].toLowerCase().indexOf(value.toLowerCase()) < 0 ){
				
				if ( r.data[aux1[j]] && r.data[aux1[j]].toLowerCase().indexOf(value.toLowerCase()) < 0 ){
    				aux2 = false;
    			}else{
    				aux2 = true;
    				break;
    			}
    		}
    		if (aux2 == false){
    			return false;
    		}
            //    }
                return true;
           });
        }
    //  };
    
    //searchBox.on("change", onFilteringBeforeQuery);
    
    //ds.load({params:{start: 0, limit: ds.lastOptions.params.limit}});
    //this.grid.render();
	
	// cleanup
	ds, searchBox, cm = null
  }
 */ 
/*  
  Ext.grid.Grid.prototype.AddQuickSearch = function(toolbar) {
	
	toolbar.addSeparator();
	cm = this.getColumnModel();
	internaldataSource = this.dataSource;
	internaldataSource.myfilter = '';
	var quickMenuItems = [];
	quickMenuItems.push('<b class="menu-title">Quicksearch Columns</b>');
	for(i=0; i < cm.getColumnCount() ; i++){
		quickMenuItems.push(new Ext.menu.CheckItem({ renderer: cm.getRenderer(i), text: cm.getColumnHeader(i), store: cm.getDataIndex(i), checked: true }))
		// time to load our renderers to the columnmodles
		cm.setRenderer(i, renderStub);
	}

    var quickMenu = new Ext.menu.Menu({
	id: 'quickMenu',
	items: quickMenuItems
    });
    toolbar.add({
	text: 'Quicksearch',
	tooltip: 'Quickly search through the current page.',
	icon: '/admin/include/m.png',
	cls: 'x-btn-text-icon btn-search-icon',
	menu: quickMenu
    });
    var sftb = toolbar.addDom({
	tag: 'input',
	id: 'quicksearch',
	type: 'text',
	size: 30,
	value: '',
	style: 'background: #F0F0F9;'
    });
    var searchBox = new Ext.form.HistoryComboBox({
	hideTrigger: true,
	//hideClearButton: true,
	emptyText: "Type to quicksearch",
	//rememberOn: 'all'
	rememberOn: 'delay'
    });
    searchBox.applyTo('quicksearch');

    var searchRec = Ext.data.Record.create([
        {name: 'query', type: 'string'}
    ]);
    var onFilteringBeforeQuery = function(e) {
	//grid.getSelectionModel().clearSelections();
	internaldataSource.myfilter = e;
	var value = searchBox.getValue();
        if (value.length==0) {
            internaldataSource.clearFilter();
        } else {
            value = value.replace(/^\s+|\s+$/g, "");
            if (value=="")
                return;
            internaldataSource.filterBy(function(r) {
		// filter operator AND on all keywords for defined columns
        valueArr = value.split(/\ +/);
		for (var j=0; j<valueArr.length; j++) {
		    re = new RegExp(Ext.escapeRe(valueArr[j]), "i");
		    keep = false;
		    for (var i=0,items=quickMenuItems,len=items.length; i<len; i++){
            	if (items[i].checked) {
            		if(items[i].renderer && renderStub)
            		{
            			var afterrder = items[i].renderer(r.data[items[i].store.toLowerCase()]);
            			if(re.test(afterrder) == true)
            				return true;
            		}
				    if (re.test(r.data[items[i].store.toLowerCase()])==true){
				        keep = true;
				    }
				}
		    }
		    if (!keep){
				return false;
		    }
		}
		return true;
            });
        }
    };
    
    function renderStub(value, p, record, rowIndex, ind , ds){
    	var stubval = value;
    	var offset = ind+1;
    	if(quickMenuItems[offset].renderer) { // we already have a renderer then call it first
    		stubval = quickMenuItems[offset].renderer(value, p, record, rowIndex, ind , ds);
    	}
    	return renderFoundAll(stubval, p, record, rowIndex, ind , ds);
    }
    
    function renderFoundAll(value, p, record, rowIndex, ind , ds){
    	if (ds.myfilter !=''){
	        foundArray = new Array();
	        result = null;
	        a = 1;
	        start = 0;
	        while(result >=0){
        		result = value.toLowerCase().indexOf(ds.myfilter.toLowerCase(),start);
        		foundArray[foundArray.length] = result;
        		a=a+1;
        		start = result+1;
			}
	        var tmpString = value.substr(0,ds.myfilter.length);
	        index = 0;
	        i = 0;
	        construct = '';
	        while (i<foundArray.length){
		        if (foundArray[i]>index){
        			construct = construct + String.format('{0}<span style="color:red; font-weight: bold;">{1}</span>', value.substring(index,foundArray[i]), ds.myfilter);
				}else if(foundArray[i]==index){
        			construct = construct + String.format('<span style="color:red; font-weight: bold;">{0}</span>', ds.myfilter);
				}else if(foundArray[i]==-1){
		          	construct = construct + String.format('{0}', value.substring(index,value.length-foundArray[i]-1));
				}
	        index = index + value.substring(index,foundArray[i]).length+ ds.myfilter.length;
	        i=i+1;
			}
	        if ((foundArray.length-1)>0){
        		return construct;
			}else{
         		return value;
			}

	    }else{
	    	return value;
		}
	}

        
    quickMenu.on('click', onFilteringBeforeQuery);
    searchBox.on("valueChange", onFilteringBeforeQuery);
};
*/

//Fixes the single category data store ( &collapseView instead of &CollapseAll
Ext.nd.UIView.prototype.init = function() {
   this.getViewDesign();
   
  };

//BDS added 7-28-07
Ext.nd.UIView.prototype.createSearch = function(toolbar) {
    this.searchField = new Ext.form.TextField({
      emptyText: "Search view...",
      name: "extnd-vw-search",
      width: 100
    });
    toolbar.addSeparator();
    toolbar.addField(this.searchField);
    toolbar.addButton({text: "Search", scope: this, handler: this.handleViewSearch});
    toolbar.addSeparator();
  };

Ext.nd.UIView.prototype.handleViewSearch = function() {
    var qry = this.searchField.getValue();
    var tb = (this.searchInPagingToolbar)?this.paging:this.toolbar;
    
    if (!this.isSearching) {
      this.oldDataSource = this.grid.getDataSource(); // Save the current DS so we can restore it when search is cleared
      
      // define the Domino viewEntry record
      var viewEntry = Ext.data.Record.create(this.dominoView.recordConfig);

      // create reader that reads viewEntry records
      //var viewEntryReader = new Ext.nd.data.DominoViewXmlReader(this.dominoView.meta, viewEntry);
      this.readerSearch = new Ext.nd.data.DominoViewXmlReader( this.dominoView.meta, this.dominoView.recordConfig);
	  
	  //BDS 
	  //var searchURL = this.viewUrl.slice(0, this.viewUrl.lastIndexOf("/")) + "/(SearchViewEntries)?OpenAgent";
	  Ext.nd.extndUrl = this.viewUrl.slice(0, this.viewUrl.lastIndexOf("/")) + "/";
      var ds = new Ext.nd.data.DominoViewStore({
          proxy: new Ext.data.HttpProxy({
              url: Ext.nd.extndUrl+'($Ext.nd.SearchView)?OpenAgent',
			  //url: searchURL,
              method: "GET"
          }),
          //baseParams: {db: "/"+Ext.nd.Session.CurrentDatabase.FilePath, vw: this.viewName },
		  //baseParams: this.baseParams.RestrictToCategory ? {vw: this.viewName, restrictToCategory: this.baseParams.RestrictToCategory} : {vw: this.viewName},
		  baseParams: this.baseParams.RestrictToCategory ? {vw: this.viewName, db: "/"+Ext.nd.Session.CurrentDatabase.FilePath, restrictToCategory: this.baseParams.RestrictToCategory} : {db: "/"+Ext.nd.Session.CurrentDatabase.FilePath, vw: this.viewName },
          //reader: viewEntryReader,
		  reader: this.readerSearch,
          remoteSort: false
      });
    
      this.grid.reconfigure(ds, this.grid.getColumnModel());
      this.paging.unbind(this.oldDataSource);
      this.paging.bind(ds);
      this.isSearching = true; // Set this so we don't create the search datastore multiple times
      this.clearSearchButton = tb.addButton({text: "Clear Results", scope: this, handler: this.handleClearSearch});
    }
    this.grid.getDataSource().load({params:{query: qry, count: this.count, start: 1}});
  }
  
Ext.nd.UIView.prototype.handleClearSearch = function() {
    if (this.isSearching) {
      this.paging.unbind(this.grid.getDataSource());
      this.paging.bind(this.oldDataSource);
      this.grid.reconfigure(this.oldDataSource, this.grid.getColumnModel());
      this.grid.getDataSource().load({params:{start:1}});
      this.isSearching = false;
      this.searchField.reset();
      this.clearSearchButton.destroy();
    }
  }
Ext.nd.UIView.prototype.getViewUrl = function(grid) {
    return this.viewUrl;
  }
  
//Overwritten to auto expand
Ext.nd.UIOutline.prototype.init2 = function(o) {
    var response = o.responseXML;
    var arEntries = response.getElementsByTagName('outlineentry');
  
    
    var dh = Ext.DomHelper;
    var container = (this.container.getEl) ? this.container.getEl() : this.container;
    
    var Tree = Ext.tree;
    var tree = new Tree.TreePanel(container, {
        animate : true, 
        enableDD : true,
        ddGroup: 'TreeDD',
        containerScroll : true,
        dropConfig : {appendOnly : true},
        rootVisible : false
    });
    
    var root = new Tree.TreeNode({
        text : 'domino-folders', 
        draggable : false, 
        id : 'domino-folders'
    });
    tree.setRootNode(root);
    
	
	var arNodes = [];
    for (var i=0; i<arEntries.length; i++) {
      var entry = arEntries.item(i);
      var extndType = entry.attributes.getNamedItem('type').value;
      var extndTitle = entry.attributes.getNamedItem('title').value;
      var tmpextndHref = entry.attributes.getNamedItem('url');
      var extndHref = (tmpextndHref) ? tmpextndHref.value : "";

      var expandable = entry.attributes.getNamedItem('expandable');
      var isExpandable = (expandable) ? true : false;
	  var isExpanded = (expandable)? ((expandable.value == 'true') ? true : false)  : false;
	  
	  //Used for full refresh
	  var tmpRefuseSelection = entry.attributes.getNamedItem('refuseselection');
      var refuseSelection = (tmpRefuseSelection) ? tmpRefuseSelection.value : ""; 
	  
	  //Used for restricttocategory
	  var tmpFrameSetName = entry.attributes.getNamedItem('framesetname');
      var frameSetName = (tmpFrameSetName) ? tmpFrameSetName.value : "";
         
      var tmpextndIcon = entry.attributes.getNamedItem('icon');
      var extndIcon = (tmpextndIcon) ? tmpextndIcon.value : "";
      var curPosition = entry.attributes.getNamedItem('position').value;
      
      var cls;          
      switch (extndType) {
         
         case "0" :
            cls = (isExpandable) ? "folder" : "file";
            break;
         
         case "2" :
            cls = "file";
            break;
         
         case "20" :
            cls = "folder";
            break;
         default :
            cls = "file";
      };
            
      var curNode = new Tree.TreeNode({
        text : extndTitle, 
        cls : cls, 
        allowDrag : true, 
        allowDrop : (extndType == "20" || extndType == "0") ? true : false,
        isTarget : true,
        leaf : false,
		expanded : isExpanded,
        extndHref : extndHref,
        extndType : extndType,
        extndExpandable: isExpandable,
		isExpanded : isExpanded,
		refuseSelection : refuseSelection,
		frameSetName : frameSetName,
        extndPosition : curPosition,
        icon : (this.useOutlineIcons) ? extndIcon : null
      });
      
      curNode.on('click', this.openEntry.createDelegate(this), this, true);
      
      arNodes[curPosition] = curNode;
      
      if (curPosition.indexOf('.') > 0) {
        var parentPosition = curPosition.substring(0,curPosition.lastIndexOf('.'));
        arNodes[parentPosition].appendChild(curNode);   
      } else {
        root.appendChild(curNode);
      }
	  
	  // cleanup
	  entry = null;
	  curNode = null;
    }

   
   tree.on('beforenodedrop', this.addToFolder);

   tree.render();
   //tree.expandAll();          
   
   
 
 /* used to expand the navigator after it renders for effect. to enable hide the expanded config above  
   root.expand();
   //root.firstChild.expand();
   var nodeArray = root.childNodes
   for( var x=1; x <= nodeArray.length; x++){
   	(nodeArray[x-1].attributes.isExpanded)?nodeArray[x-1].expand():"";
   };
    */
   
   // cleanup
   root = null;
   tree = null;
  };
  
  
/*
add categorized view support according to this thread.
http://extjs.com/forum/showthread.php?t=9495
*/
Ext.nd.data.DominoViewXmlReader.prototype.readRecords = function(doc) {
		this.xmlData = doc;

        	var root = doc.documentElement || doc;
    		var q = Ext.DomQuery;
    		var recordType = this.recordType, fields = recordType.prototype.fields;
    		var sid = this.meta.id;
    		var totalRecords = 0, success = true;

    		if(this.meta.totalRecords){
    	    		totalRecords = q.selectNumber(this.meta.totalRecords, root, 0);
    		}
        
        	if(this.meta.success){
          	  var sv = q.selectValue(this.meta.success, root, true);
              success = sv !== false && sv !== 'false';
    		}

    		var records = [];
    		var ns = q.select(this.meta.record, root);

        	for(var i = 0, len = ns.length; i < len; i++) {
	     	    var n = ns[i];
	        	var values = [];
				//var values = {};// BDS added 10-29-07
				
	        	var id = sid ? q.selectValue(sid, n) : undefined;

	        	for(var j = 0, jlen = fields.length; j < jlen; j++){
	            	var f = fields.items[j];
                	var v = this.parseEntryData(f.mapping || f.name, n, f.defaultValue);
					
					//var v = this.parseEntryData(f.name, n, f.defaultValue);
					//var v = this.getViewColumnValue(n, f.mapping, f.defaultValue);
	            	
					v = f.convert(v);
	            	values[f.name] = v;
					
					// cleanup
					f = null;
					v = null;
	        	}

	        	var record = new recordType(values, id);
	        	record.node = n;
	        	records[records.length] = record;
				
				// cleanup
				n = null;
				id = null;
				record = null;
	    	}
			
			// cleanup
			root = null;
			q = null;
			recordType = null;
			sid = null;
			ns = null;
	    	
			return {
	        	success : success,	    	
	        	records : records,
	        	totalRecords : totalRecords || records.length
	    	};

	};
	

Ext.nd.data.DominoViewXmlReader.prototype.parseEntryData = function(path, root, defaultValue) {

 		var valueCache = {};
    	var trimRe = /^\s+|\s+$/g;
    		
		path = path.replace(trimRe, "");
          if(!valueCache[path]){
          	valueCache[path] = Ext.DomQuery.compile(path, "select");
		}
          var n = valueCache[path](root);
		n = n[0] ? n[0] : n;

		// cleanup
		valueCache = null;
		
		return this.getItemText(n && n.lastChild ? n : null);
	};


Ext.nd.data.DominoViewXmlReader.prototype.getItemText = function(dataItem, nListOffset){
	
		if (!dataItem) { return null; }
		
		var oRetVal = null;
		var nItems = null;
		var i;	
		var sDate = "";
		
		switch (dataItem.lastChild.nodeName) {
			// BDS added number case 10-29-07
			/*case "number":
			     if (dataItem.lastChild.lastChild.nodeValue) {			         		
					return parseFloat(dataItem.text).toFixed(2);
				}
		     break;*/
			 
			case "date":
			     if (dataItem.lastChild.lastChild.nodeValue) {
			         	sDate = dataItem.lastChild.lastChild.nodeValue;
			         	if (sDate.length == 8) {
						sDate += "T000000,00+00";
					}     	
			    		return Ext.nd.ux.util.Format.date(sDate, 'm/d/y');
				}
		     break;
		          		
		     case "time":
				if (dataItem.lastChild.lastChild.nodeValue) {
					return Ext.nd.ux.util.Format.date(dataItem.lastChild.lastChild.nodeValue, 'H:i');
			     }
		     break;
		          		
	          case "datetime":
	          	if (dataItem.lastChild.lastChild.nodeValue) {
	          		sDate = dataItem.lastChild.lastChild.nodeValue;
		         		if (sDate.length == 8) {
						sDate += "T000000,00+00";
						return Ext.nd.ux.util.Format.date(sDate, 'm/d/y');
					} else {
						return Ext.nd.ux.util.Format.date(sDate, 'm/d/y H:i');
					}
				}
			break;
						
			case "textlist":
        			var textItems = dataItem.lastChild.getElementsByTagName("text");
				if (!textItems) { return ""; }

				nItems = textItems.length;
				if( nListOffset ) {
					if( nListOffset > nItems-1 ) { return ""; }
					return textItems[nListOffset].nodeValue;
				} 
				var aTextList = new Array();
				for( i=0; i< nItems; i++ ) {
					aTextList[i] = textItems[i].firstChild.nodeValue.replace(new RegExp("\u000A","g"), "");
				}
				oRetVal = aTextList.join("\u000A");
			break;
		
			case "datetimelist":
				var dateTimeItems = dataItem.lastChild.getElementsByTagName("datetime");
				if (!dateTimeItems) { return ""; }

				nItems = dateTimeItems.length;
				if( nListOffset ) {
					if( nListOffset > nItems-1 ) { return ""; }
					return dateTimeItems[nListOffset].nodeValue;
				} 
				var aDateTimeList = new Array();
				for( i=0; i< nItems; i++ ) {
					aDateTimeList[i] = dateTimeItems[i].firstChild.nodeValue.replace(new RegExp("\u000A","g"), "");
				}
				oRetVal = aDateTimeList.join("\u000A");
			break;
		}
		
		if (oRetVal) {
			return oRetVal;
		} else {
			return (dataItem.lastChild.firstChild ? dataItem.lastChild.firstChild.nodeValue.replace(new RegExp("\u000A","g"), "") : "");
		}
		
	};


Ext.extend(Ext.nd.grid.DominoGridView, Ext.grid.GridView, {
		init: function(grid){
		  // TO DO: add code here to look for an existing grid for the same view and destroy it if it exists?

		Ext.grid.GridView.superclass.init.call(this, grid);

		this.bind(grid.dataSource, grid.colModel);

	    grid.on("headerclick", this.handleHeaderClick, this);

        if(grid.trackMouseOver){
            grid.on("mouseover", this.onRowOver, this);
	        grid.on("mouseout", this.onRowOut, this);
	    }
	    grid.cancelTextSelection = function(){};
		this.gridId = grid.id;

		var tpls = this.templates || {};

		if(!tpls.master){
		    tpls.master = new Ext.Template(
		       '<div class="x-grid" hidefocus="true">',
		          '<div class="x-grid-topbar"></div>',
		          '<div class="x-grid-scroller"><div></div></div>',
		          '<div class="x-grid-locked">',
		              '<div class="x-grid-header">{lockedHeader}</div>',
		              '<div class="x-grid-body">{lockedBody}</div>',
		          "</div>",
		          '<div class="x-grid-viewport">',
		              '<div class="x-grid-header">{header}</div>',
		              '<div class="x-grid-body">{body}</div>',
		          "</div>",
		          '<div class="x-grid-bottombar"></div>',
		          '<a href="#" class="x-grid-focus" tabIndex="-1"></a>',
		          '<div class="x-grid-resize-proxy">&#160;</div>',
		       "</div>"
		    );
		    tpls.master.disableformats = true;
		}

		if(!tpls.header){
		    tpls.header = new Ext.Template(
		       '<table border="0" cellspacing="0" cellpadding="0">',
		       '<tbody><tr class="x-grid-hd-row">{cells}</tr></tbody>',
		       "</table>{splits}"
		    );
		    tpls.header.disableformats = true;
		}
		tpls.header.compile();

		if(!tpls.hcell){
		    tpls.hcell = new Ext.Template(
		        '<td class="x-grid-hd x-grid-td-{id} {cellId}"><div title="{title}" class="x-grid-hd-inner x-grid-hd-{id}">',
		        '<div class="x-grid-hd-text" unselectable="on">{value}<img class="x-grid-sort-icon" src="', Ext.BLANK_IMAGE_URL, '" /></div>',
		        "</div></td>"
		     );
		     tpls.hcell.disableFormats = true;
		}
		tpls.hcell.compile();

		if(!tpls.hsplit){
		    tpls.hsplit = new Ext.Template('<div class="x-grid-split {splitId} x-grid-split-{id}" style="{style}" unselectable="on">&#160;</div>');
		    tpls.hsplit.disableFormats = true;
		}
		tpls.hsplit.compile();

		if(!tpls.body){
		    tpls.body = new Ext.Template(
		       '<table border="0" cellspacing="0" cellpadding="0">',
		       "<tbody>{rows}</tbody>",
		       "</table>"
		    );
		    tpls.body.disableFormats = true;
		}
		tpls.body.compile();

		if(!tpls.row){
		    tpls.row = new Ext.Template('<tr class="x-grid-row {alt}">{cells}</tr>');
		    tpls.row.disableFormats = true;
		}
		tpls.row.compile();

		if(!tpls.cell){
		    tpls.cell = new Ext.Template(
		        '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
		        '<div class="x-grid-col-{id} x-grid-cell-inner" style="{style}"><div class="ext-nd-ed-grid-cell" unselectable="on" {attr}>{value}</div></div>',
		        "</td>"
		    );
            tpls.cell.disableFormats = true;
        }
		tpls.cell.compile();
		
		if(!tpls.categoryCell){
		    tpls.categoryCell = new Ext.Template(
		        '<td class="x-grid-col x-grid-td-{id} {cellId} {css}" tabIndex="0">',
		        '<div class="x-grid-col-{id} x-grid-cell-inner" style="{style}"><div class="ext-nd-ed-grid-categorycell" unselectable="on" {attr}>{value}</div></div>',
		        "</td>"
		    );
            tpls.categoryCell.disableFormats = true;
          }
		tpls.categoryCell.compile();
		
		if(!tpls.responseCell){
			tpls.responseCell = new Ext.Template(
        		   '<td colspan="{cols}" class="x-grid-col x-grid-td-{id} {cellId} {css}" style="width: {colWidth}" tabIndex="0">',
		        '<div class="ext-nd-ed-grid-col-response x-grid-cell-inner" style="{style}"><div class="ext-nd-ed-grid-cell" unselectable="on" {attr}>{value}</div></div>',
		        "</td>"			
			);
			tpls.responseCell.disableFormats = true;
		}
		tpls.responseCell.compile();

		this.templates = tpls;
		
		// cleanup
		tpls = null;
	},
            
        doRender : Ext.isGecko ?
            function(cs, rs, ds, startRow, colCount, stripe){
                var ts = this.templates, ct = ts.cell, rt = ts.row;
                // buffers
                var buf = "", lbuf = "", cb, lcb, c, p = {}, rp = {}, r;
                var child, category, q, indent, config, categoryTotal;
                
                for(var j = 0, len = rs.length; j < len; j++){
                    r = rs[j]; cb = ""; lcb = ""; rowIndex = (j+startRow);
                    
                    child = r.node.getAttribute("response");
                    category = !r.node.getAttribute("unid");  
                    categoryTotal = r.node.getAttribute("categorytotal");
        
   		          for(var i = 0; i < colCount; i++){
				    c = cs[i];
				    config = this.cm.config[i];
				    
				    p.style = "font-weight: " + config.fontWeight + ";"; 
                        p.style += " color: " + config.colour + ";"; 
                            
	                   if ((config.response && child) || category) {
                       
                            ct = ts.responseCell;
                            if (!categoryTotal) {
                            		p.cols = colCount - i;
					   }
                            q = Ext.DomQuery;
                            
                            if (category && !categoryTotal) {
                              indent = this.getNodeDepth(r.node.getAttribute("position"));                     
                              p.style += " margin-left: " + parseInt(indent * 16) + "px;";
                              
                              // Remap column to one containing the category data
                              // Due to pseudo-categories (myCat\pseudoCat etc.), this may not be the current column
                              if (!r.data[c.name] || "" == r.data[c.name]) {
                              	var found = false;
                              	
                              	for(var entry in r.data) {
                              		if (r.data[entry] && "" != r.data[entry]) {
									for(var k=0; k < cs.length; k++) {
										if (cs[k].name == entry) {
											i = k;
											c = cs[k];
											found = true;
										}
									}                              		
                              		}
                              	}
                              	
                              	if (!found) {
                              		r.data[c.name] = "(Not Categorized)";
                              	}
                              }
                              
                            } 			

					   if (categoryTotal) {
                            	ct = (!r.data[c.name] || r.data[c.name] == "") ? ts.cell : ts.categoryCell;
                            }
                            
					   if (!category) {
                            	indent = q.selectNode("entrydata[name='" + c.name + "']", r.node).getAttribute("indent");
                            	p.style = "margin-left: " + parseInt(this.cm.getColumnWidth(i) + parseInt(indent * 16)) + "px";
					   }                    
	                       p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
					   p.id = c.id;
                            p.css = p.attr = "";
                            p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);          
                      
                       	   if (!categoryTotal) {
                            	i = colCount - 1;
                            
                            	//Set the width of the column cell, so that table fills its container - important if only categories are loaded
                            	if (j == 0) {
                            		var totalWidth = 0;
                            		for(var z = 0, colLen = this.cm.getColumnCount(); z < colLen; z++){
                					var w = this.cm.getColumnWidth(z);
               					totalWidth += w;
					   		}
						
					   		p.colWidth = parseInt(totalWidth) + "px";
                              }
					   }                      
				    } else {
				    	   p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
				    	   p.id = c.id;
                        	   p.css = p.attr = "";
                        	   p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
				    }
                      
                        if(p.value == undefined || p.value === "") p.value = "&#160;";
                        if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
                            p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
                        }
                        var markup = ct.apply(p);
                        if(!c.locked){
                            cb+= markup;
                        }else{
                            lcb+= markup;
                        }
                    }
                    var alt = [];
                    if(stripe && ((rowIndex+1) % 2 == 0)){
                        alt[0] = "x-grid-row-alt";
                    }
                    if(r.dirty){
                        alt[1] = " x-grid-dirty-row";
                    }
                    rp.cells = lcb;
                    if(this.getRowClass){
                        alt[2] = this.getRowClass(r, rowIndex);
                    }
                    rp.alt = alt.join(" ");
                    lbuf+= rt.apply(rp);
                    rp.cells = cb;
                    buf+=  rt.apply(rp);
                }
				
				// cleanup
				ts = null;
				ct = null;
				rt = null;
                cb = null;
				lcb = null;
				c = null;
				p = null;
				rp = null;
				r = null;
                child = null;
				category = null;
				q = null;
				indent = null;
				config = null;
				categoryTotal = null;
								
                return [lbuf, buf];
            } :
            function(cs, rs, ds, startRow, colCount, stripe){
                var ts = this.templates, ct = ts.cell, rt = ts.row;
                // buffers
                var buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r;
 			    var child, category, q, indent, config, categoryTotal, sortCat;
 	        
                for(var j = 0, len = rs.length; j < len; j++){
                
                    r = rs[j]; cb = []; lcb = []; rowIndex = (j+startRow);
                    child = r.node.getAttribute("response");
                    sortCat = r.node.getAttribute("sortcategorize");
                    category = !r.node.getAttribute("unid");
                    categoryTotal = r.node.getAttribute("categorytotal");
                              
                    for(var i = 0; i < colCount; i++){
                    
                        c = cs[i];
                        
                        config = this.cm.config[i];
                        p.style = "font-weight: " + config.fontWeight + ";"; 
                        p.style += " color: " + config.colour + ";";                   
        
                        if ((config.response && child) || category) {
             
                            ct = ts.responseCell;
                            if (!categoryTotal) {
                            		p.cols = colCount - i;
					   }
               
                            q = Ext.DomQuery;   	                  
   
                            if (category  && !categoryTotal) {
                              indent = this.getNodeDepth(r.node.getAttribute("position"));
                              p.style += " margin-left: " + parseInt(indent * 16) + "px;";
                          
                          	var found = true;
                          
     					// Remap column to one containing the category data
                              // Due to pseudo-categories (myCat\pseudoCat etc.), this may not be the current column
                              if (!r.data[c.name] || r.data[c.name] == "") {
                              	found = false;
                              	
                              	for(var entry in r.data) {
                              		if (r.data[entry] && "" != r.data[entry]) {
									for(var k=0; k < cs.length; k++) {
										if (cs[k].name == entry) {
											i = k;
											c = cs[k];
											found = true;
										}
									}                              		
                              		}
                              	}
                              }
                          
                              if (!found) {
                              	r.data[c.name] = "(Not Categorized)";
                              }

                            }
                            
                            if (categoryTotal) {
                            	ct = (!r.data[c.name] || r.data[c.name] == "") ? ts.cell : ts.categoryCell;
                            }
                            
                           if (!category  && !categoryTotal) {
                            	indent = q.selectNode("entrydata[name='" + c.name + "']", r.node).getAttribute("indent");
                            	p.style = "margin-left: " + parseInt(this.cm.getColumnWidth(i) + parseInt(indent * 16)) + "px";
					   }                    
	                       p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
					   p.id = c.id;
                            p.css = p.attr = "";
                            p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);          

					   if (!categoryTotal) { 
                            	i = colCount - 1;
                        	  
                            	//Set the width of the column cell, so that table fills its container - important if only categories are loaded      
					  	if (j == 0) {                      
                            		var totalWidth = 0;
                            		for(var z = 0, colLen = this.cm.getColumnCount(); z < colLen; z++){
                					var w = this.cm.getColumnWidth(z);
               					totalWidth += w;
					   		}
						
					   		p.colWidth = parseInt(totalWidth) + "px";
					  	}
					
					  }
					     
				    } else {
				    	   p.cellId = "x-grid-cell-" + rowIndex + "-" + i;
				    	   p.id = c.id;
                        	   p.css = p.attr = "";
                        	   p.value = c.renderer(r.data[c.name], p, r, rowIndex, i, ds);
				    }
                                            
                        if(p.value == undefined || p.value === "") p.value = "&#160;";
                        if(r.dirty && typeof r.modified[c.name] !== 'undefined'){
                            p.css += p.css ? ' x-grid-dirty-cell' : 'x-grid-dirty-cell';
                        }
                        var markup = ct.apply(p);
                        if(!c.locked){
                            cb[cb.length] = markup;
                        }else{
                            lcb[lcb.length] = markup;
                        }
                    }
                    var alt = [];
                    if(stripe && ((rowIndex+1) % 2 == 0)){
                        alt[0] = "x-grid-row-alt";
                    }
                    if(r.dirty){
                        alt[1] = " x-grid-dirty-row";
                    }
                    rp.cells = lcb;
                    if(this.getRowClass){
                        alt[2] = this.getRowClass(r, rowIndex);
                    }
                    rp.alt = alt.join(" ");
                    rp.cells = lcb.join("");
                    lbuf[lbuf.length] = rt.apply(rp);
                    rp.cells = cb.join("");
                    buf[buf.length] =  rt.apply(rp);
                }
				
				// cleanup
				ts = null;
				ct = null;
				rt = null;
                cb = null;
				lcb = null;
				c = null;
				p = null;
				rp = null;
				r = null;
 			    child = null;
				category = null;
				q = null;
				indent = null;
				config = null;
				categoryTotal = null;
				sortCat = null;
				
                return [lbuf.join(""), buf.join("")];
            },
            
            updateHeaderSortState : function(){
        		var state = this.ds.getSortState();
        		if(!state){
            		return;
        		}
        		
        		this.sortState = state;
        		var sortColumn = this.cm.findColumnIndex(state.field);
        		if(sortColumn != -1){
            		var sortDir = state.direction;
            		var sc = this.sortClasses;
            		var hds = this.el.select(this.headerSelector).removeClass(sc);
            		if (sortDir != "") { hds.item(sortColumn).addClass(sc[sortDir == "DESC" ? 1 : 0]); }
        		}
				
				// cleanup
				state = null;
				sortColumn = null;
    		  },
    
            updateSplitters : function(){
        		var cm = this.cm, s = this.getSplitters();
        		if(s && cm){ // splitters not created yet
            		var pos = 0, locked = true;
            		for(var i = 0, len = cm.getColumnCount(); i < len; i++){
                		if(cm.isHidden(i)) continue;
                		var w = cm.getColumnWidth(i);
                		if(!cm.isLocked(i) && locked){
                   			pos = 0;
                    		locked = false;
                		}
               		pos += w;
               		if (typeof s[i] != "undefined") {
                			s[i].style.left = (pos-this.splitOffset) + "px";
                		}
            		}
        		}
				
				// cleanup
				cm = null;
				s = null;
    		  },
    
            getNodeDepth : function(sPos) {
    
    			var iDepth = 0;
    
    			if (sPos) {
        			var aDepth = sPos.split(".");
        			iDepth = aDepth.length - 1;	
    			} else {
        			iDepth = 0;
    			}
    			return iDepth;
		}

});

 Ext.nd.UIView.prototype.getViewDesign = function() {
    // TODO: need a failure function
    var cb = {
      success : this.getViewDesignCB, 
      failure : this.getViewDesignFailure,
      scope: this
    };    
    Ext.lib.Ajax.request('GET', this.viewUrl + '?ReadDesign&nocache=' + encodeURIComponent(new Date()), cb); // RW - changed to GET cause of proxy issues
  };
  
Ext.nd.UIView.prototype.getViewDesignCB = function(o) {
    
		if ( typeof o.getResponseHeader.NotLoggedIn == "string" && o.getResponseHeader.NotLoggedIn == "True") {window.location.href = "/";};
		var q = Ext.DomQuery;
		
		var arColumns = q.select('column',o.responseXML);
  
		this.designAttrs = q.selectNode("viewdesign", o.responseXML);
        	var arColumnConfig = [];
    		var arRecordConfig = [];
  
    		for (var i=0; i<arColumns.length; i++) {

        		if (i==0 && this.showSingleCategory) {
           		continue;
        		}
        
				var col = arColumns[i];
        		var columnnumber = q.selectNumber('@columnnumber',col);
        		columnnumber = (this.showSingleCategory) ? columnnumber - 1 : columnnumber;
        
        		var tmpName = q.selectValue('@name',col,'');
        		var name = (tmpName == undefined) ? 'columnnumber_' + columnnumber : tmpName;
        
        		var tmpTitle = q.selectValue('@title',col,"&nbsp;");
        		var title = (tmpTitle == undefined) ? "&nbsp;" : tmpTitle;
        		var width = q.selectNumber('@width',col) * 1.41;
        		
        		var response = q.selectValue('@response',col,false);
        		var responseValue = (response) ? true : false;
  
        		var twistie = q.selectValue('@twistie',col,false);
        		var twistieValue = (twistie) ? true : false;
  
	        	var listseparatorValue = q.selectValue('@listseparator',col,'none');
        	
				var resize = q.selectValue('@resize',col,false);
        		var resizeValue = (resize) ? true : false;
        
        		var sortcategorize = q.selectValue('@sortcategorize',col,false)
        		var sortcategorizeValue = (sortcategorize) ? true : false;
        
        		var resortascending = q.selectValue('@resortascending',col,false);
        		var resortascendingValue = (resortascending) ? true : false;
              	
				var resortdescending = q.selectValue('@resortdescending',col,false);
        		var resortdescendingValue = (resortdescending) ? true : false;
              	
				var resorttoview = q.selectValue('@resorttoview',col,false);
        		var resorttoviewValue = (resorttoview) ? true : false;
        		var resortviewunidValue = (resorttoview) ? q.selectValue('@resortviewunid',col,"") : "";
           
        		var isSortable = (resortascendingValue || resortdescendingValue || resorttoviewValue) ? true : false;
  
        		var icon = q.selectValue('@icon',col,false);
        		var iconValue = (icon) ? true : false;
  
        		var align = q.selectValue('@align',col,false);
        		var alignValue = (align) ? ((align == "2") ? 'center' : 'right') : 'left';

        		var headerAlign = q.selectValue('@headeralign',col,false);
        		var headerAlignValue = (headerAlign) ? ((headerAlign == "2") ? 'center' : 'right') : 'left';

        		var tmpDateTimeFormat   = q.select('datetimeformat',col)[0];
        		var datetimeformat = {};
				
	       	 	datetimeformat.show  = q.selectValue('@show',tmpDateTimeFormat);
        		datetimeformat.date  = q.selectValue('@date',tmpDateTimeFormat);
        		datetimeformat.time  = q.selectValue('@time',tmpDateTimeFormat);
        		datetimeformat.zone  = q.selectValue('@zone',tmpDateTimeFormat);
     
        		var columnConfig = {
           		header: title,
           		align: alignValue,
           		dataIndex: name,
           		width: width,
           		renderer: this.dominoRenderer.createDelegate(this), 
           		sortable: isSortable, 
           		resortascending: resortascendingValue,
           		resortdescending: resortdescendingValue,
           		resortviewunid: resortviewunidValue,
           		sortcategorize: sortcategorizeValue,
           		resize: resizeValue,
           		listseparator: listseparatorValue,
           		response: responseValue,
           		twistie: twistieValue,
           		icon: iconValue,
           		datetimeformat: datetimeformat
        		};
  
        		var recordConfig = {
           		name: name, 
           		mapping: 'entrydata[@name="' + name + '"]'
        		};          
  
        		arColumnConfig.push(columnConfig);
        		arRecordConfig.push(recordConfig);
				
				// cleanup
				columnConfig = null;
				recordConfig = null;
			}
    
    		this.dominoView = {
        		meta : {
           		root : 'viewentries',
           		record : 'viewentry',
           		totalRecords : '@toplevelentries',
           		id : '@position',
           		columnConfig : arColumnConfig
        		},
        		recordConfig : arRecordConfig
    		};

    		this.createGrid();
			//this.toolbar == false ? '' : Ext.DomHelper.applyStyles(this.toolbar.container, 'visibility: visible;');
			
			// cleanup
			arColumns = null;
			arColumnConfig = null;
			arRecordConfig = null;
        
  	};
	
	
  Ext.nd.UIView.prototype.createGrid = function() {
    	var sViewParams = (this.viewParams == undefined) ? "" : this.viewParams;
   
   		this.reader = new Ext.nd.data.DominoViewXmlReader(	this.dominoView.meta, this.dominoView.recordConfig);
   
   	 	this.cm = new Ext.grid.DefaultColumnModel(this.dominoView.meta.columnConfig);
   	 	
	    	this.ds = new Ext.nd.data.DominoViewStore({
        		proxy: new Ext.data.HttpProxy({
            		url: this.viewUrl + '?ReadViewEntries&CollapseView&nocache=' + encodeURIComponent(new Date()),
            		method: "GET"
        		}),
        		baseParams: this.baseParams,
				reader: this.reader,
        		remoteSort: false
    		});

    		if (this.grid) {
      		try {
         			this.grid.destroy();
      		} catch (e) {}
    		}
			
			var expandCol;
			if (this.designAttrs.getAttribute("extendlastcolumn")== "false" ) {
				expandCol = false;
			} else {
				expandCol = this.cm.getColumnId( this.cm.getColumnCount()-1 ).toString();
			}
			
			var autoSize = false;
			if ( expandCol != false && expandCol == "0" ) { 
				autoSize = true;
			}

    		var dh = Ext.DomHelper;
    		var container = (this.container.getEl) ? this.container.getEl() : this.container;
			
//    		this.grid = new Ext.nd.grid.DominoGrid(dh.append(document.body,{tag: 'div'}), {
//    		this.grid = new Ext.nd.grid.DominoGrid(dh.append(Ext.get('content'), {tag: 'div'}), {
    		this.grid = new Ext.nd.grid.DominoGrid(container, {
      		  ds: this.ds,
      		  cm: this.cm,
      		  selModel: this.selModel ? this.selModel : (new Ext.grid.RowSelectionModel({singleSelect : ( this.singleSelect ? this.singleSelect : true )})),
      		  enableDragDrop: true,
      		  ddGroup: 'TreeDD',
      		  autoExpandColumn: expandCol,
			  //autoHeight: true,
			  enableColLock: false
    		});

/*    		var layout = Ext.BorderLayout.create({
      		center: {
         			panels: [new Ext.GridPanel(this.grid, {toolbar: this.toolbar, fitToFrame : true})] 
      		}
    		}, container); */
    
          	this.grid.on('rowclick', this.gridHandleRowClick, this);
			this.grid.addListener('rowdblclick',this.gridHandleRowDblClick, this, true);
    		this.grid.addListener('keydown',this.gridHandleKeyDown, this, true);
    		this.grid.addListener('rowcontextmenu',this.gridHandleRowContextMenu, this, true);
    		this.grid.addListener('headerclick',this.gridHandleHeaderClick, this, true);
			
    		this.ds.load({params:{count : this.count}});
      		this.grid.render();
			
// ADD THE ACTIONBAR //
  var tb;
  
  if (this.showActionbar) {
      //if (!this.toolbar) {
         //tb = Ext.DomHelper.append(document.body,{tag: 'div'});
		 //Ext.DomHelper.applyStyles(tb, 'visibility: hidden;');
         //this.toolbar = new Ext.nd.Actionbar({
		 
		 var gridHead = this.grid.getView().getHeaderPanel(true);
		 
         tb = this.grid.toolbar = new Ext.nd.Actionbar({
            //container: tb, 
			//container: this.grid, 
			container: gridHead, 
            noteType: 'view', 
            noteName: this.viewName, 
            useDxl: true
         });
         
         //this.toolbar.addSeparator();

         if (this.showSingleCategory && this.showCategoryComboBox) {
            var store = new Ext.data.Store({
               proxy: new Ext.data.HttpProxy({
                  method:'GET', 
                  url: this.viewUrl + '?ReadViewEntries&CollapseView&count=' + this.categoryComboBoxCount + '&randomizer='+new Date().getTime()
               }),
               reader: new Ext.data.XmlReader({
                     record: 'viewentry',
                     totalRecords: '@toplevelentries',
                     id: '@position'
                  },[{name:'text'}]
               )
            });
            store.load();
            
            var combo = new Ext.form.ComboBox({
                store: store,
                displayField: 'text',
                typeAhead: true,
                mode: 'local',
                triggerAction: 'all',
                emptyText: this.emptyText,
                value: this.showSingleCategory,
                selectOnFocus: true,
                grow: true,
                resizable: true,
				listWidth: 300
            });
			
	 		if( this.singleCategoryText ) this.grid.toolbar.addText( this.singleCategoryText ); // this.toolbar.addText( this.singleCategoryText );
			//this.toolbar.addField(combo);
			this.grid.toolbar.addField(combo);
            //this.toolbar.addSeparator();
			this.grid.toolbar.addSeparator();
			
			combo.on('beforeselect',function() { 
              if( this.isSearching ) { 
                //Ext.MessageBox.alert("Error","You must clear the search results before changing categories");
                //return false; // Cancel the select
				this.handleClearSearch();
              }
            }, this );
            combo.on('select', this.handleCategoryChange.createDelegate(this));
			
			// cleanup
			store = null;
			combo = null;
         }
		 
		 this.searchInPagingToolbar = true;
		 if (this.showSearch && !this.searchInPagingToolbar) {
           //this.createSearch(this.toolbar);
		   this.createSearch(this.grid.toolbar);
		 }

        /*if (this.showSearch) {
          this.searchField = new Ext.form.TextField({
            emptyText: "Search view...",
            name: "extnd-vw-search",
            width: 100
          });
          this.toolbar.addField(this.searchField);
          this.toolbar.addButton({text: "Find", scope: this, handler: this.handleViewSearch});
		  this.toolbar.addSeparator();
        }*/
//        if ( !( (this.showSingleCategory && this.showCategoryComboBox) || (this.showSearch && !(this.searchInPagingToolbar))) ) {this.toolbar.addSeparator(); }
//        if ( !( (this.showSingleCategory && this.showCategoryComboBox) || (this.showSearch && !(this.searchInPagingToolbar))) ) {this.grid.toolbar.addSeparator(); }
	  
//	    }
    } 

// DONE ADDING THE ACTION BAR //

			
			var gridFoot = this.grid.getView().getFooterPanel(true);
    		this.paging = new Ext.nd.DominoPagingToolbar(gridFoot, this.ds, {pageSize: this.count});
			
   			//bds added 7-28
    		if (this.showSearch && this.searchInPagingToolbar) {
      			this.createSearch(this.paging);
	    	}
					
			// cleanup
			//container, layout = null;
			container = null;
			gridFoot = null;

	};

Ext.nd.UIView.prototype.dominoRenderer = function(val, cell, row, rowIdx, colIdx, ds) {
	
		if (typeof val == "undefined" || val == null) { return ""; }
	
	 	var config = this.dominoView.meta.columnConfig[colIdx];
	 	var output = "";
	 	var isResponse = false;
	 
	 	//Check whether we have a category or a document with responses
	 	if (config.twistie && val != "" && !config.icon) {
	 		if (row.node) {
		 		output += (row.node.getAttribute("children")) ? "<img id='" + Ext.id() + "' class='ext-nd-ed-twistie' src='/icons/expand.gif' />" : "<img class='ext-nd-ed-blank' src='/icons/ecblank.gif' />";
		 	}
	 	}
	
		if (config.icon) {
	
			if (val == "" || val == 0 || val == null) {
          		output += "<img id='" + Ext.id() + "' class='ext-nd-ed-icon' src='/icons/ecblank.gif' />";
          	} else {
				if (!isNaN(val)) {
          			var sIcon = "00" + val;
               		sIcon = sIcon.substr(sIcon.length - 3, 3);
               		var url = "/icons/vwicn" + sIcon + ".gif" ;
                             
					output += "<img id='" + Ext.id() + "' class='ext-nd-ed-icon' src='" + url + "' />";
				}
			}
		
		} else {
			output += val;
		}
		
		// cleanup
		config = null;
	
		return output;
	
	};
	
Ext.nd.UIView.prototype.gridHandleRowClick= function(grid, rowIndex, e) {
		var el = e.getTarget();
		var row = grid.selModel.getSelected();
		var node = row.node;
		
		if (node) {
		
			var unid = (node.getAttribute("unid")) ? node.getAttribute("unid") : node.getAttribute("noteid");
			var position = node.getAttribute("position");
			var children = node.getAttribute("children");
				
			if (el.className == "ext-nd-ed-twistie") {
				this.retrieveChildNodes(row, el.id, unid, position, children);
			}
		}
		
		// cleanup
		el = null;
		row = null;
	};

Ext.nd.UIView.prototype.renderChildNodeData = function(o, success, resp) {
		if ( typeof resp.getResponseHeader.NotLoggedIn == "string" && resp.getResponseHeader.NotLoggedIn == "True") {window.location.href = "/";};
		
		var row = this.grid.selModel.getSelected();
		var node = row.node;
		row.childRowsLoaded = true;
		
		var unid = (node.getAttribute("unid")) ? node.getAttribute("unid") : node.getAttribute("noteid");
	
		var doc = resp.responseXML;
		var root = doc.documentElement || doc;
		
		var ds = this.grid.getDataSource();
		var index = ds.indexOf(row);

		//Read in the child records
		var childRecords = this.reader.readRecords(root);
	
		for (var i = 0; i < childRecords.records.length; i++) {

			//Handle hidden documents that contain readers fields
			if (this.getNodeDepth(childRecords.records[i].id) <= this.getNodeDepth(row.id)) { break; }

			ds.insert(++index, childRecords.records[i]);
		}
		
		//BDS added 10-29-07
		//var gridEl = this.grid.getGridEl();
		var gridEl = this.grid.container;
		gridEl.unmask();
		
		// cleanup
		row = null;
		doc = null;
		root = null;
		ds = null;
	};
	
	
Ext.nd.UIView.prototype.retrieveChildNodes = function(row, elementId, unid, position, children) {

		var oTwistie = Ext.getDom(elementId);
		var view = this.grid.getView();
		var selModel = this.grid.selModel;
		var rowIdx = this.ds.indexOf(row);
		var parentRowId = row.id;
		var currentRowId = null;
		var q = Ext.DomQuery;
		var tr = null;

		if (oTwistie) {
			var bIsCollapsed = (oTwistie.src.indexOf("expand") >= 0) ? true : false;
			if (bIsCollapsed) {
				oTwistie.src = oTwistie.src.replace(/expand/g, "collapse");
								
				if (!row.childRowsLoaded) {
					var childNodeData = new Ext.data.Connection();
					
					var sRestrictUrl =  (this.showSingleCategory) ? "&RestrictToCategory=" + this.showSingleCategory : ""
					
					//BDS added 10-29-07
					//var gridEl = this.grid.getGridEl();
					var gridEl = this.grid.container;
					gridEl.mask('Loading...','x-mask-loading');
					// - end add
					
					childNodeData.request({
						url: this.dbPath + this.viewName + "?ReadViewEntries&Start=" + position + ".1&Count=" + children + "&Collapse=" + position + sRestrictUrl + "&nocache=" + encodeURIComponent(new Date()),
						method: "GET",
						callback: this.renderChildNodeData,
						scope: this
					});
				} else {
					//Display existing child rows
					this.grid.selModel.selectNext();
					row = selModel.getSelected();
					while(row) {
						currentRowId = row.id;
					
						//Ensure we only act on child rows
						if(this.getNodeDepth(currentRowId) <= this.getNodeDepth(parentRowId)) { break; }
						
						//Make sure we only act on immediate descendants
						if(this.getNodeDepth(currentRowId) == parseInt(this.getNodeDepth(parentRowId) + 1)) {
							tr = view.getRow(this.ds.indexOf(row));
							if (tr) {
								
								tr.style.display = "";

								//Now find the twistie, and reset its state to collapsed
								oTwistie = q.selectNode("IMG[class='ext-nd-ed-twistie']", tr);
								if (oTwistie) {
									oTwistie.src = oTwistie.src.replace(/collapse/g, "expand");
								}
							}
						}
					
						selModel.selectNext();
						row = selModel.getSelected();
						if (row.id == currentRowId) { row = null };
					}
				
					selModel.selectRow(rowIdx, false);
				}
				
			} else {
				oTwistie.src = oTwistie.src.replace(/collapse/g, "expand");
				
				//Hide child rows
				this.grid.selModel.selectNext();
				row = selModel.getSelected();
				while(row) {
					currentRowId = row.id;
					
					if(this.getNodeDepth(currentRowId) <= this.getNodeDepth(parentRowId)) { break; }
					tr = view.getRow(this.ds.indexOf(row));
					if (tr) {
						tr.style.display = "none";
					}
					
					selModel.selectNext();
					row = selModel.getSelected();
					if (row.id == currentRowId) { row = null };
				}
				
				selModel.selectRow(rowIdx, false);
						
			}
		}
		
		// cleanup
		view = null;
		selModel = null;
		rowIdx = null;
		oTwistie = null;
			
	};
	
	
Ext.nd.UIView.prototype.getNodeDepth = function(sPos) {
    
    		var iDepth = 0;
    
    		if (sPos) {
    			var aDepth = sPos.split(".");
        		iDepth = aDepth.length - 1;	
    		} else {
        		iDepth = 0;
    		}
    		return iDepth;
	};
	

//Fixes Extra blank button on view toolbars
Ext.nd.Actionbar.contructor = function(config){
  var sess = Ext.nd.Session; 
  var db = sess.CurrentDatabase;
   
  
  this.dbPath = db.WebFilePath;
  this.noteType = '';
  this.noteName = '';
  this.useDxl = false;
  
  Ext.apply(this, config);
  //Ext.extend(this, Ext.Toolbar);
  Ext.nd.Actionbar.superclass.constructor.call(this, config.container);
  
  this.noteUrl = (this.noteUrl) ? this.noteUrl : this.dbPath + this.noteName;
  
  
  if (this.noteName == '') {
    var vni = this.noteUrl.lastIndexOf('/')+1;
    this.dbPath = this.noteUrl.substring(0,vni);
    this.noteName = this.noteUrl.substring(vni);
	
	// cleanup
	vni = null;
  }

/*  if(this.useDxl) {
    this.add({text:'&nbsp;', id:'xnd-tb-tmp'});
  }*/
  
  
  this.createToolbar();

  // cleanup
  sess = null;
  db = null;
};

//Fix for the new grid layouts - the entire class was overridden even though we only needed to change the handleok function
Ext.nd.UIWorkspace.prototype = {

  
  PickList : function(config) {
    var dialog, cb;
    var sess = Ext.nd.Session; 
    var db = sess.CurrentDatabase;

    
    this.server = "";
    this.dbPath = db.WebFilePath;
    this.viewName = "";
    this.width = 500;
    this.height = 400;
    this.shadow = true;
    this.minWidth = 500;
    this.minHeight = 400;
    this.type = "custom";
    this.select = "single";

    this.title = "PickList";
    this.prompt = "Please make your selection(s) and click <OK>.";
    this.column = 0;

    
    this.showSingleCategory = null;
    this.emptyText = 'Select a category...';
    this.showCategoryComboBox = false;
    this.categoryComboBoxCount = -1;
	this.showActionbar = false;   
    
    Ext.apply(this,config);

    
    this.viewUrl = (this.viewUrl) ? this.viewUrl : this.dbPath + this.viewName;

    
    if (this.callback) {
       cb = this.callback;
       this.callback = false;
    }

    
    var pl = Ext.get('xnd-picklist');
    if (pl) {
       pl.remove(); 
    }
    if (this.uiView) {
       if (this.uiView.grid) {
          this.uiView.grid.destroy(); 
       }
    }

    
    if(!dialog){ 
      dialog = new Ext.LayoutDialog('xnd-picklist', { 
        autoCreate: true,
        modal:true,
        width:this.width,
        height:this.height,
        shadow:this.shadow,
        minWidth:this.minWidth,
        minHeight:this.minHeight,
        title:this.title,
        north : {
          titlebar : true
        },
        center : {
          autoScroll:true
        }
      });
      dialog.addKeyListener(27, handleOK, this);
      dialog.addButton('OK', handleOK, this);
      dialog.addButton('Cancel', handleCancel, this);

      
      var layout = dialog.getLayout();
      layout.beginUpdate();

      
      var promptPanel = layout.add('north', new Ext.ContentPanel('xnd-picklist-prompt', {autoCreate : true, title : this.prompt}));

      
      var viewPanel = layout.add('center', new Ext.ContentPanel('xnd-picklist-view', {
        autoCreate : true,
        title : this.title,
        closable : false,
        fitToFrame : true
      }));

      
      this.uiView = new Ext.nd.UIView({
        container : viewPanel,
        viewUrl : this.viewUrl,
        gridHandleRowDblClick : handleOK.createDelegate(this),
        showSingleCategory : this.showSingleCategory,
		singleCategoryText: this.singleCategoryText,
        emptyText : this.emptyText,
		showActionbar: this.showActionbar,
		showSearch : this.showSearch,
        showCategoryComboBox : this.showCategoryComboBox,
        categoryComboBoxCount : this.categoryComboBoxCount,
		selModel: new Ext.grid.RowSelectionModel( {singleSelect: (( this.select == "single") ? true : false ) } )
      });

      
      layout.endUpdate();

    } 
      
    
    dialog.show();

    function handleOK() {
      var arSelections = this.uiView.grid.getSelections();
      var arReturn = new Array();
      dialog.hide();

      for (var i=0; i<arSelections.length; i++) {
        var map = arSelections[i].fields.keys[this.column];
        var data = arSelections[i].data[map];
        //for (var d=0; d<data.length; d++) {
          arReturn.push(data);
        //}
      }

      
      if (cb) {
        cb(arReturn);
      } else {
        return arReturn; 
      }
    }

    function handleCancel() {
      dialog.hide();
      if (cb) {
        cb(null);
      } else {
        return null;
      }
    }

  },


  Prompt : function() {
    var cb;
    this.type = "ok";
   
    if (arguments.length > 0) {
      if (typeof arguments[0] == "object") {
        
        Ext.apply(this,arguments[0]);
      } else if (arguments.length >= 3) {
        this.type = arguments[0];
        this.title = arguments[1];
        this.prompt = arguments[2];   
      }
    }
   
    
    if (this.callback) {
      cb = this.callback;
      this.callback = false;
    }

    
    this.type = this.type.toLowerCase();
   
    switch (this.type) {
      case "ok" :
        Ext.MessageBox.alert(this.title, this.prompt, cb);
        break;
         
      default :
         Ext.MessageBox.alert("type '" + this.type + "', not yet supported");
    } 

  
  }
};

Ext.namespace('Ext.nd.ux.util');
Ext.nd.ux.util.Format = function(){

	return {
	
		fromIso8601String : function(sDate) {
  
            	var regexp = 	'^([0-9]{4})[-/.]?([0-9]{1,2})[-/.]?' 	+ 
							   	'([0-9]{1,2})(T?([0-9]{1,2})([-:.]?' 	+
								'([0-9]{1,2})([-:.]?([0-9]{1,2})' 		+
								'(,([0-9]{1,3}))?)?)?)?((Z)' 			+
								'|([+-])([0-9]{1,2})([-:.]?' 				+
								'([0-9]{1,2})([-:.]?([0-9]{1,2}))?)?)?$';	
            	var r 			= 	sDate.match(new RegExp(regexp));
            
            	if (r == null) { return null; }
            
            	var y		=	r[1];
            	var mo	=   r[2];
            	var d		=	r[3];
            	
			if (r.length > 5) {
               	var h = ("" != r[5]) ? h = r[5] : 0;
              		if (r.length > 7) {
                 		var mi = ("" != r[7]) ? r[7] : 0;
                 		if (r.length > 9) {
	                		var s = ("" != r[9]) ? r[9] : 0;	
	                		var ms = (r.length > 11 && "" != r[11] && r[11]) ? r[11] * Math.pow(10, 3 - r[11].length) : 0;
                 		}
              		}
         		}

              	//var oDate = new Date(Date.UTC(y, mo - 1, d, h, mi, s, ms));
				var oDate = new Date(y, mo - 1, d, h, mi, s, ms);
              	var o = -1 * oDate.getTimezoneOffset() * 60;
              	if (r.length > 14 && "" != r[14] && "" != r[15]) {
                   	o = 	(('+' == r[14]) ? 1 : -1) * r[15] * 60 * 60;
                   	o += 	(("" != r[17]) && r[17]) ? r[17] * 60 : 0; 
                   	o += 	(("" != r[19]) && r[19]) ? r[19] : 0;
              	}

              oDate.setTime(parseInt(oDate.getTime()) - (o * 1000));
              
              return oDate;
          },

		date : function(v, format){
            if(!v){
                return "";
            }
            if(!(v instanceof Date)){
                if (this.fromIso8601String(v)) {
		             v= this.fromIso8601String(v);
              	       return v.format(format || "m/d/Y");
                } else {
                	return v;
                }
            }

        }

    };
}();

//BDS added 10-29-07
/*
Ext.nd.data.DominoViewStore = function(config){
	Ext.nd.data.DominoViewStore.superclass.constructor.call(this, config);
};

Ext.extend(Ext.nd.data.DominoViewStore, Ext.data.Store, {

	load : function(options){
     	   options = options || {};
	        if(this.fireEvent("beforeload", this, options) !== false){
     	       this.storeOptions(options);
          	  var p = Ext.apply(options.params || {}, this.baseParams);
			  delete p["ResortAscending"];
	            delete p["ResortDescending"];
	            	 	            	 
	            if (this.sortInfo && this.remoteSort) {    
	            	 if (this.sortInfo.name != "") {	            	 
     	           	p[this.sortInfo.name] = this.sortInfo.value;
     	           }
	            }
	            p = Ext.apply(p, {nocache : new Date()});
     	       this.proxy.load(p, this.reader, this.loadRecords, this, options);
	        }
    	},
    	
    	setDefaultSort : function(field, dir){
        	this.sortInfo = { field: field, direction: dir ? dir.toUpperCase() : "ASC" };
    	},
    
	sort : function(fieldName, dir){

        	var f = this.fields.get(fieldName);
        	var col = this.reader.meta.colState[f.name];

        	var sortType = col.getSortType();
		if (sortType > 0) {
			var currentSortState = col.getSortState();
			currentSortState++;
			col.setSortState(currentSortState);
	
			switch (sortType) {
				case 1:
					if (col.getSortState() > 1) { col.setSortState(0); }
					if (col.getSortState() == 0) {
							dir = null;
					} else {
							dir = "ASC";
					}
				break;
				
				case 2:
					if (col.getSortState() > 1) { col.setSortState(0); }
					if (col.getSortState() == 0) {
						dir = null;
					} else {
						dir = "DESC";
					}
				break;
			
				case 3:
					if (col.getSortState() > 2) { col.setSortState(0); }
					if (col.getSortState() == 0) {
						dir = null;
					} 
					if (col.getSortState() == 1) {
						dir = "ASC";
					}
					if (col.getSortState() == 2) {
						dir = "DESC";
					}
				break;
			}
		}

        	this.sortToggle[f.name] = dir;

		var sortInfo = null;

		switch(dir) {
			
			case "ASC":
				sortInfo = { field: f.name, direction: dir, name: "ResortAscending", value: col.getColumnNumber() };
			break;
			
			case "DESC":
				sortInfo = { field: f.name, direction: dir, name: "ResortDescending", value: col.getColumnNumber() };			
			break;
			
			default:
				sortInfo = { start: 1, count: 30, field: f.name, direction: "", name: "", value: "" };			
		}
		
        	this.sortInfo = sortInfo;

        	if(!this.remoteSort){
            	this.applySort();
            	this.fireEvent("datachanged", this);
        	} else {
            	this.load(this.lastOptions);
        	}

    	}
    	
});*/

