// Original Code for DynamicDrive
// Visit http://www.dynamicdrive.com for original
//		now heavily modified for AGN

//Drop Down/ Overlapping Content: http://www.dynamicdrive.com
//**Updated: Dec 19th, 07': Added ability to dynamically populate a Drop Down content using an external file (Ajax feature)
//**Updated: Feb 29th, 08':
				//1) Added ability to reveal drop down content via "click" of anchor link (instead of default "mouseover")
				//2) Added ability to disable drop down content from auto hiding when mouse rolls out of it
				//3) Added hidediv(id) public function to directly hide drop down div dynamically

var timingID = "-";
var timingAD1 = "-";
var timingAD2 = "-";
var timingQuotes = "-";

var dropdowncontent={
	disableanchorlink: true, //when user clicks on anchor link, should link itself be disabled (always true if "revealbehavior" above set to "click")
	hidedivmouseout: [true, 400], //Set hiding behavior within Drop Down DIV itself: [hide_div_onmouseover?, miliseconds_before_hiding]
	ajaxloadingmsg: '<center><font class="loading"><img src="images/loading.gif" align="center"><br />Loading content. Please wait...</font></center>', //HTML to show while ajax page is being feched, if applicable
	ajaxbustcache: true, //Bust cache when fetching Ajax pages?

	getposOffset:function(what, offsettype){
		return (what.offsetParent)? what[offsettype]+this.getposOffset(what.offsetParent, offsettype) : what[offsettype]
	},

	isContained:function(m, e){
		var e=window.event || e
		var c=e.relatedTarget || ((e.type=="mouseover")? e.fromElement : e.toElement)
		while (c && c!=m)try {c=c.parentNode} catch(e){c=m}
		if (c==m)
			return true
		else
			return false
	},

	show:function(anchorobj, subobj, e){
		if(subobj.style.visibility == 'visible'){
			return false
		}
		var now = new Date()
		if(((now.getTime() - subobj.loaded) > 900000) ){ //if content is more than 15min old (in miliseconds !!)
			this.ajaxconnect(anchorobj.getAttribute("rev"), anchorobj.getAttribute("rel"))
		}
		if (!this.isContained(anchorobj, e)){
			var e=window.event || e
			if (e.type=="click" && subobj.style.visibility=="visible"){
				subobj.style.visibility="hidden"
				return
			}
			var horizontaloffset=(subobj.dropposition[0]=="left")? -(subobj.offsetWidth-anchorobj.offsetWidth) : 0 //calculate user added horizontal offset
			var verticaloffset=(subobj.dropposition[1]=="top")? -subobj.offsetHeight : anchorobj.offsetHeight //calculate user added vertical offset
			subobj.style.left=this.getposOffset(anchorobj, "offsetLeft") + horizontaloffset + "px"
			subobj.style.top=this.getposOffset(anchorobj, "offsetTop")+verticaloffset+"px"
			subobj.style.clip=(subobj.dropposition[1]=="top")? "rect(auto auto auto 0)" : "rect(0 auto 0 0)" //hide drop down box initially via clipping
			subobj.style.visibility="visible"
			subobj.startTime=new Date().getTime()
			subobj.contentheight=parseInt(subobj.offsetHeight)
			if (typeof window["hidetimer_"+subobj.id]!="undefined"){ //clear timer that hides drop down box?
				clearTimeout(window["hidetimer_"+subobj.id])
			}
			this.slideengine(subobj, (subobj.dropposition[1]=="top")? "up" : "down")
		}
	},

	curveincrement:function(percent){
		return (1-Math.cos(percent*Math.PI)) / 2 //return cos curve based value from a percentage input
	},

	slideengine:function(obj, direction){
		var elapsed=new Date().getTime()-obj.startTime //get time animation has run
		if (elapsed<obj.glidetime){ //if time run is less than specified length
			var distancepercent=(direction=="down")? this.curveincrement(elapsed/obj.glidetime) : 1-this.curveincrement(elapsed/obj.glidetime)
			var currentclip=(distancepercent*obj.contentheight)+"px"
			obj.style.clip=(direction=="down")? "rect(0 auto "+currentclip+" 0)" : "rect("+currentclip+" auto auto 0)"
			window["glidetimer_"+obj.id]=setTimeout(function(){dropdowncontent.slideengine(obj, direction)}, 10)
		}
		else{ //if animation finished
			obj.style.clip="rect(0 auto auto 0)"
		}
	},

	hide:function(activeobj, subobj, e){
		if (!dropdowncontent.isContained(activeobj, e)){
			window["hidetimer_"+subobj.id]=setTimeout(function(){
				subobj.style.visibility="hidden"
				subobj.style.left=subobj.style.top=0
				clearTimeout(window["glidetimer_"+subobj.id])
			}, dropdowncontent.hidedivmouseout[1])
		}
	},

	hidediv:function(subobjid){
		document.getElementById(subobjid).style.visibility="hidden"
	},

	ajaxconnect:function(pageurl, divId){
		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
		}
		document.getElementById(divId).innerHTML=this.ajaxloadingmsg //Display "fetching page message"
		page_request.onreadystatechange=function(){
			dropdowncontent.loadpage(page_request, divId)
			var now = new Date();
			document.getElementById(divId).loaded = now.getTime();
		}
		if (this.ajaxbustcache){ //if bust caching of external page
			bustcacheparameter=(pageurl.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
		}
		page_request.open('GET', pageurl+bustcacheparameter, true)
		page_request.send(null)
	},

	loadpage:function(page_request, divId){
		if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)){
			document.getElementById(divId).innerHTML=page_request.responseText
		}
	},

	init:function(anchorid, pos, glidetime, revealbehavior){
		var anchorobj=document.getElementById(anchorid)
		var subobj=document.getElementById(anchorobj.getAttribute("rel"))
		var subobjsource=anchorobj.getAttribute("rev")
		if (subobjsource!=null && subobjsource!=""){
			this.ajaxconnect(subobjsource, anchorobj.getAttribute("rel"))
		}
		subobj.dropposition=pos.split("-")
		subobj.glidetime=glidetime || 1000
		subobj.style.left=subobj.style.top=0
		if (typeof revealbehavior=="undefined" || revealbehavior=="mouseover"){ //react mouseover only
			anchorobj.onmouseover=function(e){dropdowncontent.show(this, subobj, e)}
			anchorobj.onmouseout=function(e){dropdowncontent.hide(subobj, subobj, e)}
			if (this.disableanchorlink) anchorobj.onclick=function(){return false}
		}else{ //show on click
			anchorobj.onclick=function(e){dropdowncontent.show(this, subobj, e); return false}
		}
		
		if (this.hidedivmouseout[0]==true){ //hide drop down DIV when mouse rolls out of it?
			subobj.onmouseout=function(e){dropdowncontent.hide(this, subobj, e)}
		}
		if(revealbehavior=="clickonly"){
			subobj.onmouseout= ''	//do nothing onmouse out
		}
		if(revealbehavior=="mcOver_clickclose"){
			anchorobj.onmouseover=function(e){dropdowncontent.show(this, subobj, e)}
			anchorobj.onclick=function(e){dropdowncontent.show(this, subobj, e); return false}
			subobj.onmouseout= ''	//do nothing onmouse out
		}
	},
	
	userLogin:function(){
		var loginurl = 'include/include_user_login.php'
		var login_request = false
		if (window.XMLHttpRequest){ // if Mozilla, IE7, Safari etc
			login_request = new XMLHttpRequest()
		}else if (window.ActiveXObject){ // if IE6 or below
			try {
				login_request = new ActiveXObject("Msxml2.XMLHTTP")
			} 
			catch (e){
				try{
					login_request = new ActiveXObject("Microsoft.XMLHTTP")
				}
				catch (e){}
			}
		}else{
			return false
		}
		if (login_request == null) {
			alert("Your browser doesn't support AJAX.");
			document.forms['user_login'].submit();
			end	
		}else{
			var passData = "uname=" + document.getElementById('u_name').value + "&upass=" + document.getElementById('u_pass').value
			document.getElementById('userbox').innerHTML = '<center><font class="loading"><img src="images/loading.gif" align="center"><br />Loading content. Please wait...</font></center>' //Display "fetching page message"
			
			login_request.open('POST', loginurl, true)
			login_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			login_request.send(passData);
	
			login_request.onreadystatechange = function() {
				if (login_request.readyState==4 || login_request.readyState=="complete") {
					if(login_request.responseText == "success"){	// login in successful reload box and headerbar text
						//dropdowncontent.ajaxconnect('include/include_user_top.php', 'userbox')
						dropdowncontent.ajaxconnect('include/include_user_top.php?f=textline', 'usertext')
						dropdowncontent.init("userlink", "left-bottom", 500, 'mcOver_clickclose')//must AJAX the new bar!
					}else{
						alert("Login Failed. Please try again : " + login_request.responseText)
						dropdowncontent.ajaxconnect('include/include_user_top.php', 'userbox')
					}
				}
			}
		}	//end of login_request == null else
	}	//end of userLogin:function
}

