tojo.require("dijit.dijit");
tojo.require("dijit.Declaration");
tojo.require("dijit.layout.ContentPane");
isLocalTest=false;

tojo.require("tojo.data.ItemFileReadStore");
tojo.require("tojo.cookie");
tojo.require("tojo.date");
tojo.require("tojo.date.stamp");
tojo.require("dijit.layout.TabContainer");
tojo.require("dijit.Dialog");
tojo.require("dijit.Tooltip");
tojo.require("dijit.Tree");
tojo.require("tojo.parser");



tojo.registerModulePath("tfa", tfaConfig.TFACommonPath +"js/tfa");



////////fix/move this?
var MONTH_NAMES= new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');

var querystringObj; //global. need this?
 



tojo.require("tfa.util");
tojo.require("tfa.widget.global");





//REMOVE this soon.... 

tojo.declare("wcmContainer",dijit.layout.ContentPane, {

		"class":"wcmContainer",
		//commented out since personalization is not used with this release
		//wcmRequestParams:null,
		arrConnectList:null,
		disableHistory:false,
		scrollToTop:false,

	_downloadExternalContent: function(){
		this._onUnloadHandler();

		// display loading message
		this._setContent(
			this.onDownloadStart.call(this)
		);
		
		var self = this;
		var getArgs = {
			preventCache: (this.preventCache || this.refreshOnShow),
			url: this.href,
			handleAs: "text"
		};
		if(tojo.isObject(this.ioArgs)){
			tojo.mixin(getArgs, this.ioArgs);
		}

		// replaced tfautil xhrPost  with tfautil loggingXhrPost EK 6/9/09 
		var hand = this._xhrDfd =(tfautil.loggingXhrPost)(getArgs);  

		// replaced xhrGet with tfautil xhrPost EK
		//var hand = this._xhrDfd = (tfautil.xhrPost)(getArgs);

		hand.addCallback(function(html){
			try{
				self.onDownloadEnd.call(self);
				self._isDownloaded = true;
				self.setContent.call(self, html); // onload event is called from here
			}catch(err){
				self._onError.call(self, 'Content', err); // onContentError
			}
			delete self._xhrDfd;
			return html;
		});

		hand.addErrback(function(err){
			if(!hand.cancelled){
				// show error message in the pane
				self._onError.call(self, 'Download', err); // onDownloadError
			}
			delete self._xhrDfd;
			return err;
		});
		
	},

	setContent:function(data) {

		// summary:
		//		Replaces old content with data content, include style classes from old content
		//	data:
		//		the new Content may be String, DomNode or NodeList
		//
		//		if data is a NodeList (or an array of nodes) nodes are copied
		//		so you can import nodes from another document implicitly

		// clear href so we cant run refresh and clear content
		// refresh should only work if we downloaded the content
		if(!this._isDownloaded){
			this.href = "";
			this._onUnloadHandler();
		}

		if (typeof data  == "string" && data.indexOf("wcmContainer")>=0)	{	
				var i1= data.indexOf("div");
				i1= data.indexOf(">",i1);

				var i2= data.lastIndexOf("div");
				i2= data.lastIndexOf("<",i2);
				data = data.substring(i1+1,i2);
		}
		
		this._setContent(data || "");

		this._isDownloaded = false; // must be set after _setContent(..), pathadjust in tojox.layout.ContentPane

		if(this.parseOnLoad){
			this._createSubWidgets();
		}

		this._checkIfSingleChild();
		if(this._singleChild && this._singleChild.resize){
			this._singleChild.resize(this._contentBox);
		}

		this._onLoadHandler();
		
	},

	startup:function() {
		if(!this.disableHistory){
			var mstate = {
				//back: function() { this.doLoadContent("/net/wcm/myconnect/TFAnet/tfaportal/system/fellowshiplanding");},
				back: function() { location.reload(); },
				forward: function() { location.reload(); },
				stateData:"init",
				changeUrl:true
			};
			tojo.back.setInitialState(mstate);
		}

		//commented out since personalization is not used with this release
		/*
         if(typeof widgetWcmContainerRegionList == "undefined") widgetWcmContainerRegionList=[];

	//temp code - xli
//portletTitleRegionList = [{name:"blahregion", value:"ATLANTA"}];

         if(!widgetWcmContainerRegionList[this.widgetId]) {
			var ptr = portletTitleRegionList.pop();
			widgetWcmContainerRegionList[this.widgetId] = ptr;
         } 
		else 
			var ptr = widgetWcmContainerRegionList[this.widgetId];
                

		this.wcmRequestParams={};
		this.wcmRequestParams.region={};

		this.wcmRequestParams.region.paramName=ptr.name;
		this.wcmRequestParams.region.paramVal=ptr.value;
*/
//		console.debug("startup","!!!!!!!!!!!! removed personalization")
		this.inherited("startup",arguments);		
		this.postProcessWcmLinks();	

		
	},

	// EVENT's, should be overide-able
	onLoad: function(e){
		
		// summary:
		//		Event hook, is called after everything is loaded and widgetified
		this.postProcessWcmLinks();
	},

	postProcessWcmLinks: function(){
		if(this.arrConnectList){
			tojo.forEach(this.arrConnectList, function(w){
				//alert(w);
				tojo.disconnect(w);				
			}, this);
		//alert(this.arrConnectList.length);
		}	
		this.arrConnectList = new Array();
			
			//set parent widget for all children
			//tojo.query("*", this.containerNode || this.domNode).filter("[widgetId]").forEach(function(wn){ 
			//var w = dijit.byNode(wn); w.parentWidget=this;
			//},this);
			tojo.forEach(this.getDescendants(),function(w){w.parentWidget=this;},this);

			tojo.query("a", this.domNode).forEach(function(n, i, a){
			// If the link goes back to the current page and has
                        // an anchor in it, don't attach an onClick; we just
                        // want to bounce to the anchor.
                        var anchorLink = (n.href.indexOf('#') >= 0) && tfautil.isSamePage(n.href);
			if (n.href && ( n.href.indexOf('WCM_CONTEXT')>0 ||  n.href.indexOf('WCM_GLOBAL_CONTEXT')>0 || ( n.href.indexOf('/myconnect')>0 && n.href.indexOf('MOD=')<0 ) ) && !anchorLink) {
			 this.arrConnectList.push(tojo.connect(n, "onclick", this, "loadClicked"));
			 
			 //alert(n.innerHTML);
			 //tojo.connect(n, "onclick",  tojo.hitch(this, "doLoadContent", n.href));
                        }
		}, this);
	},
	loadClicked:function(evt){
		
			var objThis = this;
			var strURL = evt.target.href;
			//alert(strURL);
			//return;
			//tojo.hitch(objParent, "doLoadContent", strURL,evt)();
			tojo.hitch(this, "doLoadContent", strURL, evt)();
			if(!this.disableHistory){
				var mstate = {
					back: function() {tojo.hitch(objThis, "doLoadContent", strURL,evt)();},
					forward: function() { tojo.hitch(objThis, "doLoadContent", strURL,evt)();},			
					changeUrl:true
				};
				tojo.back.addToHistory(mstate);
				if(this.scrollToTop){
					window.scrollTo(0,0);
				}
			}
	},
	doLoadContent: function(href,evt){
		if(evt){
			tojo.stopEvent(evt);
		}	
			
		var contextArr=href.split('WCM_CONTEXT=');
		if (contextArr.length<2) contextArr= href.split("WCM_GLOBAL_CONTEXT=");
		if (contextArr.length>1) {
			//portlet specific url
			var context = contextArr[1];

			if (context.indexOf('WCM_Page')>0)
			{
				//console.debug("index > 0");
				var paramArr=context.split('&');
				var newContext=[];
				if (paramArr.length>1)
				{
					//console.debug("paramArr > 0");
					for (var i=0;i<paramArr.length;i++)
						{
							if (paramArr[i].indexOf("WCM_Page")>0)
							{
								var tmp = paramArr[i];
								var pageArr=tmp.split("WCM_Page");
								newContext.push("WCM_Page"+pageArr[1]);
								//console.debug(newContext.length);
							}
							else
								newContext.push(paramArr[i]);

						}
					context=newContext.join("&");
					//console.debug("context:"+context);
				}	
				//commented out since personalization is not used with this release
				//context=context+"&"+this.wcmRequestParams.region.paramName+"="+this.wcmRequestParams.region.paramVal;
			}
			
			

		} else {
			var context = href;		
		}

		if (context.substr(0,1)!="/") context= "/" +context;
		if (context.indexOf("/net/wcm/myconnect")<0) context= "/net/wcm/myconnect" +context; //direct wcm link (hardcoded!)
	
		// point to wcm proxy servlet to take advantage of caching
		context= context.replace("/net/wcm/myconnect","/net/PA_WCMAccessorProxy/wcmaccessorproxy?url=http://"+document.domain+"/net/wcm/myconnect");

		this.setHref(context);	
		
	},

	onDownloadStart: function(){
		
		return "<div class='loaderContainer'><div class='loader'><span><img src='" +tfautil.v.strImgPath +"loadingbar.gif'/> Loading...</span></div></div>";
		//return "<div style='position:relative;width:100%;text-align:right;background-color:blue;'><div style='position:absolute;top:0;right:0;background-color:red;z-index:99;'><span><img src='" +tfautil.v.strImgPath +"loadingbar.gif'/> Loading...</span></div></div>";
		
	}

});


