/*
*
* dm9 DCL (Dyniamic Content Loader)
* dependencies:
*		./gen.js
*			- getElement()
*			-	insertHTML()
*			- addEvent()
*
* adapted for orrensjo.com by Ragnar Seton of dm9.se
*
*/

/*
* using a global to store loaded url to fix the
* back, forward and bookmark issues that comes
* with an AJAX app
*/
var DCL_loadedURL="";

function DCL_loadContent(page,target)
{
	var req=false;
	
	window.status='DCL: loading content...';
	
	if(/partners\.php/.test(page) || /enter\.php/.test(page))
	{
		getElement('container').style.backgroundColor='transparent';
		getElement('shadow').style.visibility='hidden';
	}
	else
	{
		getElement('container').style.backgroundColor='#efefef';
		getElement('shadow').style.visibility='visible';
	}	
	
	req=DCL_httpRequest();
	if(req)
	{
		req.onreadystatechange=function(){ DCL_processReqChange(req,target) };
		req.open("GET",page,true);
		req.send("");
		window.status='DCL: request sent...'
	}
	else DCL_error(-1,'Could not set up request.','No further information available.');
}

function DCL_submitForm(frm,page,target)
{
	var req=false;
	var frmData="";
	var method="";
	var urlSplit=new Array();
	
	frmData=DCL_formatFormData(document.forms[frm]);
	method=document.forms[frm].method.toUpperCase();
	req=DCL_httpRequest();
	if(req)
	{
		req.onreadystatechange=function(){ DCL_processReqChange(req,target) };
		if(method=="POST")
		{
			req.open("POST",page,true);
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			req.setRequestHeader("Content-length", frmData.length);
			req.setRequestHeader("Connection", "close");
			req.send(frmData);
		}
		else
		{
			page+="?"+frmData;
			req.open("GET",page,true);
			req.send("");
		}
		
		urlSplit=window.location.href.split("#");
		if(document.DCL_ieFix)
		{
			/*
			* passing noProbe switch to DCL_ieFix.php to avoid extra
			* update of the page posted to.
			*/
			getElement('DCL_ieNav').setAttribute("src","DCL_ieFix.php?noProbe=1&page="+escape(page));
			window.location=urlSplit[0]+"#"+page;
		}
		else
		{
			/*
			* update window.location for back/bookmark and
			* DCL_loadedURL to avoid extra update 
			*/
			window.location=DCL_loadedURL=urlSplit[0]+"#"+page;
		}
	}
	else DCL_error(-1,'Could not set up request.','No further information available.');
}

function DCL_loadExternalFile()
{
	var i,loadedFiles,fp,fileRef;
	
	for(i=0;i<arguments.length;i++)
	{
		fp=arguments[i];
		fileRef="";
		
		if(loadedFiles.indexOf(fp)==-1)
		{
			if(/\.js$/i.test(fp))
			{
				/* load javascript file */
				fileRef=document.createElement('script');
				fileRef.setAttribute("type","text/javascript");
				fileRef.setAttribute("src", fp);
			}
			else if(/\.js$/i.test(fp))
			{
				/* load cascading style sheet file */
				fileRef=document.createElement("link");
				fileRef.setAttribute("rel", "stylesheet");
				fileRef.setAttribute("type", "text/css");
				fileRef.setAttribute("href", fp);
			}
		}
		if(fileRef!="")
		{
			document.getElementsByTagName('head').item(0).appendChild(fileref);
			loadedFiles+=fp+" ";
		}
	}
}

function DCL_httpRequest()
{
	var req=false;
	
	if(window.XMLHttpRequest)
	{
		try{ req=new XMLHttpRequest(); }
		catch(e){ req=false; }
		/*
		* since well be transfering html
		*/
		if(req && req.overrideMimeType) req.overrideMimeType('text/html');
	}
	else if(window.ActiveXObject)
	{
		try{ req=new ActiveXObject("Msxml2.XMLHTTP"); }
		catch(e)
		{
			try{ req=new ActiveXObject("Microsoft.XMLHTTP"); }
			catch(e){ req=false; }
		}
	}
	return req;
}

function DCL_formatFormData(frm)
{
	var i,j,clearedGroups="",postStr="";
	var fe=frm.elements;
	
	for(i=0;i<fe.length;i++)
	{
		if(!fe[i].disabled)
		{
			switch(fe[i].type)
			{
				case "select-one":
					if(fe[i].selectedIndex>=0)
						postStr+=fe[i].name+"="+encodeURI(fe[i].options[fe[i].selectedIndex].value)+"&";
				break;
				case "select-multiple":
					for(j=0;j<fe[i].options.length;j++)
					{
						if(fe[i].options[j].selected)
							postStr+=fe[i].name+"="+encodeURI(fe[i].options[j].value)+"&";
					}
				break;
				case "radio":
				/*
				* theres no need to loop through the same group of radios
				* more than once (each radiobutton will be trigger this case
				* no matter of group).
				*/
				if(clearedGroups.indexOf(fe[i].name)==-1)
				{
					for(j=0;j<fe[fe[i].name].length;j++)
					{
						if(fe[fe[i].name][j].checked)
						{
							postStr+=fe[fe[i].name][j].name+"="+encodeURI(fe[fe[i].name][j].value)+"&";
							break;
						}
					}
					clearedGroups+=fe[i].name+" ";
				}
				break;
				case "checkbox":
					if(fe[i].checked)
						postStr+=fe[i].name+"="+encodeURI(fe[i].value)+"&";
				break;
				case "button": case "submit": case "reset":
					/* dont add button values */
				break;
				default:
					/* quick and dirty fix */
					tmp=escape(fe[i].value);
					if(tmp.indexOf("+")!=-1) tmp=tmp.replace(/\+/,'%2B');
					postStr+=fe[i].name+"="+tmp+"&";
			}
		}
	}
	return postStr.substr(0,postStr.length-1);
}