var pagecontent={
	ajaxloadingmsg: '<table align="center" width="95%" bgcolor="#000000" height="100%"><tr><td align="center" height="300"><font class="loading"><img src="images/loading.gif" align="center"><br />Loading content. Please wait...</font></td></tr></table>', //HTML to show while ajax page is being feched, if applicable
	ajaxexist: false,
	ajaxloadingmsg_post:'<table align="center" width="95%" bgcolor="#000000" height="100%"><tr><td align="center" height="300"><font class="loading">Your information has been sent <img src="images/loading.gif" align="center"><br />Please wait for a response...</font></td></tr></table>', //HTML to show while ajax page is being feched, if applicable
	page : "-",

	init:function(){
		pagecontent.sortoutlinks();
	},

	followlink:function(submenulink){
		var domainURL = 'http://www.absolutegamerz.com/'
		var LinkTarget = new String(submenulink)
		var TargetDom = LinkTarget.substring(0,domainURL.length)
		var scriptLink = ''
		if (TargetDom == domainURL){//link is on this site
			scriptLink = LinkTarget.replace(domainURL, '')
			if(scriptLink.substring(0,8) == 'include_'){//ajax-ed page link
				pagecontent.connect(scriptLink )
				return false;
			}else{ //old link, reformat it to a new one.
				//alert('reformating link to show: include_' + scriptLink)
				pagecontent.connect('include/include_' + scriptLink )
				return false;
			}
		}else{//it's an external link
//			alert('does not match, domainURL:'+domainURL+'; TargetDom:' + TargetDom+';');
			window.open(submenulink,'');
			return false;
		}
	},

	connect:function(pageurl){
		var content_request = false
		if (window.XMLHttpRequest){ // if Mozilla, IE7, Safari etc
			content_request = new XMLHttpRequest()
		}else if (window.ActiveXObject){ // if IE6 or below
			try {
				content_request = new ActiveXObject("Msxml2.XMLHTTP")
			} 
			catch (e){
				try{
					content_request = new ActiveXObject("Microsoft.XMLHTTP")
				}
				catch (e){}
			}
		}else{
			alert('failed');
			return false
		}

		if(document.body.scrollTop > 200){
			timingID = setInterval("scrolluppage()", 1);
		}		

		document.getElementById('Site_Content').innerHTML=this.ajaxloadingmsg //Display "fetching page message"

		content_request.onreadystatechange=function(){
			if (content_request.readyState == 4 && (content_request.status==200)){
				document.getElementById('Site_Content').innerHTML = content_request.responseText;
				pagecontent.sortoutlinks();
				document.body.style.cursor = "auto";
			}
		}

		document.body.style.cursor = "progress";
		content_request.open('GET', pageurl, true)
		content_request.send(null)

	},

	sortoutlinks: function(){
		var mainInstance = this;
		var extra = "-";
		thispage = document.getElementById('Site_Content');
		for (var j = 0; j < thispage.getElementsByTagName('a').length; j++){
			if(thispage.getElementsByTagName('a')[j].getAttribute('rel') == 'AGN_Playr'){
					var relUrl = thispage.getElementsByTagName('a')[j].getAttribute('relUrl')
				thispage.getElementsByTagName('a')[j].onclick = function(){
					/*alert('url is:' + relUrl1 +'|'+ rel2 + '|' + thispage.getElementsByTagName('a')[j].getAttribute('relUrl') + '|' + thispage.getElementsByTagName('a')[j].getAttribute('rel') + '/8.4/')*/
					window.open('http://www.absolutegamerz.com/player/' + relUrl + '/index.php','AGN_Playr','toolbar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,copyhistory=no,width=850,height=610');
				}
			}else{
				thispage.getElementsByTagName('a')[j].onclick = function() {
					mainInstance.followlink(this)
					return false
				}
			}
		}
		extra = document.getElementById('extra');
		if(extra != null){
			if (extra.getAttribute('value') == 'lightbox'){
				initLightbox();
			}
			if (extra.getAttribute('value') == 'wysiwyg'){
				if(document.getElementById('defaultpageload').value == 0){
					var mysettings = new WYSIWYG.Settings(); 
					mysettings.ImagesDir = "/images/wysiwyg/";
					mysettings.PopupsDir = "/include/wysiwyg/";
					mysettings.CSSFile = "/css/wysiwyg.css"; 
					mysettings.PreviewWidth = '450'; 
					mysettings.Width = '450px'; 
					mysettings.DefaultStyle = "font-family: Arial; font-size: 12px; background-color: #FFFFFF; color:#333333;";
					WYSIWYG.attach('postmsg', mysettings, 1);
				}
			}
		}
		for (var j= 0; j < thispage.getElementsByTagName('input').length; j++){
			if(thispage.getElementsByTagName('input')[j].getAttribute('type') == 'submit'){
				thispage.getElementsByTagName('input')[j].onclick = function() {
					mainInstance.postFormAjaxed(this)
					return false
				}
			}
		}
	},
	
	postFormAjaxed: function(childObj){
		// find the form object
	    var testObj = childObj.parentNode;
	    var count = 1;
    	while(testObj.nodeName.toUpperCase() != 'FORM') {
	        testObj = testObj.parentNode;
	        count++;
	    }
	    // now you have the object you are looking for - do something with it
		var submiterFormReady = $(testObj).serialize()
		var loginurl = 'include/include_'+testObj.getAttribute('action')


		var post_request = false
		if (window.XMLHttpRequest){ // if Mozilla, IE7, Safari etc
			post_request = new XMLHttpRequest()
		}else if (window.ActiveXObject){ // if IE6 or below
			try {
				post_request = new ActiveXObject("Msxml2.XMLHTTP")
			} 
			catch (e){
				try{
					post_request = new ActiveXObject("Microsoft.XMLHTTP")
				}
				catch (e){}
			}
		}else{
			alert('failed');
			return false
		}

		if(document.body.scrollTop > 200){
			timingID = setInterval("scrolluppage()", 1);
		}		

		document.getElementById('Site_Content').innerHTML=this.ajaxloadingmsg_post //Display "fetching page message"
			
		post_request.open('POST', loginurl, true)
		post_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		post_request.send(submiterFormReady);

		post_request.onreadystatechange = function() {
			if (post_request.readyState==4 || post_request.readyState=="complete") {
				document.getElementById('Site_Content').innerHTML = post_request.responseText;
			}
		}
	}// end of postforms function
}

