//** Tab Content script

function ddtabcontent(tabinterfaceid){
	this.tabinterfaceid=tabinterfaceid //ID of Tab Menu main container
	this.tabs=document.getElementById(tabinterfaceid).getElementsByTagName("a") //Get all tab links within container
	this.enabletabpersistence=true
	this.hottabspositions=[] //Array to store position of tabs that have a "rel" attr defined, relative to all tab links, within container
	this.currentTabIndex=0 //Index of currently selected hot tab (tab with sub content) within hottabspositions[] array
	this.subcontentids=[] //Array to store ids of the sub contents ("rel" attr values)
	this.revcontentids=[] //Array to store ids of arbitrary contents to expand/contact as well ("rev" attr values)
	this.selectedClassTarget="link" //keyword to indicate which target element to assign "selected" CSS class ("linkparent" or "link")
}

ddtabcontent.getCookie=function(Name){ 
	var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
	if (document.cookie.match(re)) //if cookie found
		return document.cookie.match(re)[0].split("=")[1] //return its value
	return ""
}

ddtabcontent.setCookie=function(name, value){
	document.cookie = name+"="+value+";path=/" //cookie value is domain wide (path=/)
}

ddtabcontent.prototype={

	expandit:function(tabid_or_position){ //PUBLIC function to select a tab either by its ID or position(int) within its peers
		this.cancelautorun() //stop auto cycling of tabs (if running)
		var tabref=""
		try{
			if (typeof tabid_or_position=="string" && document.getElementById(tabid_or_position).getAttribute("rel")) //if specified tab contains "rel" attr
				tabref=document.getElementById(tabid_or_position)
			else if (parseInt(tabid_or_position)!=NaN && this.tabs[tabid_or_position].getAttribute("rel")) //if specified tab contains "rel" attr
				tabref=this.tabs[tabid_or_position]
		}
		catch(err){alert("Invalid Tab ID or position entered!")}
		if (tabref!="") //if a valid tab is found based on function parameter
			this.expandtab(tabref) //expand this tab
	},

	cycleit:function(dir, autorun){ //PUBLIC function to move foward or backwards through each hot tab (tabinstance.cycleit('foward/back') )
		if (dir=="next"){
			var currentTabIndex=(this.currentTabIndex<this.hottabspositions.length-1)? this.currentTabIndex+1 : 0
		}
		else if (dir=="prev"){
			var currentTabIndex=(this.currentTabIndex>0)? this.currentTabIndex-1 : this.hottabspositions.length-1
		}
		if (typeof autorun=="undefined") //if cycleit() is being called by user, versus autorun() function
			this.cancelautorun() //stop auto cycling of tabs (if running)
		this.expandtab(this.tabs[this.hottabspositions[currentTabIndex]])
	},

	setpersist:function(bool){ //PUBLIC function to toggle persistence feature
			this.enabletabpersistence=bool
	},

	setselectedClassTarget:function(objstr){ //PUBLIC function to set which target element to assign "selected" CSS class ("linkparent" or "link")
		this.selectedClassTarget=objstr || "link"
	},

	getselectedClassTarget:function(tabref){ //Returns target element to assign "selected" CSS class to
		return (this.selectedClassTarget==("linkparent".toLowerCase()))? tabref.parentNode : tabref
	},

	urlparamselect:function(tabinterfaceid){
		var result=window.location.search.match(new RegExp(tabinterfaceid+"=(\\d+)", "i")) //check for "?tabinterfaceid=2" in URL
		return (result==null)? null : parseInt(RegExp.$1) //returns null or index, where index (int) is the selected tab's index
	},

	expandtab:function(tabref){
		var subcontentid=tabref.getAttribute("rel") //Get id of subcontent to expand
		//Get "rev" attr as a string of IDs in the format ",john,george,trey,etc," to easily search through
		var associatedrevids=(tabref.getAttribute("rev"))? ","+tabref.getAttribute("rev").replace(/\s+/, "")+"," : ""
		this.expandsubcontent(subcontentid)
		this.expandrevcontent(associatedrevids)
		for (var i=0; i<this.tabs.length; i++){ //Loop through all tabs, and assign only the selected tab the CSS class "selected"
			this.getselectedClassTarget(this.tabs[i]).className=(this.tabs[i].getAttribute("rel")==subcontentid)? "selected" : ""
		}
		if (this.enabletabpersistence) //if persistence enabled, save selected tab position(int) relative to its peers
			ddtabcontent.setCookie(this.tabinterfaceid, tabref.tabposition)
		this.setcurrenttabindex(tabref.tabposition) //remember position of selected tab within hottabspositions[] array
	},

	expandsubcontent:function(subcontentid){
		for (var i=0; i<this.subcontentids.length; i++){
			var subcontent=document.getElementById(this.subcontentids[i]) //cache current subcontent obj (in for loop)
			subcontent.style.display=(subcontent.id==subcontentid)? "block" : "none" //"show" or hide sub content based on matching id attr value
		}
	},

	expandrevcontent:function(associatedrevids){
		var allrevids=this.revcontentids
		for (var i=0; i<allrevids.length; i++){ //Loop through rev attributes for all tabs in this tab interface
			//if any values stored within associatedrevids matches one within allrevids, expand that DIV, otherwise, contract it
			document.getElementById(allrevids[i]).style.display=(associatedrevids.indexOf(","+allrevids[i]+",")!=-1)? "block" : "none"
		}
	},

	setcurrenttabindex:function(tabposition){ //store current position of tab (within hottabspositions[] array)
		for (var i=0; i<this.hottabspositions.length; i++){
			if (tabposition==this.hottabspositions[i]){
				this.currentTabIndex=i
				break
			}
		}
	},

	autorun:function(){ //function to auto cycle through and select tabs based on a set interval
		this.cycleit('next', true)
	},

	cancelautorun:function(){
		if (typeof this.autoruntimer!="undefined")
			clearInterval(this.autoruntimer)
	},

	init:function(automodeperiod){
		var persistedtab=ddtabcontent.getCookie(this.tabinterfaceid) //get position of persisted tab (applicable if persistence is enabled)
		var selectedtab=-1 //Currently selected tab index (-1 meaning none)
		var selectedtabfromurl=this.urlparamselect(this.tabinterfaceid) //returns null or index from: tabcontent.htm?tabinterfaceid=index
		this.automodeperiod=automodeperiod || 0
		for (var i=0; i<this.tabs.length; i++){
			this.tabs[i].tabposition=i //remember position of tab relative to its peers
			if (this.tabs[i].getAttribute("rel")){
				var tabinstance=this
				this.hottabspositions[this.hottabspositions.length]=i //store position of "hot" tab ("rel" attr defined) relative to its peers
				this.subcontentids[this.subcontentids.length]=this.tabs[i].getAttribute("rel") //store id of sub content ("rel" attr value)
				this.tabs[i].onclick=function(){
					tabinstance.expandtab(this)
					tabinstance.cancelautorun() //stop auto cycling of tabs (if running)
					return false
				}
				if (this.tabs[i].getAttribute("rev")){ //if "rev" attr defined, store each value within "rev" as an array element
					this.revcontentids=this.revcontentids.concat(this.tabs[i].getAttribute("rev").split(/\s*,\s*/))
				}
				if (selectedtabfromurl==i || this.enabletabpersistence && selectedtab==-1 && parseInt(persistedtab)==i || !this.enabletabpersistence && selectedtab==-1 && this.getselectedClassTarget(this.tabs[i]).className=="selected"){
					selectedtab=i //Selected tab index, if found
				}
			}
		} //END for loop
		if (selectedtab!=-1) //if a valid default selected tab index is found
			this.expandtab(this.tabs[selectedtab]) //expand selected tab (either from URL parameter, persistent feature, or class="selected" class)
		else //if no valid default selected index found
			this.expandtab(this.tabs[this.hottabspositions[0]]) //Just select first tab that contains a "rel" attr
		if (parseInt(this.automodeperiod)>500 && this.hottabspositions.length>1){
			this.autoruntimer=setInterval(function(){tabinstance.autorun()}, this.automodeperiod)
		}
	} //END int() function

} //END Tabs Rotator

	function UpdatePage( ContentType, ContentID, ExtraParam)
	{
		var k = CMS.Organizor.RmtScriptAPIs.BuildPublicURL( ContentType , ContentID , ExtraParam);
		top.location.href =  k.value;
		//alert(top.location.href);
	}
	function HidShowSummary(ID , bShow)
	{
		
		if (document.getElementById(ID))
		{
			if (bShow)
			{
				document.getElementById(ID).style.display ='block';
			}
			else
				document.getElementById(ID).style.display ='none';
		}	
	}
	
	function TrimString(sInString) 
	{
			sInString = sInString.replace( /^\s+/g, "" );// strip leading
			return sInString.replace( /\s+$/g, "" );// strip trailing
			//return sInString;
	}

	function MySetTimeOut( id , bShow)
	{	
		if(bShow)
			document.getElementById("hhbLastSummary").value = setTimeout("HidShowSummary('" + id + "', true)" , 2000);
		else
		{
			//debugger;
			clearTimeout(document.getElementById("hhbLastSummary").value);
			//setTimeout("HidShowSummary('" + id + "', false)" , 1000);
			HidShowSummary( id , false);
			
		}	
	}
	
	function HideShowItem(ID ,Image, Src1,Src2) 
	{
		
		
		if (document.getElementById(ID))
		{
			if(document.getElementById(ID).style.display == 'block')
			{
				document.getElementById(ID).style.display ='none';
			}
			else
			{
				document.getElementById(ID).style.display ='block';
			}
			// Temporary: To solve vote archive list clipping !!!! 
			if (document.getElementById('VoteResultBtn'))
			{
				document.getElementById('VoteResultBtn').className=document.getElementById('VoteResultBtn').className; 
			}
			if(Image)
			{
				
				if (Src1)
				{
					if (document.getElementById(ID).style.display == "block")
						Image.src=  'DataFiles/Templates/' + Src1;
					else 
						Image.src = 'DataFiles/Templates/' + Src2;
				}
				else
					Image.src = GetMenuImg(document.getElementById(ID).style.display);
					
			}
		}
	}
	
	//============ EmadA 07.09.2005 
	function FormatDateGridBinding(strDate, bIgnoreTime)
	{
		if ((strDate == null) || (strDate == ''))
		{
			return '';
		}
		var DateString = strDate.replace("T"," ");
		
		if (!bIgnoreTime)
			DateString = DateString.substring(0,19);
		else
			DateString = DateString.substring(0,10);
		
		return	DateString;	
		
	}

	function Search(SearchType)
	{
		//alert(document.getElementById('SearchWords').value);
		if ((SearchType =='ADV') ||  document.getElementById('SearchWords').value != "" )
			UpdatePage('SRH', document.getElementById('SearchWords').value, SearchType);
	}

	function openVoteResult(param)
	{
		var index = -1;
		if (param)
		{
			index = GetSelectedVoteOption();
			if (index < 0)
				return;
		}
		Url = CMS.Organizor.RmtScriptAPIs.GetVoteResultURL(document.getElementById("hhbActiveCat").value, (index > 0) ? String(index) : '');
		window.showModalDialog(Url.value,null,'dialogHeight: 400px; dialogWidth: 590px; edge: Raised; center: yes; help: no; resizable: no; status: no;');
	} 
	
	function AddBlogs()
	{
		Url = CMS.Organizor.RmtScriptAPIs.AddBlogs(); 
		top.location.href =  Url.value;
	}
	
	function MyArticles()
	{
		Url = CMS.Organizor.RmtScriptAPIs.MyArticles(); 
		top.location.href =  Url.value;
	}
	function SubsArticles(subID)
	{
		Url = CMS.Organizor.RmtScriptAPIs.SubsArticles(subID); 
		top.location.href =  Url.value;
	}
	function RgisterNewUser()
	{
		Url = CMS.Organizor.RmtScriptAPIs.GetRgisterNewUser(); 
		top.location.href =  Url.value;
	}
	
	function LoginUser(name, pass)
	{
		var sep = '*';
		document.getElementById("hhbAction").value = 3; // Login.
		document.getElementById("hhbActionParams").value = name + sep + pass;
		document.forms[0].submit();
	}
	
	function LogoutUser()
	{
		document.getElementById("hhbAction").value = 4; // logout.
		//document.getElementById("hhbActionParams").value = name + sep + pass;
		document.forms[0].submit();
	}
	function OpenVoteHis()
	{
		Url = CMS.Organizor.RmtScriptAPIs.GetVoteHis(); 
		top.location.href =  Url.value;
	}
	
	function GetSelectedVoteOption()
	{
		//var divOption = document.getElementById(document.getElementById('__VotingUCPre').value + "VoteOptionsListTD");
		var divOption = document.getElementById("VoteOptionsListTD");
		var options = divOption.getElementsByTagName("input");
		var index = -1;
		for (i = 0 ; i < options.length; i++)
		{
			if(options[i].checked)
			{ 
				index = i  + 1;
				break
			}
		}
		return index;
	}
	
	function VoteButtonStatus()
	{
		index = GetSelectedVoteOption();
		btn = 	document.getElementById( "VoteBtn");
		//Check Cookies 
		var cookieName ="__VOTE_" +  document.getElementById(document.getElementById('__VotingUCPre').value + "_hhbtnVoteID").value;
		if (!GetCookie(cookieName))
			btn.disabled = (index < 0);
		else
			btn.disabled = true;
	}


	// Retrieve the value of the cookie with the specified name.
	function GetCookie(sName)
	{
		// cookies are separated by semicolons
		var aCookie = document.cookie.split("; ");
		for (var i=0; i < aCookie.length; i++)
		{
			// a name/value pair (a crumb) is separated by an equal sign
			var aCrumb = aCookie[i].split("=");
			if (sName == aCrumb[0]) 
			return unescape(aCrumb[1]);
		}

		// a cookie with the requested name does not exist
		return null;
	}
	// Create a cookie with the specified name and value.
	
	function SetCookie(sName, sValue)
	{
		date = new Date();
		date.setMilliseconds(date.getMilliseconds() + (1000 * 60 * 60 * 24 * 30));
		document.cookie = sName + "=" + escape(sValue) + "; expires=" + date.toGMTString();
		
	}
	
	function FillYearDDL( Id, Start, End, Selected , target)
	{
		oSelect  = document.getElementById(Id);
		if (oSelect)
		{
			for (; Start <= End; End--)
			{
				var oOption = document.createElement("OPTION");
				oOption.text=End;
				oOption.value=End;
				if (End == Selected)
					oOption.selected = true;
				oSelect.add(oOption);
			}
		}
		
		strFunc = "ArchivedIssueDDLChanged('" + Id +  "','" +  target + "');"
		oSelect.onchange = new Function(strFunc);
	}
	
	function ArchivedIssueDDLChanged(Id, target)
	{
		//alert('To be Checked');
		ctrl = document.getElementById(Id);
		var k = CMS.Organizor.RmtScriptAPIs.BuildPublicURL( target , ctrl.value , '');
		top.location.href =  k.value;

		
	}
	
	function ChangeCurrIssue(id, no, year)
	{
		var sep = '*';
		document.getElementById("hhbAction").value = 1; // Set Current Issue to Last published one.
		document.getElementById("hhbActionParams").value = id + sep + no + sep + year;
		document.forms[0].submit();
	}
	
	function NavSearch( NewPage)
	{
		
		document.getElementById("hhbAction").value = 2; //Go To Next or Previous Search Page.
		document.getElementById("hhbActionParams").value = NewPage ;
		document.forms[0].submit();
	}

	function SetCurrentPubIssue()
	{
		if (st_IssuesInfo && st_IssuesInfo[0] != st_IssuesInfo[3])
		{
			ChangeCurrIssue(st_IssuesInfo[0], st_IssuesInfo[1], st_IssuesInfo[2]);
		}
	}
	
	function InitCtrls(IssueExist)
	{
	
		// TODO: Try to use getElementsByName instead of getElementById
		// Last Issue
		var ctrl;
		var Coll;
		//alert(st_IssuesInfo);
		if (IssueExist)
		{
			ctrl = document.getElementById("liLastIssueLbl");
			if (ctrl)
			{
				if (st_IssuesInfo[0] != st_IssuesInfo[3])
					ctrl.style.display ='block';
				else
					ctrl.style.display ='none';
			}
			// Current Issue lable
			
			Coll = document.getElementsByTagName("CurrentIssueLbl");	
			for (var i=0; i< Coll.length; i++ )
				Coll[i].outerHTML =   Coll[i].outerHTML + st_IssuesInfo[4] ;
				
			Coll = document.getElementsByTagName("CurrentIssueDateLbl");	
			for (var i=0; i< Coll.length; i++ )
				Coll[i].outerHTML =   Coll[i].outerHTML + st_IssuesInfo[5] ;
			// Archived Issues
			
			// Printed Pages
		}
		
		ctrl = document.getElementById("__hhdnCurrentDate");
		if (ctrl)
		{
			Coll = document.getElementsByTagName("CurrentDateString");	
			for (var i=0; i< Coll.length; i++ )
				Coll[i].outerHTML =   ctrl.value ;
			
			// Archived Issues
		} 
		
		// Site Map
		
		
		// Main Page
		
		
		// CopyWrites
		ctrl = document.getElementById("__hhdnCopyWriteMsg");
		if (ctrl)
		{
			Coll = document.getElementsByTagName("CopywriteMessage");	
			for (var i=0; i< Coll.length; i++ )
				Coll[i].outerHTML =   ctrl.value ;
			
			// Archived Issues
		} 
		
		// Free Areas 
		var Coll2; 
		
		
		if (st_FreeAreasHCtrls)
		{
			for (var j=0; j< st_FreeAreasHCtrls.length; j++ )
			{
				var str =  st_FreeAreasHCtrls[j]  ;

				Coll2 = document.getElementsByTagName( str );// st_FreeAreasHCtrls[j][0]);	
				
				for (var i=0; i< Coll2.length; i++ )
					Coll2[i].outerHTML = document.getElementById(str + "__Hdn").value;
					
				// document.getElementById(str + "__Hdn").value	= "";
			}
		}
			
	//	theObjects = document.getElementsByTagName("object"); 
	//	for (var i = 0; i < theObjects.length; i++) { 
	//		theObjects[i].outerHTML = theObjects[i].outerHTML; 
	//	}


	}
	
	function SetBorders()
	{
		RUZEE.Borders.add({
		'.RB_Shadow': { borderType:'shadow',  cornerRadius:7, shadowWidth:4 },
		'.RB_Fade': { borderType:'fade', cornerRadius:8 },
		'.RB_Corner': { borderType:'simple', cornerRadius:8, height:2 }
			});
		RUZEE.Borders.render();
		//rzCrShadowBorder(8,3).draw('.RB_Shadow');
		//rzCrSimpleBorder(8).draw('.RB_Corner');
		//rzCrGlowBorder(8,5).draw('.RB_Glow','white');
		//rzCrShadowBorder(10,5).draw('.RB_Shadow');
	}
	function IsCookiesEnabled()
	{
		if (!navigator.cookieEnabled)
		{
			var ctrl = document.getElementById("VoteingBtn");
			if (ctrl)
				ctrl.disabled = true;
				
			document.getElementById("lblCookeNotAllowed").style.display = "block";	
				
		}
	}
	function SubsFrgtnPsw()
	{
		Url = CMS.Organizor.RmtScriptAPIs.SubsFrgtnPsw();
		window.showModalDialog(Url.value,null,'dialogHeight: 200px; dialogWidth: 450px; edge: Raised; center: yes; help: no; resizable: no; status: no;');
	}
	function AddToFav()
	{
		var AppName = document.getElementById("__SiteName").value;
		var AppPath = document.getElementById("__SitePath").value;
		
		if (document.all) 
			window.external.AddFavorite(AppPath, AppName);
	}
	function SetHomePage()
	{
		var AppPath = document.getElementById("__SitePath").value;
	
		document.body.style.behavior= 'url(#default#homepage)';
		document.body.setHomePage(AppPath);
	}
		
