var o="";
var k="";
var l="";
var step2="";
var step3="";
var step4="";
var step5="";
var lr="";
var currentOrigin ="";

//START READY BLOCK
$(function(){
  var queryString = window.top.location.search.substring(1);
  var expireIn3Months = 90;
  var expireIn1Year = 365;

    
	/* KEYWORD RULES: Captures the first keyword used in an organic search */
	/* KEYWORDS (k) MAY BE SET ONLY IN THE FOLLOWING WAY PER JESSIE WARNER AND TREVOR HAMMOND:
	1. if cookie 'keywords' exists and has a value, set 'k' to its value
	2. else if 'k' parameter exists in request and has a value, set this 'k' to its value
	3. URL decode this 'k' and set value of cookie 'keywords' to  value of this 'k' */
    k = getCookie('keywords');
    if(k==""){
      var newParameter = getParameter(queryString, 'k');
      newParameter = newParameter != "" ? newParameter : getReferringKeywords();
      if(k==""){k = newParameter != "" ? newParameter : "";}
    }
    k = URLDecode(k);
    setCookie('keywords', k, expireIn3Months);
    //console.log("Keywords = " + k);
	
	/* Current Keyword RULES: */
	currentKeyword = getParameter(queryString, 'k') != "" ? getParameter(queryString, 'k') : "";
	currentKeyword = currentKeyword != "" ? currentKeyword : getReferringKeywords();
	currentKeyword = URLDecode(currentKeyword);
	//console.log("Current Keyword = " + currentKeyword);
	
	
	/* LINK RULES: Captures URL of the first referring site */
	/* LINK (l) MAY BE SET ONLY IN THE FOLLOWING WAY PER JESSIE WARNER AND TREVOR HAMMOND:
	1. if cookie 'link' exists and has a value, set 'l' to its value
	2. else if 'l' parameter exists in request and has a value, set this 'l' to its value
	3. URL decode this 'l' and set value of cookie 'link' to  value of this 'l' */
	l = getCookie('link');
	
	if (currentKeyword == "") {
	  newParameter = getParameter(queryString, 'l');
    if(l==""){l = newParameter != "" ? newParameter : "";}
  	var newLink = getLink();
  	if(l==""){l = newLink != "" ? newLink : "";} 
	}
  l=URLDecode(l);
  if (l.indexOf("attask\.") != -1) { l = ""; }
	setCookie('link', l, expireIn3Months);
	//console.log("Links = " + l);
	
	/* Current Link Rules: */
	currentLink = getParameter(queryString, 'l') != "" ? getParameter(queryString, 'l') : "";
	currentLink = currentLink != "" ? currentLink : getLink();
	currentLink = URLDecode(currentLink);
	if (currentLink.indexOf("attask.") != -1) { currentLink = ""; }
	//console.log("Current Link = " + currentLink);
	
	
	
    /* ORIGIN RULES: Captures the first campaign that touches a prospect */
	/* ORIGIN (o) MAY BE SET ONLY IN THE FOLLOWING WAY PER JESSIE WARNER AND TREVOR HAMMOND:
	1. if cookie 'origin' exists and has a value, set 'o' to its value
	2. else if 'o' parameter exists in request and has a value, set this 'o' to its value
	3. else if 'k' exists and has a value, set this 'o' to string '[BROWSER NAME]_Organic'
	4. else if 'l' exists and has a value, set this 'o' to the string 'Referring_Site'
	5. else set this 'o' to string 'Direct'
	6. URL decode this 'o' and set value of cookie 'origin' to  value of this 'o' */
  o = getCookie('origin');
  //console.log("Origin Cookie = " + URLDecode(o));
  if (o == ""){
    o = getParameter(queryString, 'o') != "" ? getParameter(queryString, 'o') : "";
    if (o == "") {
      o = k!=null && k!=undefined && k!="" ? getSearchEngine() : "";
      if (o == ""){
        o = l != null && l != undefined && l!="" ? "ReferringSite" : "";
      }
    }
  }
  if (o == ""){o = "Direct";}
    o=URLDecode(o);
  //console.log("Origin = " + o);
  setCookie('origin', o, expireIn3Months);

	
	/* CURRENT ORIGIN RULES: Captures the curent campaign touching a prospect */
	/* CURRENT ORIGIN (currentOrigin) MAY BE SET ONLY IN THE FOLLOWING WAY PER JESSIE WARNER AND TREVOR HAMMOND:
	1. if 'o' parameter exists in request and has a value, set 'currentOrigin' to its value
	2. else if 'k' exists and has a value, set 'currentOrigin' to string '[BROWSER NAME]_Organic'
	3. else if 'l' exists and has a value, set 'o' to the string 'Referring_Site'
	4. else set 'currentOrigin' to string 'Direct'
	5. URL decode 'currentOrigin'*/
	currentOrigin = getParameter(queryString, 'o') != "" ? getParameter(queryString, 'o') : "";
	if (currentOrigin == ""){
	  currentOrigin = currentKeyword!=null && currentKeyword!=undefined && currentKeyword!="" ? getSearchEngine() : "";
	  if (currentOrigin == ""){
	    currentOrigin = currentLink != null && currentLink != undefined && currentLink!="" ? "ReferringSite" : "";
	  }
	}
	if (currentOrigin == ""){currentOrigin = "Direct";}
	currentOrigin=URLDecode(currentOrigin);
	//console.log("Current Origin = " + currentOrigin);	
	
	var lastPage = getLink();
	lastPage = lastPage.split(".");
	lastPage = lastPage[1];
	
	/*THIS IS THE LAST RESPONSE-- IT CAN BE SET IN THE FOLLOWING WAYS PER BEN RASMUSSEN & CINDY MOREL: 
     When a lead comes in, last response (lr) will always be set to something. Here is the precedence:
	 1. If origin (o) exists in request, use it
	 2. else if keywords from the referring page exist (k), use them  
	 3. else if an affiliate id (aid) exists, use it to get name of affiliate and use it 
	 4. else if a partner id (r) exists, use it to get name of partner and use it
	 5. else if the referring URL (l) exists, use it
	 6. else use 'Direct'
    */
    lr = getCookie('lr');
    if (lastPage != "attask" && lastPage != "go")
    {
      lr = getParameter(queryString, 'lr') != "" ? getParameter(queryString, 'lr') : "";
      if (lr == ""){
        lr = getParameter(queryString, 'o') != "" ? getParameter(queryString, 'o') : "";
        if (lr == ""){
          if(lastPage != "attask" && lastPage != "go"){lr = currentKeyword!=null && currentKeyword!=undefined && currentKeyword!="" ? getSearchEngine() : "";}
          if (lr == ""){
            if(lastPage != "attask" && lastPage != "go"){lr = currentLink != null && currentLink != undefined && currentLink!="" ? "ReferringSite" : "";}
          }
        }
      }
    }
    
    if (lr == ""){lr = "Direct";}
    lr=URLDecode(lr);
    //console.log("Last Response = " + lr);
    setCookie('lr', lr, expireIn3Months);

    
    
    
	  /* FIFTH CAMPAIGN RULES: Captures the fifth campaign that touches a prospect */
  	/* FIFTH CAMPAIGN (step5) MAY BE SET ONLY IN THE FOLLOWING WAY PER JESSIE WARNER AND TREVOR HAMMOND:
  	1. if cookie 'step5' does not exist or is blank AND cookie 'step4' is set, set it to 'currentOrigin'
  	2. URL decode 'step5' and set value of cookie 'step5' to  value of this 'step5' */
  	
  	step2 = getCookie('step2');
  	step3 = getCookie('step3');
  	step4 = getCookie('step4');
  	step5 = getCookie('step5');
  	
  	if (lastPage != "attask" && lastPage != "go")
  	{
      // step4 = getCookie('step4');
      //       step5 = getCookie('step5');
      step5 = step5 == "" && step4 != "" && currentOrigin != "" ? currentOrigin : step5;
      step5=URLDecode(step5);
      setCookie('step5', step5, expireIn3Months);


      /* FOURTH CAMPAIGN RULES: Captures the third campaign that touches a prospect */
      /* FOURTH CAMPAIGN (step4) MAY BE SET ONLY IN THE FOLLOWING WAY PER JESSIE WARNER AND TREVOR HAMMOND:
      1. if cookie 'step4' does not exist or is blank AND cookie 'step3' is set, set it to 'currentOrigin'
      2. URL decode 'step4' and set value of cookie 'step4' to  value of this 'step4' */
      // step3 = getCookie('step3');
      //  step4 = getCookie('step4');
      step4 = step4 == "" && step3 != "" && currentOrigin != "" ? currentOrigin : step4;
      step4=URLDecode(step4);
      setCookie('step4', step4, expireIn3Months);


      /* THIRD CAMPAIGN RULES: Captures the third campaign that touches a prospect */
      /* THIRD CAMPAIGN (step3) MAY BE SET ONLY IN THE FOLLOWING WAY PER JESSIE WARNER AND TREVOR HAMMOND:
      1. if cookie 'step3' does not exist or is blank AND cookie 'step2' is set, set it to 'currentOrigin'
      2. URL decode 'step3' and set value of cookie 'step3' to  value of this 'step3' */  
      // step2 = getCookie('step2');
      //       step3 = getCookie('step3');
      step3 = step3 == "" && step2 != "" && currentOrigin != "" ? currentOrigin : step3;
      step3=URLDecode(step3);
      setCookie('step3', step3, expireIn3Months);



      /* SECOND CAMPAIGN RULES: Captures the second campaign that touches a prospect */
      /* SECOND CAMPAIGN (step2) MAY BE SET ONLY IN THE FOLLOWING WAY PER JESSIE WARNER AND TREVOR HAMMOND:
      1. if cookie 'step2' does not exist or is blank, set it to 'currentOrigin'
      2. URL decode 'step2' and set value of cookie 'step2' to  value of this 'step2' */
      var step1 = getCookie('origin');
      // step2 = getCookie('step2');
      step2 = step2 == "" && step1 != currentOrigin && currentOrigin != "" ? currentOrigin : step2;
      step2=URLDecode(step2);
      setCookie('step2', step2, expireIn3Months);
  	}
    
    
	
   /*THIS APPENDS THE PROPOGATION VARIABLES TO CLICKED URLS*/	
   var apendedQueryString = "?o="+o+"&lr="+lr+"&step2="+step2+"&step3="+step3+"&step4="+step4+"&step5="+step5+"&k="+k+"&l="+l;
   
   //console.log("Query String =" + apendedQueryString);
   
   $("[href*='go.attask.com']").each(function(index) {
     $(this).attr('href', $(this).attr('href')+apendedQueryString);
   });
   $("[href='http://www.attask.com']").each(function(index) {
     $(this).attr('href', $(this).attr('href')+apendedQueryString);
   });
   $("[href*='/workout']").each(function(index) {
     $(this).attr('href', $(this).attr('href')+apendedQueryString);
   });
   
   
   $("[href*='/forms_test.html']").each(function(index) {
     $(this).attr('href', $(this).attr('href')+apendedQueryString);
   });
   $("[href*='/rules_test.php']").each(function(index) {
     $(this).attr('href', $(this).attr('href')+apendedQueryString);
   });

});
//END READY BLOCK