tojo.declare("tfa.data.ItemFileReadStore", tojo.data.ItemFileReadStore, {

	_containsValue: function( 	item, // item //
					attribute, // attribute-name-string // 
					value, // anything //
					regexp) { // RegExp?//
		//	summary: 
		//		Internal function for looking at the values contained by the item.
		//	description: 
		//		Internal function for looking at the values contained by the item.  This 
		//		function allows for denoting if the comparison should be case sensitive for
		//		strings or not (for handling filtering cases where string case should not matter)
		//	
		//	item:
		//		The data item to examine for attribute values.
		//	attribute:
		//		The attribute to inspect.
		//	value:	
		//		The value to match.
		//	regexp:
		//		Optional regular expression generated off value if value was of string type to handle wildcarding.
		//		If present and attribute values are string, then it can be used for comparison instead of 'value'
			
		if(typeof value === "string" &&  value.indexOf("regexp:") > -1 ) {
			//console.debug("idx:"+value.indexOf("regexp:"));
			regexp = new RegExp(value.substring(7),"g"); 
		}
		//console.debug("regexp:"+regexp);

		return tojo.some(this.getValues(item, attribute), function(possibleValue){
			if(possibleValue !== null && tojo.isArray(value)) {
				var date1 =value[0];
				var date2 = value[1];
				var testdate = tojo.date.stamp.fromISOString(possibleValue);
				//console.debug(date1+" "+date2+ " "+testdate);
				if (tojo.date.compare(date1,testdate)<=0 && tojo.date.compare(date2,testdate)>=0 )	
					return true; // Boolean
			}
			else if(possibleValue !== null && !tojo.isObject(possibleValue) && regexp){
				//console.debug("possibleValue:"+possibleValue.toString());
				var ar =possibleValue.toString().match(regexp);		
				// if "AND" to be used instead of "OR" uncomment following
				//var spl=regexp.toString().split("|");
				//console.debug("split:"+spl);
				//console.debug("split#:"+spl.length);
				//console.debug("ar:"+ar);
				//if(ar && ar.length == spl.length){
				if(ar){
					//console.debug("regexp:yea");
					return true; // Boolean
				}
			}else if(value === possibleValue){
				return true; // Boolean
			}
			
		});
	}

});


