
//click tracking code 7/2006 Mike Warner
var now = new Date();
var userAction="";
var theURL="";
var pauseVar=0;
var dbHit=0;
var linkText="nada";
var buttonText="";
//moved to template
//var theData='<sm type="area" name="memberID">,<sm type="area" name="crID">,<sm type="area" name="sID">'.split(",")
		
function pause(numberMillis) {
    var exitTime = now.getTime() + numberMillis;
    while (true) {
        now = new Date();
        if (now.getTime() > exitTime)
            return;
    }
}



function setLinkTrackingCode(){
	//add tracking to buttons (regular and submit)
	for(g=0;g<document.getElementsByTagName('input').length;g++){
		if(document.getElementsByTagName('input')[g].type=="button"||document.getElementsByTagName('input')[g].type=="submit"){
			//don't put in on normal buttons, just Submit buttons MWarner 3/16/09
			//removed:  put it back 4/14/09
		
			//if there's no onclick already, add it...
			if(!document.getElementsByTagName('input')[g].onclick){
				document.getElementsByTagName('input')[g].onclick=function(){
					buttonText=this.value;
					trackIt(this,buttonText);
				}
			}else{
				//onclick already exists, so modify it
				tmp=getOnClickBit(document.getElementsByTagName('input')[g].onclick);
				document.getElementsByTagName('input')[g].onclick=null;
				//use eval() for the whole statement.  It's the only way to do this
				eval("document.getElementsByTagName('input')[g].onclick=function(){"+tmp+";buttonText=this.value;trackIt(this,buttonText)}")
			}
		}
	}
	
	//add tracking to links
	for(g=0;g<document.getElementsByTagName('a').length;g++){
		if(document.getElementsByTagName('a')[g].href.indexOf("javascript")>-1 || document.getElementsByTagName('a')[g].onclick){
			continue;
		}
		//check for existing onclick handler
		//if(!document.getElementsByTagName('a')[g].onclick){
		if(!document.getElementsByTagName('a')[g].onclick){
			//if there isn't one and the href is 'javascript:something" then modify the javascript call (more robust to have all javascript calls in one place)
			if(document.getElementsByTagName('a')[g].href.indexOf("javascript")>-1){
				tmp=document.getElementsByTagName('a')[g].href;
				//if(document.getElementsByTagName('a')[g].href.lastIndexOf(";")==document.getElementsByTagName('a')[g].href.length-1){
					replaceWith="&#039;";
					reg = new RegExp(/["'"]/g);
					tmp2=tmp.replace(reg,replaceWith);	
					//don't add it here (on links with onClick already) anymore MWarner 3/16/09 
					//- cleans up code for when we're trying to debug an interactive by looking at the page source.
					//document.getElementsByTagName('a')[g].href="javascript:trackIt(this,false,'"+escape(escape(tmp2))+"');"+tmp;//,false,'"+escape(tmp)+"')";
				/*
				}else{
					document.getElementsByTagName('a')[g].href=tmp+";trackIt(this,false,'testing:"+escape(escape(tmp))+"')";//,false,'"+escape(tmp)+"')";
				}
				*/
			}else{
				if(document.getElementsByTagName('a')[g].href.indexOf("javascript")<0){//new 3/16/09 MWarner
					document.getElementsByTagName('a')[g].onclick=function(){
							trackIt(this);
					}
				}
			}
		}else{
			//there is an onclick, but change it to "javascript:..."
			tmp=getOnClickBit(document.getElementsByTagName('a')[g].onclick)
			//if(document.getElementsByTagName('a')[g].href.indexOf("#")>-1){
			if(document.getElementsByTagName('a')[g].href.indexOf("#")>-1 && document.getElementsByTagName('a')[g].href.indexOf("javascript")<0){//new 3/16/09 MWarner
				document.getElementsByTagName('a')[g].onclick=null;
				replaceWith="&#039;";
				reg = new RegExp(/["'"]/g);
				tmp2=tmp.replace(reg,replaceWith);
				document.getElementsByTagName('a')[g].href="javascript:"+tmp+";trackIt(this,false,'javascript:"+escape(escape(tmp2))+"')";			
			}
			
		}
	}
}

function getOnClickBit(fromWhat){
	tmp=fromWhat.toString().split("{");
	tmp=tmp[1].split("}");
	return tmp[0];
}

function trackIt(whichLink,buttonValue,escapedHref){
	prevURL=document.location.href;
	SetCookie("prevURL",prevURL);
	
	linkText=(buttonValue)?buttonValue:escape(whichLink.innerHTML);
	//alert(linkText)
	//default action
	userAction="nav-link-click";
	userAction=(buttonValue)?buttonValue:userAction;
	if(!buttonValue){
		theURL=(escapedHref)?escapedHref:whichLink.href;//(whichLink.href)?escape(whichLink.href):escapedHref;//"javascript link";
		//pop-up, javascript, etc
		if(hasTarget(whichLink)||theURL.indexOf("#")!=-1||theURL.indexOf("javascript")!=-1){
			userAction="non-nav-link-click";
		}
		//if(whichLink.href.indexOf("memberLogout")>-1){
		if(theURL.indexOf("memberLogout")>-1){
			userAction="logout";
		}
		if(linkText=="Reply"){
			userAction="discuss-reply-link-click";
		}
	}else{
		theURL="";
		buttonText=buttonValue;
		userAction="btn click: "+buttonValue;
	}
	
	SetCookie("userAction",userAction);
	
	pullerUrl="/tools/clickTracker.php?pause="+theData+"&action="+userAction+"&now="+now.getTime()+"&theURL="+theURL+"&linkText="+linkText;
	ajax_save(pullerUrl);
	//for debugging: 
	//prompt('link click',tmp3.src)
	if(userAction!="non-nav-link-click"&&!buttonValue){//don't need it otherwise
		//pause(pauseVar)//pause a bit to let the php code get rolling
	}
	//return true;
}