//START HELPER FUNCTIONS
function URLDecode(encodedValue){
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = encodedValue;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   }else if (ch == "%"){
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			}else{
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		}else{
		   plaintext += ch;
		   i++;
		}
	}
   return plaintext;
};


function getParameter(queryString, parameterName) {
  var returnValue = "";
  var parameterName = parameterName;
   var queryString = queryString;
   if(queryString.length > 0){
    var parsedQueryString = queryString.split("&");
	var currentValue = "";
    var queryLength = parsedQueryString.length;
	for(i=0; i<queryLength; i++){
	  if(queryLength == 1){
	    currentValue = parsedQueryString[i].split('=');
		currentParameter = currentValue[0];
		currentValue = currentValue[1];
		if(currentParameter == parameterName){returnValue = currentValue;}
		break;
	  }else{
	   currentValue=parsedQueryString[i].split("=");
	   currentParameter = currentValue[0];
	   currentValue = currentValue[1];
	  }
	  if(currentParameter == parameterName){returnValue = currentValue;break;}
	} 
  }
  return returnValue;
}



function setCookie(cookieName,cookieValue,nDays) {
  var today = new Date();
  var expire = new Date();
  if (nDays==null || nDays==0) nDays=1;
  expire.setTime(today.getTime() + 3600000*24*nDays);
  document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString() + ";path=/;";
}