tojo.declare("wcmFilter", dijit.layout._LayoutWidget, {

	inputFields: null,

	query:{},

	getChildren:function() {
			
		//	var childNodes = tojo.query(">", this.containerNode || this.domNode);
			//var children = childNodes.filter("[widgetId]");
		//	console.debug("getChildren:"+children);
			return this.getDescendants();

	},		


	postCreate:function(){
		//console.debug("wcmFilter postCreate started...")
		this.inherited("postCreate",arguments);

		this.inputFields=[];
		tojo.query("select",this.domNode).forEach(function(el, idx){
			if (tfautil.isVisible(el))
				this.inputFields.push(el);
			tojo.connect(el,"onchange",this,"_doFilter");
		},this);

		tojo.query("input",this.domNode).forEach(function(el, idx){
			if (tfautil.isVisible(el))
				this.inputFields.push(el);
			tojo.connect(el,"onclick",this,"_doFilter");
		},this);

		var isResetAllFilter = tfautil.gup("resetAllFilter");
		for (var i=0;i<this.inputFields.length ; i++)
		{
			var el =this.inputFields[i];
			//var inputval=tojo.cookie("tfa"+this.id+el.name.replace(/ /g, ""));
			var elName=el.name.replace(/ /g, "");
			var cookiename="tfa"+elName;
			var inputval = tfautil.gup(elName);
			if (inputval) {
				var inputval=inputval.replace(/\+/g, " "); 
				tojo.cookie(cookiename,inputval,{path:'/'});
			}
			else
				inputval=(isResetAllFilter)?null:tojo.cookie(cookiename);

			//console.debug("cookie param:"+cookiename+" val:"+inputval);
			
			if (inputval) {
				if (el.nodeName=="SELECT") 
					tfautil.setHtmlSelectValue(el,inputval); 
				else if (el.nodeName=="INPUT") 
					el.checked=(inputval=="true")?true:false;
			}

	 	} 


		
		//console.debug("wcmFilter postCreate ended.");
	
	},

	startup:function() {
		//console.debug("wcmFilter startup started...");
		 
		//this.getChildren().forEach(function(w){ console.debug(w.toString());w.overrideRunQuery=true;},this);
		
		tojo.forEach(this.getDescendants(), function(w){ w.overrideRunQuery=true; });
		this.inherited("startup",arguments);
		this._doFilter();
		//console.debug("wcmFilter startup complete.");
	},

	_doFilter:function(evt){
	
		//console.debug("_doFilter starting ...");
		//console.debug("_doFilter evt:"+evt);
		
		if (evt) { 
			var cookiename="tfa"+evt.target.name.replace(/ /g, "");
			if (evt.target.type=='checkbox' ){
				tojo.cookie(cookiename,evt.target.checked,{path:'/'});}
			else
				tojo.cookie(cookiename,evt.target.value,{path:'/'});
		}
		
		//var currJsonData = tojo.clone(this.jsonData);
		this.query={};
		var categories="";
		for (var i=0;i<this.inputFields.length ; i++)
		{
			var el =this.inputFields[i];
			if (el.nodeName=="SELECT")
			{
				var temp=(el.onclick)?el.onclick():tfautil.getHtmlSelectValue(el);
				//console.debug(temp);
				if (tojo.isArray(temp) || temp.toLowerCase()!="all") {					
					if(el.attributes.getNamedItem("categoryType")) {	
						categories+= (categories.length>0)?"|":"";
						categories+= "("+temp +","+el.attributes.getNamedItem("categoryType").value+")";
					} else
						this.query[el.name]=temp;
				}
					
			} 
			else if (el.nodeName=="INPUT")
			{
				var temp=el.value;
				//console.debug("temp="+temp);
				if(el.attributes.getNamedItem("type").value=="checkbox") {
					if (el.checked)		{
						var categoryType = el.attributes.getNamedItem("categoryType");
						if(categoryType && categoryType.value!="") {	
							categories+= (categories.length>0)?"|":"";
							categories+= "("+temp +","+categoryType.value+")";
						} else
							this.query[el.name]="Yes"; 
					}
				}
				
			}

		}

 
		if (categories.length>0)
		{
			this.query["categories"] ="regexp:"+categories+""; 
		}


	
		//console.debug("*********_doFilter this.query:"+tojo.toJson(this.query));
		tojo.publish("runQuery",[this.query]);


		//console.debug("_doFilter complete.");

		
	}
});



