// add .hasJS class to html tag
document.documentElement.className="hasJS";

/* 
	popup div with ajax called content
	author mike foskett - 14/08/09
	version:5.1
	parameters:
		init(display class name)
*/
var poppit = function(){

	/* author: Simon Willisons - http://simon.incutio.com/archive/2004/05/26/addLoadEvent */
	function addLoadEvent(f){var o=window.onload;if(typeof window.onload!='function'){window.onload=f;}else{window.onload=function(){if(o){o();}f();};}}
	function jsCSS(a,o,c1,c2){switch(a){case'swap':o.className=!jsCSS('check',o,c1)? o.className.replace(c2,c1) : o.className.replace(c1,c2);break;case'add':if(!jsCSS('check',o,c1)){o.className+=o.className?' '+c1:c1;}break;case'remove':var rep=o.className.match(' '+c1)?' '+c1:c1;o.className=o.className.replace(rep,'');break;case'check':return new RegExp('\\b'+c1+'\\b').test(o.className);case'toggle':if (jsCSS('check',o,c1)){jsCSS('remove',o,c1);}else{jsCSS('add',o,c1);}break;}return false;}

	/* author: luke breuer - http://luke.breuer.com/tutorial/javascript-modal-dialog.aspx */
	function GetWindowHeight(){return document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight||document.body&&document.body.parentNode&&document.body.parentNode.clientHeight||0;}

	// XMLHttpRequest methods - author Jim Ley - http://jibbering.com/2002/4/httprequest.html
	var xmlhttp=false;
	/*@cc_on @*/
	/*@if (@_jscript_version>=5)
	try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")}catch(e){try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")}catch(E){xmlhttp=false}}
	@else
	xmlhttp=false
	@end @*/
	if(!xmlhttp&&typeof XMLHttpRequest!='undefined'){
		try{xmlhttp=new XMLHttpRequest();}
		catch(e){xmlhttp=false;}
	};
	if(!xmlhttp&&window.createRequest){
		try{xmlhttp=window.createRequest();}
		catch(e){xmlhttp=false;}
	}

	/* http://james.padolsey.com/javascript/get-document-height-cross-browser/ */
	function getDocHeight(){var D=document;return Math.max(Math.max(D.body.scrollHeight,D.documentElement.scrollHeight),Math.max(D.body.offsetHeight,D.documentElement.offsetHeight),Math.max(D.body.clientHeight,D.documentElement.clientHeight));}

	/* author: mike foskett - http://webSemantics.co.uk/ */
	function $id(id){return(document.getElementById(id)?document.getElementById(id):false);}
	function idExists(id){return($id(id)?true:false);}
	function replaceContent(id,content){if(idExists(id)){$id(id).innerHTML=content;}}
	function isDom(){return (document.getElementById && document.getElementsByTagName)?true:false;}
	function setOpacity(id,op){var o=$id(id).style;o.opacity=op/100;o.MozOpacity=op/100;o.KhtmlOpacity=op/100;o.filter="alpha(opacity="+op+")";}
	function isLessThanIE(version){if(navigator.appName=='Microsoft Internet Explorer'){var ua=navigator.userAgent,re=new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");if(re.exec(ua)!==null){if(parseFloat(RegExp.$1)<version){return true;}}}return false;}


	function addLightBoxBg(){
		if(!idExists('lightBox')){
			// first call create bg object
			var newDiv=document.createElement('div');
			newDiv.id="lightBox";
			if (isLessThanIE('8')){
				newDiv.style.height=GetWindowHeight()+"px";
			}
			// append to end of body
			document.body.appendChild(newDiv);
		}
		$id('lightBox').innerHTML="<p>Please wait.</p>";
	}


	function toggleLightBox(){
		jsCSS('toggle',$id('lightBox'),'lightBox');
	}


	function popOff(id){
		toggleLightBox();
		setOpacity(id,100);
		for(var o=0;o<100;o+=30){
			setTimeout("poppit.setOpacity('"+id+"',"+(100-o)+")",o*2);
		}
		// remove the displayClass (.show)
		setTimeout('poppit.jsCSS("remove",document.getElementById("'+id+'"),"'+$id(id).displayClass+'")',o*2);

		// optionally returns to original link (good for accessibility)
		return false;
	}

	function popOn(id){
	// THIS IE BIT SHOULD BE RELOCATED
		toggleLightBox();
		setOpacity(id,0);
		for(var o=0;o<101;o+=25){
			var op=(o>100)?100:o;
			setTimeout("poppit.setOpacity('"+id+"',"+op+")",o*2);
		}
		jsCSS('add',$id(id),$id(id).displayClass);
	}


	function popup(idName,linkId,displayClass){
		// store variables in objects for reference
		$id(linkId).idName=idName;
		$id(idName).linkId=linkId;
		$id(idName).displayClass=displayClass;
		$id(linkId).onclick=function(){
			// toggle via css class of popup.displayClass (.show)
			var divObj=$id(this.idName);
			if (jsCSS('check',divObj,divObj.displayClass)){var show=true;}
			if (!show){
				popOn(this.idName);
			}else{
				popOff(this.idName);
			}
			return false;
		};
	}

	function popups(){
		addLightBoxBg();

		// loop through all links using a "quick" loop method
		var A=document.getElementsByTagName("a");
		for(var i=A.length-1;i>-1;i--){
			// act on links with rel = "popupAjax" attribute only
			if (A[i].getAttribute("rel")=="popupAjax"){

				// link has variables attached:
				// idName= id of div to create for popup (filename+anchor)
				// incName= url of page to ajax without anchor
				// contentDivId= id of div in ajax page to copy, default is "content"

				// url stripped down to filename.extension#anchor
				var urlStripped=A[i].href.substring(A[i].href.lastIndexOf("/")).replace('/','');
				//alert(urlStripped)

				var filename=urlStripped.substring(0,urlStripped.lastIndexOf('.'));
				//alert(filename)

				var t=urlStripped.lastIndexOf('#');
				var anchor=(t>=0)?urlStripped.substring(t).replace('#',''):defaultAjaxContentId;
				//alert(anchor)

// ADD ANCHOR TO ORIGINAL HREF IF MISSING?
				var t=A[i].href.lastIndexOf('#');
				A[i].href=(t>=0)?A[i].href:A[i].href+'#'+anchor;

				// ensure id for div to create is unique.
				A[i].idName=filename+anchor;
				//alert(A[i].idName)

				// id of content in Ajaxed file
				A[i].contentDivId=anchor;

				// if the link does not have an id then give it one. Acts as a focus anchor upon return.
				A[i].id=(A[i].id)?A[i].id:A[i].idName+'Link'+i;
				A[i].linkId=A[i].id;

				// get url with anchor stripped out
				var t=A[i].href.lastIndexOf("#");
				A[i].incName=(t>=0)?A[i].href.substring(0,t):A[i].href;
				//alert(A[i].incName)


				A[i].onclick=function(){

					if(!idExists(this.idName)){
						// first click: create a new div for ajax content
						var newDiv=document.createElement('div');
						newDiv.id=this.idName;
						newDiv.incName=this.incName;
						newDiv.contentDivId=this.contentDivId;
						newDiv.linkId=this.linkId;
						newDiv.className="popup";

						//inside div
						var insideDiv=document.createElement('div');
						insideDiv.id=this.idName+'In';
						insideDiv.incName=this.incName;
						insideDiv.contentDivId=this.contentDivId;
						insideDiv.linkId=this.linkId;
						insideDiv.className="popupIn";

						// add to containing div
						newDiv.appendChild(insideDiv);

						// create a close link for pop-up - pass in pop-up id
						var linkObj=document.createElement('a');
						linkObj.href="#"+this.linkId;
						linkObj.id=this.linkId+"Close";
						linkObj.className=$id(this.linkId).className;
						linkObj.onclick=function(){return popOff(this.parentNode.id);};
						linkObj.appendChild(document.createTextNode("Return to main content"));
						newDiv.appendChild(linkObj);

						// add containing div to end of body
						document.body.appendChild(newDiv);

						toggleLightBox();
						//alert('bg on')

						// go get content
						getAjaxContent(this.idName,this.incName,this.contentDivId);

					}else{

// only ever called when a duplicated link is clicked for the first time
// NEEDS REWORKING AS IT DUPLICATES CODE IN GETAJAXCONTENT()

						toggleLightBox();
						popup(this.idName,this.linkId,popupDisplayClass);

						setOpacity(this.idName,0);
						for(var o=0;o<101;o+=25){
							var op=(o>90)?90:o;
							setTimeout("setOpacity('"+this.idName+"',"+op+")",o*2);
						}
						jsCSS('add',$id(this.idName),$id(this.idName).displayClass);

					}
					return false;
				};
			}
		}
	}


	function getAjaxContent(id,f,contentDivId){
		if(xmlhttp){
			xmlhttp.open("GET",f,true);
			xmlhttp.onreadystatechange=function(){
				if(xmlhttp.readyState==4){

					replaceContent(id+"In",xmlhttp.responseText);

					// strip content from delivered page
					// compensate for possible duplicated ids
					var divs=$id(id+"In").getElementsByTagName('div');
					for(var i=divs.length-1;i>-1;i--){
						if (divs[i].id===contentDivId){
						 replaceContent(id+"In",divs[i].innerHTML);
						 // remove please wait.
						 $id('lightBox').innerHTML="";
						 break;
						}
					}

// THIS CODE IS DUPLICATED - REWORK IT
					popup(id,$id(id).linkId,popupDisplayClass);
					setOpacity(id,0);
					for(var o=0;o<101;o+=25){
						var op=(o>90)?90:o;
						setTimeout("poppit.setOpacity('"+id+"',"+op+")",o*2);
					}
					jsCSS('add',$id(id),$id(id).displayClass);
				}
			};
			xmlhttp.send(null);
		}
	}

	var popupDisplayClass="show";
	var defaultAjaxContentId="content";

	function init(showClass){
		popupDisplayClass=showClass;
		if (isDom()){addLoadEvent(popups);}
	}



	return{ // public functions
		init:init,
		setOpacity:setOpacity,
		popOff:popOff,
		jsCSS:jsCSS
	};


}();

// parameters: popup display class, Ajax content id
poppit.init("show");