function getCookie(cookieName) {
  var returnValue = "";
  var theCookie=""+document.cookie;
  var ind=theCookie.indexOf(cookieName);
  if (ind!=-1 && cookieName!=""){ 
    var ind1=theCookie.indexOf(';',ind);
    if (ind1==-1){
	  ind1=theCookie.length; 
	}
	var currentCookie = unescape(theCookie.substring(ind+cookieName.length+1,ind1));
	if(currentCookie == undefined){returnValue = "";}
	else{returnValue = currentCookie;}
  }
  return returnValue;
}



function getLink() {
  var returnValue = "";	
  var url = document.referrer;
  url = url.split('?');
  url = url[0];
  if(url != null && url != undefined && url != ""){returnValue = url;}
  return returnValue;
}


function getSearchEngine(){
  var returnValue = "OtherSearch_Organic";
  var searchEngineAddressLiteralWWW = new Array("http://www.google.", "http://www.yahoo.", "http://www.bing.", "http://www.baidu.", "http://www.ask.", "http://www.aol.", "http://www.youtube.");
  var searchEngineAddressLiteral = new Array("http://google.", "http://yahoo.", "http://bing.", "http://baidu.", "http://ask.", "http://aol.", "http://youtube.");
  var searchEngineAddress = new Array(".google.", ".yahoo.", ".bing.", ".baidu.", ".ask.", ".aol.", ".youtube.");
  var searchEngineValue = new Array("Google_Organic", "Yahoo_Organic", "Bing_Organic", "Baidu_Organic", "Ask_Organic", "AOL_Organic", "YouTube_Organic");
  var url = document.referrer;
  url = url.split('?');
  url = url[0];
  if(null !== url && undefined !== url && url != ""){
	  for(var i=0; i<searchEngineAddress.length; i++){
	    var searchEngineFound = url.indexOf(searchEngineAddress[i]);
	    var literalSearchEngineFound = url.indexOf(searchEngineAddressLiteral[i]);
	    var literalWWWSearchEngineFound = url.indexOf(searchEngineAddressLiteralWWW[i]);
	    var NEGATIVE = -1;	
  	  if(searchEngineFound != NEGATIVE || literalSearchEngineFound != NEGATIVE || literalWWWSearchEngineFound != NEGATIVE){
  		  returnValue = searchEngineValue[i]; 
  		  break;
  	  }
  	}   
  }
  //console.log("Search Engine = " + returnValue);
  return returnValue;
}