function DCL_processReqChange(req,target)
{
	/*
	* full list of readystates
	* http://www.w3.org/TR/XMLHttpRequest/#dfn-readystate
	*
	* more extensive readyState handeling is available
	* in the full version of DCL. visit www.dm9.se or
	* contact ragnar@dm9.se for further information.
	*/
	
	if(req.readyState==4)
	{
		/*
		* status code 200 == "OK"
		* full HTTP/1.1 status code definitions at
		* http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
		*/
		if(req.status==200)
		{
			insertHTML(target,req.responseText);
			/*
			* adaptation, since used with DSC the scroller should be reinited here
			*/
			DCS_initialize();
			if(document.DCL_ieFix) getElement(target).style.top=0; // getElement(target).parentElement.scrollTop=0;
			else getElement(target).parentNode.scrollTop=0;
			window.status='DCL: done!';
		}
		else
		{
			window.status='DCL: request return code '+req.status;
			DCL_error(req.status,req.statusText,req.getAllResponseHeaders());
		}
	}
	else window.status='DCL: readystate '+req.readyState;
}

function DCL_error(code,text,info)
{
	alert("The request could not be completed.\n"
		+"statuscode: "+code+"\n"
		+"statustext: "+text+"\n"
		+"full info:\n"+info);
}

function DCL_queryURL()
{
	if(window.location.href!=DCL_loadedURL)
	{
		window.status='DCL: querying url...';
		/*
		* what now?! declaring vairables in the middle of a func!
		* since the function is polled every 0.2 sec theres no
		* need to allocate memmory each run =)
		*/
		var urlSplit=window.location.href.split("#");
		if(window.location.href.indexOf("#")>-1 &&
			/\.php/i.test(urlSplit[urlSplit.length-1]))
				DCL_loadContent(urlSplit[urlSplit.length-1],'content');
		else if(window.location.href.indexOf("#")==-1)
		{
			/*
			* the above if clause is used to prevent 
			* a buffer overflow vuln in older browsers
			*/
			
			/* add cookie check */
			
			window.location+='#tmppages/home.php';
			DCL_loadContent('tmppages/home.php','content');
		}
		DCL_loadedURL=window.location.href;
	}
}

function DCL_ieQueryURL(page,phpTimestamp)
{
	var urlSplit=new Array();
	var now=new Date();
	var gmtTimestamp=0;
	
	urlSplit=window.location.href.split("#");

	if(window.location.href.indexOf("#")>-1)
	{
		/*
		* calc unix gmt timestamp and determine what was clicked
		*/
		gmtTimestamp=now.getTime();
		gmtTimestamp+=(now.getTimezoneOffset()*3600);
		gmtTimestamp/=1000;
		if(gmtTimestamp<phpTimestamp)
		{
			/* iframe reload click */
			DCL_loadContent(unescape(page),'content');
			window.location=urlSplit[0]+"#"+unescape(page);
		}
		else
		{
			/* link click */
			DCL_loadContent(urlSplit[urlSplit.length-1],'content');
			getElement('DCL_ieNav').setAttribute("src","DCL_ieFix.php?page="+escape(urlSplit[urlSplit.length-1]));
		}
	}
	else
	{
		/* start page */
		DCL_loadContent(page,'content');
		window.location=urlSplit[0]+"#"+escape(page);
	}
}

function DCL_link(page)
{
	var urlSplit=window.location.href.split("#");
	window.location=urlSplit[0]+"#"+page;
	invokesubmenu(page);
	if(document.DCL_ieFix)
		getElement('DCL_ieNav').setAttribute("src","DCL_ieFix.php?page="+escape(page));
	else DCL_queryURL();
}

function DCL_browserButtonsFix()
{
	if(!gebiSupport) return false;
	
	/*
	* poll for changes in the adressbar..
	* its a working solution but i shure hope as ajax apps grows
	* that it will be possible to alter the history object or
	* even better to create a page specifik historyobject
	*/
	setInterval("DCL_queryURL()",200);
}

/*
* well, ms didnt cut it this time either.
* one generic and one ms ie version it is then!
*/
if(navigator.userAgent.toLowerCase().indexOf("msie")>-1) document.DCL_ieFix=true;
else addEvent(window, "load", DCL_browserButtonsFix);