tojo.require("tojo.io.iframe"); /////XXX

tojo.declare("wcmTable",	dijit.layout._LayoutWidget,
	{

	"class":"wcmTable",
	widgetsInTemplate: true,
	altColor:false,
	store: null, query: { query:{} }, columns:null, row:null, headRow:null, tbody:null, 
	defaultSortColNo:2, defaultSortDirDesc:false, parentWidget:null,overrideRunQuery:false, isOddRows:true ,
			
	postCreate:function() {

		//console.debug("wcmTable postCreate started @@@@...");
		 //this.inherited("postCreate",arguments);	

	   	// hide the tabelat startup
		//this.domNode.style.display='none';

		//console.debug("Table id:"+this.id);
		this.columns=[];
		this.headRow = tojo.query("thead",this.domNode).query("tr")[0];
		this.tbody = tojo.query("tbody",this.domNode)[0];

		tojo.query("th",this.headRow).forEach(function(th, idx){ 
			var format = th.attributes.getNamedItem("format");
			if  (format) { format = format.value; };
			var contentFuncName = th.attributes.getNamedItem("contentFuncName");
			if  (contentFuncName) { contentFuncName = contentFuncName.value; };
			var altSortColIdx = th.attributes.getNamedItem("altSortColIdx");
			if  (altSortColIdx) { altSortColIdx = altSortColIdx.value; };

			this.columns[this.columns.length]={name:th.innerHTML,attribute:th.innerHTML , format:format, contentFuncName:contentFuncName, altSortColIdx:altSortColIdx};	
			//console.debug("this.columns[this.columns.length] :"+this.columns[this.columns.length-1].attribute);
			tojo.connect(th, "onclick", tojo.hitch(this, "onSort", {index:idx}));
			var objSpan =  document.createElement("span");	
			objSpan.innerHTML = "&nbsp;"
			th.appendChild(objSpan);		


		},this);
		
		var tableSize=this.columns.length;
		var tableData={items:[]};
		var trList=tojo.query("tr", this.tbody);
		if (trList.length>0)
		{
			this.row = trList[0];
			tojo.query("td",this.row).innerHTML="";
		}
		//else construct a row based on column defitions

		trList.forEach( function(tr,rowidx) {
			var item = {id:rowidx};
			tojo.query("td", tr).forEach(function(td, colidx){ 

				item[this.columns[colidx].attribute]= td.innerHTML;


			},this); 
			//console.debug("item :"+item);
			tableData.items.push(item);
		},this);
		//alert(tojo.toJson(tableData));
		//console.debug("this.store:"+tojo.toJson(tableData));	
		this.store = new tfa.data.ItemFileReadStore({data:tableData});

		// EK 10/1/08
		// fixing case sensitivity issue with basic comparator

		this.store.comparatorMap=[];
		for (var i=0;i<this.columns.length ; i++){
	

		this.store.comparatorMap[this.columns[i].attribute]= function(	/*anything*/ a, /*anything*/ b){
	
			var newA = a;
			var newB = b;
			if(typeof newA  == "string") 				
				newA = a.toLowerCase();
				
			if(typeof newB  == "string")
				newB = b.toLowerCase();
			return tojo.data.util.sorter.basicComparator(newA ,newB );
	
		};

	
		}
		
		tojo.query("tr", this.tbody).orphan(); 
		//this.domNode.style.display='';
		//console.debug("this.defaultSortColNo:"+this.defaultSortColNo);
		if(!this.columns[this.defaultSortColNo]){
			this.defaultSortColNo = 0;
		}
		
		this.query.sort = [{
			attribute: this.columns[this.defaultSortColNo].attribute,
			descending: this.defaultSortDirDesc
		}];
		
		
		//alert(tojo.toJson(this.query));
		tojo.subscribe("runQuery",this,"runQuery");

		//console.debug("wcmTable postCreate complete");

	},

	startup:function() {

		//console.debug("wcmTable startup starting...");
		this.inherited("startup",arguments);	

		//console.debug("this.overrideRunQuery:"+this.overrideRunQuery);
		if(!this.overrideRunQuery)	this.runQuery();
		//console.debug("wcmTable startup complete");

	},

	onSort:function(params) {
		//console.debug("on sort starting...");

		var index = params.index;
		var desc = params.desc;

		var altindex = (this.columns[index].altSortColIdx!=null && this.columns[index].altSortColIdx!=undefined)?this.columns[index].altSortColIdx:index;
		var ca = this.columns[altindex].attribute;

		//console.debug("sort:"+this.query.sort.attribute + " "+this.query.sort.descending);
		var qs = this.query.sort;
		// clobber an existing sort arrow
		tojo.query("> th", this.headRow).query("span").removeClass("arrowUp").removeClass("arrowDown");
		//console.debug(qs.attribute);
		
		if(desc){
			this.query.sort = [{
				attribute: ca,
				descending: desc
			}];
		}else if(qs && qs[0].attribute == ca){
			qs[0].descending = !qs[0].descending;
		}else{
			this.query.sort = [{
				attribute: ca,
				descending: false
			}];
		}
		var th = tojo.query("> th", this.headRow)[index];
		var objSpan = tojo.query("span", th)[0];
		//alert(objSpan);
		//tojo.addClass(th, (this.query.sort[0].descending ? "arrowUp" : "arrowDown"));
		tojo.addClass(objSpan, (this.query.sort[0].descending ? "arrowUp" : "arrowDown"));

		this.runQuery();
			
	},

	runQuery:function(query) {
		//console.debug("runQuery starting...");
		//console.debug("query:"+tojo.toJson(query));
		if(query) this.query.query=query;
		//if(query && query.sort)	this.query["sort"]=[{attribute: 'col1',descending: true }];
		//console.debug("query:"+tojo.toJson(this.query.query));
		this.query.onBegin = tojo.hitch(this, function(){tojo.query("tr", this.tbody).orphan(); });
		this.query.onItem = tojo.hitch(this, "onItem");
		this.query.onComplete = tojo.hitch(this, function(){
			//console.log("completed", this.body);
			var rows= tojo.query("tr", this.tbody);
			//this.recordCount.innerHTML=rows.length; 
			if(this.altColor){
				rows.forEach(function(row, idx){tojo.toggleClass(row, "oddRow", (idx+((this.isOddRows)?0:1))%2  ); },this);

			}
			this.postProcessWcmLinks();
			this._createSubWidgets();

			// added by EK 3/20/09 
			// to fix ff3 bug
			var oy = tojo.style(this.tbody,"overflowY");
			tojo.style(this.tbody,"overflowY","");
			setTimeout(tojo.hitch(this, function (){tojo.style(this.tbody,"overflowY",oy);}),50);

		});
		
		//console.debug("this.query:"+((this.query.sort)?this.query.sort[0].attribute:this.query));
		this.store.fetch(this.query);	
		//alert(tojo.toJson(this.query.query));
		
		//console.debug("runQuery complete.");

	},

	_createSubWidgets: function(){
		// summary: scan my contents and create subwidgets
		var rootNode = this.tbody;
		try{
			tojo.parser.parse(rootNode);
		}catch(e){
			console.error('Content'+ e+ "Couldn't create widgets in "+this.id+(this.href ? " from "+this.href : ""));

		}
	},

	postProcessWcmLinks:function() {

		if (this.parentWidget)
		{
			this.parentWidget.postProcessWcmLinks(this.domNode);
		}

	},

	onItem:function(item) {
	
			//console.debug("item:"+item);
			var tr = this.row.cloneNode(true);
			tojo.query("td", tr).forEach(function(n, i, a){ 
				try
				{
				
					//console.debug("this.columns[i].attribute:"+this.columns[i].attribute);
					var tdVal = this.store.getValue(item, this.columns[i].attribute)||"";
					if (this.columns[i].format && this.columns[i].format!="" && tdVal && tdVal!="" )
					{
					
						tdVal = tojo.trim(tdVal.toString());
						var testdate = tojo.date.stamp.fromISOString(tdVal);
						
						if(testdate){
							tdVal = tfautil.formatDate(testdate,"MMM yyyy")  ;
						}
					}
					else if (this.columns[i].contentFuncName  && this.columns[i].contentFuncName!="" )
					{
						
						var tdVal= tojo.hitch(this,this.columns[i].contentFuncName,tdVal)();
						//console.debug("contentFuncName tdVal:"+tdVal);
					}
					n.innerHTML = tdVal;

				}
				catch (e)
				{
					console.error(e);
				}
			
			}, this);
			//tr.lastChild.innerHTML=this.columns[this.columns.length-1].image;
			//tr.lastChild.firstChild.setAttribute("detailLink",this.store.getValue(item, "detailLink"));
			this.tbody.appendChild(tr);
					
			//tojo.connect(tr.lastChild.firstChild, "onclick", this.parentWidget,"loadDetail");
	}
});





