//** Ajax Tabs Content script v2.0- © Dynamic Drive DHTML code library (http://www.dynamicdrive.com)
//** Updated Oct 21st, 07 to version 2.0. Contains numerous improvements

var TabObj = Class.create();
TabObj.prototype = 
{

}

var TabMenuObj = Class.create();
TabMenuObj.prototype = 
{
	tabinterfaceid: null,
	contentdivid: null,
	container: null,
	content: null,
	tabs: [],
	selectedTab:'',
	selectedTabIndex: 0, // selected by default
	selectedTabId:'',
	bustcachevar:1,	
	loadstatustext:"<img src='ajaxtabs/loading.gif' /> Requesting content...",
	selectedClassTarget:"link", //keyword to indicate which target element to assign "selected" CSS class ("linkparent" or "link")		
	enabletabpersistence:false,
	hottabspositions:[], //Array to store position of tabs that have a "rel" attr defined, relative to all tab links, within container
	defaultHTML:'',
	defaultIframe: '',
	frameId:'',
	frame:false,
	updatehash:false,
	
	revcontentids:[], //Array to store ids of arbitrary contents to expand/contact as well ("rev" attr values),
	
	initialize:function(tabinterfaceid,contentdivid,selectedTabIndex,selectedTabId)
	{
		////alert('initialize func in tab');
		this.tabinterfaceid=tabinterfaceid //ID of Tab Menu main container
		this.contentdivid=contentdivid
		this.container = document.getElementById(tabinterfaceid);
		this.content = document.getElementById(contentdivid);
		if(selectedTabIndex != '') this.selectedTabIndex = selectedTabIndex;
		if(selectedTabId != '') this.selectedTabId = selectedTabId;
		//this.selectedTabIndex = container.getAttribute('selectedTabIndex'); this.selectedTabId = container.getAttribute('selectedTabId'); 
		this.frameid = '_ddajaxtabsiframe-'+this.contentdivid;
		var eles = this.container.getElementsByTagName("span") //Get all tab links within container
		var tabs = [];
		for(var i=0; i < eles.length; i++)
		{
			var ele = eles[i];
			var classname = ele.getAttribute(document.all ? 'className' : 'class');
			
			// be sure to name the class tab until write code to get attribute
			if(classname=='tab') 
			{
				ele.selected = Boolean(ele.getAttribute('selected'));

				/*------------------------------------------------------------------------------
					if title is assigned as attribute instead of innerHTML and there is no innerHTML 
					as title, use title in innerHTML
					if(ele.title=='' && ele.innerHTML!='') ele.title = ele.innerHTML;
					else ele.title = ele.getAttribute('title');
				------------------------------------------------------------------------------*/

				ele.title = ele.innerHTML;
				ele.text = ele.getAttribute('text');
				ele.location = ele.getAttribute('location');
				ele.target = ele.getAttribute('target');
				ele.srcid = ele.getAttribute('srcid');
				ele.tabindex = i;

				// select tab if the tab has "selected" as attribute or the tab menu has attribute set for index or id that matches this tab
				if(Boolean(ele.getAttribute('selected')) || (this.selectedTabId != '' && ele.id == this.selectedTabId) || (this.selectedTabIndex != '' && i == this.selectedTabIndex)) 
				{
					ele.selected = true;
					this.selectedTabId = ele.id;
					this.selectedTabIndex = i;
					this.selectedTab = ele;
					//alert([ele.title, this.selectedTabIndex, this.selectedTabId]);
				}
				else
				{
					ele.selected = false;
				}
				
				tabs.push(ele);
			}
		}
		this.tabs = tabs;
		//alert([this.tabinterfaceid,tabs.length]);
	},

	connect:function(pageurl, tabinstance){
		var page_request = false
		var bustcacheparameter=""
		
		/*
		if (window.XMLHttpRequest) // if Mozilla, IE7, Safari etc
			page_request = new XMLHttpRequest()
		else if (window.ActiveXObject){ // if IE6 or below
			try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP")
			} 
			catch (e){
				try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP")
				}
				catch (e){}
			}
		}
		else
			return false

		var ar = ajaxfriendlyurl.split('?');

		*/
		
		var ajaxfriendlyurl=pageurl.replace(/^http:\/\/[^\/]+\//i, "http://"+window.location.hostname+"/") 
		var ar = ajaxfriendlyurl.split('?');
		url = ar[0];
		query = {};
		if(ar[1])
		{
			var tmp = ar[1].split('&');
			for(var i=0; i < tmp.length; tmp++)
			{
				var tmp2 = tmp[i].split('=',2);
				var field = tmp2[0];
				var value = tmp2[1];
				query[field] = value;
				//alert(value);
			}
		}

		/**********************************************************************************
		http://www.codeguru.com/csharp/csharp/cs_network/internetweb/article.php/c14285__2/
		ReadyState: This is an integer value stating whether the request is ready and if you can access the ResponseText object. The possible states are as follows: 
		0 = uninitialized 
		1 = loading 
		2 = loaded 
		3 = interactive 
		4 = complete 
		ResponseText: This is the response text, web page or XML content that is returned by the request. 
		Status: This is the status of the HTTP Request: 200 or 404. 
		URL: This is the URL that was requested. 
		UserObject: This is a free user object that was allowed to be passed around. Use it to store whatever you want. 
		Complete: This is a boolean telling you if all the page requests have been completed that were in the PageRequests Array Collection. 
		**********************************************************************************/
		this.pageurl = pageurl;
		this.tabinstance = tabinstance;
		////url = 'http://'+document.location.host+url; alert(url);
		var a = new System.Net.Ajax.Request ('POST', url, this.ajax_response, true, this);
		for(var field in query)
		{
			//alert(field +' '+query[field]);
			a.AddParam(field,query[field]);
		}
		var b = new System.Net.Ajax.PageRequests(a);
		var c = new System.Net.Ajax.Connection(b);
		c.Open();

	},

	// JS & AJAX etc:  ** http://www.tutorom.com/courses/418/Ajax.htm
	// Attributes:  http://www.howtocreate.co.uk/tutorials/javascript/dombasics
	ajax_response: function (src)
	{	
		//FOR TESTING: response = '<?xml version="1.0" encoding="UTF-8"?><results id="pop1"><pop id="1" type="store" code="1">This is a test</pop></results>';
    if(src.ReadyState==4)
    {
			if(src.Status==200)
			{
	 			src.UserObject.content.innerHTML=src.ResponseText
				src.UserObject.ajaxpageloadaction(src.UserObject.pageurl, src.UserObject.tabinstance)
			}
		}
	},			
	
	loadpage:function(page_request, pageurl, tabinstance){
		this.content.innerHTML=this.loadstatustext //Display "fetching page message"
		if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
			this.content.innerHTML=page_request.responseText
			this.ajaxpageloadaction(pageurl, tabinstance)
		}
	},

	ajaxpageloadaction:function(pageurl, tabinstance){
		tabinstance.onajaxpageload(pageurl) //call user customized onajaxpageload() function when an ajax page is fetched/ loaded
	},

	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 ""
	},

	setCookie:function(name, value){
		document.cookie = name+"="+value+";path=/" //cookie value is domain wide (path=/)
	},

	// NOT SURE WHAT THIS IS ...
	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 tab=""
		try{
			if (typeof tabid_or_position=="string") //if specified tab contains "rel" attr
				tab = this.tabs[tabid_or_position];
				//tabref=document.getElementById(tabid_or_position)
			else if (parseInt(tabid_or_position)!=NaN) //if specified tab contains "rel" attr
				tab = this.tabs[tabid_or_position];
		}
		catch(err){alert("Invalid Tab ID or position entered!")}
		if (tab) //if a valid tab is found based on function parameter
			this.expandtab(tab) //expand this tab
	},	

	setpersist:function(bool){ //PUBLIC function to toggle persistence feature
			this.enabletabpersistence=bool
	},

	loadajaxpage:function(pageurl){ //PUBLIC function to fetch a page via Ajax and display it within the Tab Content instance's container
		this.connect(pageurl, this)
	},

	loadiframepage:function(pageurl){ //PUBLIC function to fetch a page and load it into the IFRAME of the Tab Content instance's container
		this.iframedisplay(pageurl)
	},

	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
	},

	onajaxpageload:function(pageurl){ //PUBLIC Event handler that can invoke custom code whenever an Ajax page has been fetched and displayed
		//do nothing by default
	},

	expandtab:function(tabref)
	{
		if(!tabref) return;
		
		// FRAME content via src
		if (tabref.frame==true)
			this.iframedisplay(tabref.url)

		// URL content via ajax
		else if(tabref.url)
			this.connect(tabref.url, this)
		
		// TEXT content via string
		else if(tabref.text)
			this.update(tabref, tabref.text)
		
		// SRC content via another layer
		else if(tabref.srcid)
			this.update(tabref, null, tabref.srcid)
		
		// LOCATION content via another window location
		else if(tabref.location)
		{
			if(tabref.target) window.open(tabref.location,tabref.target);
			else window.location.href = tabref.location;
		}
		
		// Not sure what this is for ...
		var associatedrevids=(tabref.getAttribute("rev"))? ","+tabref.getAttribute("rev").replace(/\s+/, "")+"," : ""
		this.expandrevcontent(associatedrevids)
		
		// open selected tab
		var tabs = this.tabs;
		for (var i=0; i< 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("href")==tabref.getAttribute("href"))? "selected" : ""
			var tab = tabs[i];
			tabref.selected = (i == tabref.tabposition) ? true : false;
			this.getselectedClassTarget(tab).className=(tabref.selected) ? "selected" : "";
			if(this.updatehash && tabref.selected) document.location.hash = "tab="+(i+1)
		}
		
		// store selected tab
		if (this.enabletabpersistence) //if persistence enabled, save selected tab position(int) relative to its peers
			this.setCookie(this.tabinterfaceid, tabref.tabposition)
	},

	iframedisplay:function(pageurl){
		if (typeof window.frames["_ddajaxtabsiframe-"+this.contentdivid]!="undefined"){
			try{delete window.frames["_ddajaxtabsiframe-"+this.contentdivid]} //delete iframe within Tab content container if it exists (due to bug in Firefox)
			catch(err){}
		}
		var frameid = this.frameid;
		var str = '';
		str += '<iframe name="'+frameid+'" src="about:blank" marginwidth="0" marginheight="0" frameborder="0" vspace="0" hspace="0" class="tabcontentiframe" style="width:100%; height:60; "></iframe>';
		this.content.innerHTML = str;
		try {
			window.frames[frameid].location.replace(pageurl) //load desired page into iframe
	
		} catch (e) {
			alert('error framing');
		}
	},
	
	update:function(tab,text,id)
	{
		if(text) this.content.innerHTML = text;
		else if(id) this.content.innerHTML = document.getElementById(id).innerHTML;
	},
	
	// WHAT IS THIS FOR?
	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"
		}
	},

	autorun:function(){ //function to auto cycle through and select tabs based on a set interval
		var currentTabIndex=this.automode_currentTabIndex //index within this.hottabspositions to begin
		var hottabspositions=this.hottabspositions //Array containing position numbers of "hot" tabs (those with a "rel" attr)
		this.expandtab(this.tabs[hottabspositions[currentTabIndex]])
		this.automode_currentTabIndex=(currentTabIndex<hottabspositions.length-1)? currentTabIndex+1 : 0 //increment currentTabIndex
	},

	cancelautorun:function(){
		if (typeof this.autoruntimer!="undefined")
			clearInterval(this.autoruntimer)
	},

	init:function(automodeperiod){
		var persistedtab = this.getCookie(this.tabinterfaceid) //get position of persisted tab (applicable if persistence is enabled)
		var persisterror = true //Bool variable to check whether persisted tab position is valid (can become invalid if user has modified tab structure)
		this.automodeperiod = automodeperiod || 0
		this.defaultHTML = this.content.innerHTML
		var tabs = this.tabs;
		
		for (var i=0; i < tabs.length; i++)
		{
			var tab = tabs[i];
			tab.tabposition=i //remember position of tab relative to its peers
			tab.url = tab.getAttribute('url');
			tab.frame = tab.getAttribute('frame') ? Boolean(tab.getAttribute('frame')) : false;
			tab.container = this.container;
			tab.rev = tab.getAttribute("rev");
			tab.id = tab.getAttribute("id");
			tab.index = i;
			//tabs.container = this;
			//alert(tab.id);
			/////tab.selected = tab.getAttribute("selected"); // DON'T USE THIS, selected is set during initialization!
			if(tab)
			{
				var tabinstance=this
				this.hottabspositions[this.hottabspositions.length]=i //store position of "hot" tab ("rel" attr defined) relative to its peers
				//Event.observe(element, eventName, handler[, useCapture = false])
				//Event.observe(tab, 'click', function()
				tab.onclick = function()
				{
					if(!tab) return;
					//alert(1)
					tabinstance.expandtab(this)
					tabinstance.cancelautorun() //stop auto cycling of tabs (if running)
					return false
				}
				if (tab.rev){ //if "rev" attr defined, store each value within "rev" as an array element
					this.revcontentids=this.revcontentids.concat(tabs.getAttribute("rev").split(/\s*,\s*/))
				}
				if (this.enabletabpersistence && parseInt(persistedtab)==i || !this.enabletabpersistence && tab.selected==true){
					this.expandtab(tab) //expand current tab if it's the persisted tab, or if persist=off, carries the "selected" CSS class
					persisterror=false //Persisted tab (if applicable) was found, so set "persisterror" to false
					//If currently selected tab's index(i) is greater than 0, this means its not the 1st tab, so set the tab to begin in automode to 1st tab:
					this.automode_currentTabIndex=(i>0)? 0 : 1
				}
			}

			this.tabs[i] = tab;

		} //END for loop
		
		if (persisterror) //if an error has occured while trying to retrieve persisted tab (based on its position within its peers)
			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.automode_currentTabIndex=this.automode_currentTabIndex || 0
			this.autoruntimer=setInterval(function(){tabinstance.autorun()}, this.automodeperiod)
		}
	}
}