function getReferringKeywords(){
  var returnValue = ""; 
  var searchEngineAddress = new Array(".google.", ".yahoo.", ".msn.", ".aol.", ".altavista.", ".feedster.", ".lycos.", ".ask.", ".baidu.", ".bing.", ".youtube.");
  var keywordQueryParameter = new Array("q", "p", "q", "userQuery", "q", "q", "query", "q", "wd", "q", "search_query", "x");
  var url = document.referrer;
  url = url.split('?');
  var queryString = undefined !== url[1] ? url[1] : ""; 
  url = url[0];
  if(null !== url && undefined !== url && url != "" && queryString != ""){
	for(var i=0; i<searchEngineAddress.length; i++){
	  var searchEngineFound = url.indexOf(searchEngineAddress[i]);
	  var NEGATIVE = -1;	
	  if(searchEngineFound != NEGATIVE){
		var qParam = keywordQueryParameter[i];
		queryString = queryString.split('&');
		if(undefined !== queryString[0] && queryString.length >= 1){
		  for(var j=0; j<queryString.length; j++){
		    var nameValuePair = queryString[j];
		    nameValuePair = nameValuePair.split('=');
		    if(undefined !== nameValuePair[0] && nameValuePair[0] == qParam){returnValue = nameValuePair[1];}
		  }	
		}
		if(returnValue != ""){break;} 
	  }
	}   
  }
  return returnValue; 
}


//END HELPER FUNCTIONS