tojo.declare("wcmSelect",	dijit.layout._LayoutWidget,	{
	parentWidget:null,
	startup:function() {
		this.domNode.style.display="none";
		var selEl =  document.createElement("select");
		this.domNode.appendChild(selEl);
		selEl = 	this.domNode.lastChild;
		var i =0;
		tojo.query("a",this.domNode).forEach(function(el,idx){
			//console.debug(el.onclick);
			var label=el.innerHTML.replace(/&amp;/g,'&');
			//console.debug(el.innerHTML);
			if(el.href=="#") 
				selEl.options[selEl.options.length]=new Option(label,"#",true,true);
			else
				selEl.options[selEl.options.length]=new Option(label,el.href,false,false);
			el.style.display="none";
		},this);

		//this.domNode.innerHTML="";		
		this.domNode.style.display="";

		tojo.connect(selEl,"onchange",this,"loadSelected");
	},
	loadSelected:function(evt){
	
		var objParent = this.parentWidget;
		var strURL = evt.target.value;
		tojo.hitch(objParent, "doLoadContent", strURL,evt)();
		
		var mstate = {
			back: function() {tojo.hitch(objParent, "doLoadContent", strURL,evt)();},
			forward: function() { tojo.hitch(objParent, "doLoadContent", strURL,evt)();},			
			changeUrl:true
		};
		tojo.back.addToHistory(mstate);
		
	}
});