function UserMenu(page){
	var ajaxloadingmsg = '<table cellpadding="4" width="90%" align="center" height="400" valign="top" bgcolor="#000000"><tr><td height="400" align="center"><p><font class="loading"><img src="images/loading.gif" align="center"><br />Loading content. Please wait...</font></p></td></tr></table>'; //HTML to show while ajax page is being feched, if applicable

	document.body.style.cursor = "progress";
	document.getElementById('Site_Content').innerHTML = ajaxloadingmsg;

	new Ajax.Request('include/include_' + page,   {
		method:'get',
		onSuccess: function(transport){
			var response = transport.responseText || "no response text";
			document.getElementById('Site_Content').innerHTML = response;
			scrolluppage();
			pagecontent.sortoutlinks();
			document.body.style.cursor = "auto";
		},
		onFailure: function(){
			alert('Something went wrong... AJAX could not load the requested page');
			document.body.style.cursor = "auto";
		}
	});
	
	dropdowncontent.hidediv('userbox')
	
}

function scrolluppage(){
	if(document.body.scrollTop > 0){
		self.scrollBy(0,-15);
	}else{
		clearInterval(timingID);
	}
}

function runExtras(){
	timingAD1 = setInterval("AJAXExtras('include/include_ads_agn.php', 'ADsmalllright')", 480000);	//8min
	timingAD2 = setInterval("AJAXExtras('include/include_ads_tall.php', 'ADtallright')", 320000);	//5.3min
	timingQuotes = setInterval("AJAXExtras('include/include_rand_quote.php', 'Quotes')", 280000);	//4.6min
}

function AJAXExtras(turl,tid){
	var Extra_request = false
	if (window.XMLHttpRequest){ // if Mozilla, IE7, Safari etc
		Extra_request = new XMLHttpRequest()
	}else if (window.ActiveXObject){ // if IE6 or below
		try {
			Extra_request = new ActiveXObject("Msxml2.XMLHTTP")
		} 
		catch (e){
			try{
				Extra_request = new ActiveXObject("Microsoft.XMLHTTP")
			}
			catch (e){}
		}
	}else{
		return false
	}


	Extra_request.onreadystatechange=function(){
		if (Extra_request.readyState == 4 && (Extra_request.status==200)){
			document.getElementById(tid).innerHTML = Extra_request.responseText
		}
	}
	Extra_request.open('GET', turl, true)
	Extra_request.send(null)
}