function hasTarget(whichLink){
	if(whichLink.target=="undefined"||whichLink.target==""||!whichLink.target||whichLink.target==null){
		return false;
	}else{
		return true;
	}
}

/*	*/

window.onbeforeunload=function(){
	extraBits="";
	prevURL=document.location.href;
	SetCookie("prevURL",prevURL);
	if(!theURL&&!buttonText){//check for theURL, as this gets set on a link click
		
		userAction=(buttonText)?buttonText:"leftCMS";
		
		prevURL=(GetCookie('prevURL'))?GetCookie('prevURL'):"filler";
		if(location.search.indexOf("v=test")>-1){
			//all other symptoms of clicking a button in a test are the same as clicking the forward button
			userAction="started test";
			extraBits=+"&theURL="+document.location.href;
		}
		if(location.search.indexOf("v=testQ")>-1){
			//all other symptoms of clicking a button in a test are the same as clicking the forward button
			userAction="answered test question";
			extraBits=+"&theURL="+document.location.href;
		}
		SetCookie("userAction",userAction);
		pullerUrl="/tools/clickTracker.php?pause="+theData+"&action="+userAction+"&now="+now.getTime()+extraBits;
		ajax_save(pullerUrl);
		//prompt('onbeforeunload',tmp.src)
		dbHit=1;		
	}
}	

//for the Opera browser
window.onunload=function(){
	if(!theURL&&!buttonText){
		if(navigator.appName=="Opera"&&theData[1]){//Opera doesn't support onbeforeunload, so...
			pullerUrl="/tools/clickTracker.php?pause="+theData+"&action="+userAction+"&now="+now.getTime()+"&theURL="+theURL+"&linkText="+linkText;
			ajax_save(pullerUrl);
			prevURL=document.location.href;
			SetCookie("prevURL",prevURL);
		}
	}
}

/**/
window.onload=function(){
	setLinkTrackingCode();
	//check the previous non-link navigation 
	prevURL=(GetCookie('prevURL'))?GetCookie('prevURL'):"filler";
	prevUrl_bits=prevURL.split("/");
	currentURL=document.location.href;
	currentURL_bits=document.location.href.split("/");
	//default url
	pullerUrl="/tools/clickTracker.php?pause="+theData+"&now="+now.getTime()+"&theURL="+escape(currentURL)
		
	//alert(prevURL)
	
	//check the following only if the userAction is leftCMS (set by the user clicking a browser control, not anything on the page)
	if(GetCookie('userAction')=="leftCMS"){
		if(prevURL==document.location.href){
			//is refresh so remove last entry for this user, which was a leftCMS event (entered by onunload w/o link click)
			//alert("refresh?")
			userAction="refreshed page";
			pullerUrl+="&action=delete&userAction=refreshed+page&lastRow="+GetCookie("lastRow");
		}
		
		if(prevURL!=document.referrer && currentURL!=document.referrer && prevURL!=currentURL){
			//back button clicked, so remove last leftCMS entry (just added when the prev page unloaded w/o link click)
			//alert("back button?")
			userAction="clicked back button";
			pullerUrl+="&action=delete&userAction=clicked+back+button&lastRow="+GetCookie("lastRow");
		}
		
		if(prevURL==document.referrer  && document.location.href.indexOf("viewThread.php")==-1){
			//forward button clicked, so remove last leftCMS entry (just added when the prev page unloaded w/o link click)
			//alert("forward button?")
			userAction="clicked forward button";
			pullerUrl+="&action=delete&userAction=clicked+forward+button&lastRow="+GetCookie("lastRow");
		}
		ajax_save(pullerUrl)
	}
}

function ajax_save(pullerUrl){
	//alert(pullerUrl)
	xhr=null;
	// non-IE
	if (window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	}
	// IE version - activeX
	else if (window.ActiveXObject){
		xhr = new ActiveXObject("Microsoft.XMLHTTP");
	}
	xhr.open("GET",pullerUrl);
	/*only needed for POST
	xhr.setRequestHeader(
		'Content-Type',
		'application/x-www-form-urlencoded; charset=UTF-8');
	*/
	xhr.setRequestHeader("Pragma", "no-cache"); 
	xhr.setRequestHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); 
	xhr.setRequestHeader("Cache-Control", "no-store, must-revalidate,must-revalidate, max-age=-1"); 
			
	if(window.XMLHttpRequest){//non-IE
		xhr.send(null);
	}	
	else if(window.ActiveXObject){//IE
		xhr.send();
	}
	xhr.onreadystatechange=function() {
		if(xhr.readyState==4){
			//doWindowOpenWriteText("height=300,width=400",xhr.responseText)
			SetCookie("lastRow",xhr.responseText);
			//alert(xhr.responseText)
			return;//returnToFunction(xhr.responseText);			
		}
	}
}