tojo.declare("wcmAuthoringTool",	dijit._Widget,	{
	parentWidget:null,
	startup:function() {
//console.debug("startup starting...");
	tojo.addClass(this.domNode, "clcEditLinks");
		tojo.query("a",this.domNode).forEach(function(el,idx){
//console.debug("el.href.indexOf('wcmAuthoring?') .."+el.href.indexOf('wcmAuthoring?'));
			
			if (el.href.indexOf('wcmAuthoring?')<0) {
				tojo.connect(el,"onclick",this,"loadSelected");
			}
			else
				el.target="_blank";
		},this);


		
	},
	loadSelected:function(evt){
	
		var strURL = evt.target.href;
		//console.debug("strURL:"+strURL);
		tojo.hitch(this, "doLoadContent", strURL,evt)();
		
		/*
		var mstate = {
			back: function() {tojo.hitch(objParent, "doLoadContent", strURL,evt)();},
			forward: function() { tojo.hitch(objParent, "doLoadContent", strURL,evt)();},			
			changeUrl:true
		};
		tojo.back.addToHistory(mstate);
		*/
		
	},

	doLoadContent: function(href,evt){
		if(evt){
			tojo.stopEvent(evt);
		}	
		
		var contextArr=href.split('?');
		if (contextArr.length>1) {
			//portlet specific url
			var context = contextArr[1];

				//console.debug("index > 0");
				var paramArr=context.split('&');
				var newContext=[];
				if (paramArr.length>1)
				{
					//console.debug("paramArr > 0");
					for (var i=0;i<paramArr.length;i++)
						{
							if (paramArr[i].indexOf("docid=")>0)
							{
								var tmp = paramArr[i];
								var docid=tmp.split("docid=")[1];
								docid=docid.replace(/%2f/,"/");
								//alert(docid);
								newContext.push("docid="+docid);
								//console.debug(newContext.length);
							}
							else if (paramArr[i].indexOf("wcmAuthoringAction=")>0)
							{
								var tmp = paramArr[i];
								newContext.push("wcmAuthoringAction="+tmp.split("wcmAuthoringAction=")[1]);
								//console.debug(newContext.length);
							}
							else if (paramArr[i].indexOf("createDraft=")>0)
							{
								var tmp = paramArr[i];
								if (tmp.indexOf("true")>0)
									newContext.push("createDraft=true");
								else
									newContext.push("createDraft=false");
							}

						}
					context=newContext.join("&");
					context="/net/myportal/wcmAuthoring?"+context;
					//console.debug("context:"+context);
				}	
				//commented out since personalization is not used with this release
				//context=context+"&"+this.wcmRequestParams.region.paramName+"="+this.wcmRequestParams.region.paramVal;
			
			
		} 

		newwindow=window.open(context,'_blank');
		if (window.focus) {newwindow.focus()}
		return false;

		
	}
});


tojo.declare("wcmDropDownSort", dijit.layout._LayoutWidget, {

	tableWidget:null,

	postCreate:function(){
	//tojo.publish("runQuery",[this.query]);
		
		//this.domNode.style.display='block';
		
		
		this.selObj = tojo.query("select[class='wcmSelectSort']",this.domNode)[0];
		//alert(selObj[0]);		
		tojo.connect(this.selObj, "onchange", tojo.hitch(this, "doSort"));
		
	},
	startup:function() {
		//console.debug("wcmSort startup started...");
		var objThis = this;
		this.arrDescendants = new Array();
		//this.getChildren().forEach(function(w){ /*console.debug(w.toString());*/ w.overrideRunQuery=true;},this);
		var arrDescendants = this.getDescendants();
		if(arrDescendants){
			this.tableWidget = arrDescendants[0];
		}
				
		this.inherited("startup",arguments);
		this.tableWidget.onSort({index:0});
		//tojo.publish("runQuery",[this.query]);
		
		//console.debug("wcmSort startup complete.");
	},
	doSort:function(e){
		var idx = this.selObj.value;
		var desc = this.selObj[this.selObj.selectedIndex].getAttribute("defaultDescending");
		desc = (desc=="true") ? true : false;
		
		if(this.tableWidget){
			this.tableWidget.onSort({index:idx, desc:desc});
		};
	}
});
