
//START READY BLOCK
//var $ = jQuery.noConflict();
$(function(){

	var queryString = window.top.location.search.substring(1);
	var expireIn3Months = 90;
    var expireIn1Year = 365;
	
	
	var aid = getCookie('aid');
	newParameter = getParameter(queryString, 'aid');
	if(aid==""){aid = newParameter != "" ? newParameter : "";}
    aid = URLDecode(aid);
	setCookie('aid', aid, expireIn3Months);
	$("#affilate_ID__c").attr("value",aid);
	
	
    var 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);

	
	var r = getCookie('partner');
	var newParameter = getParameter(queryString, 'r');
	if(r==""){r = newParameter != "" ? newParameter : "";}
    r=URLDecode(r);
	setCookie('partner', r, expireIn3Months);
	$("#Freeside_Agent__c").attr("value",r);
	
	
	var l = getCookie('link');
    newParameter = getParameter(queryString, 'l');
	if(l==""){l = newParameter != "" ? newParameter : "";}
	var newLink = getLink();
	if(l==""){l = newLink != "" ? newLink : "";}
    l=URLDecode(l);
	setCookie('link', l, expireIn3Months);
	$("#Referring_Page_URL__c").attr("value",l);
	
	
	var src = getCookie('source');
	var newSrc = getLink();
	if(src==""){src = newSrc != "" ? newSrc : "";}
    src=URLDecode(src);
	setCookie('source', src, expireIn3Months);
	$("#leadsource").attr("value",src);

	

	
    /*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 = getParameter(queryString, 'lr') != "" ? getParameter(queryString, 'lr') : "";
          if (lr == ""){
          lr = getParameter(queryString, 'o') != "" ? getParameter(queryString, 'o') : "";
	  if (lr == ""){
	    lr = k!=null && k!=undefined && k!="" ? "keyword:"+k : "";
	    if (lr == ""){
		  lr = aid!="" ? getAffiliate(aid) : "";
		  if(lr != ""){lr = "affiliate:" + lr;}
		  if (lr == ""){
		    lr = r != "" ? getPartner(r) : "";
		    if(lr != ""){lr = "partner:" + lr;}
		    if (lr == ""){
	          lr = l != null && l != undefined && l!="" ? "link:"+l : "";
			}
		  }
		}
	  }
        }  
	if (lr == ""){lr = "Direct";}
    lr=URLDecode(lr);
    $("#Last_Response__c").attr("value",lr);	
	
	
	
    /*THIS IS THE ORIGIN-- IT CAN BE SET IN THE FOLLOWING WAYS PER SCOTT JOHNSON: 
     When a lead comes in, origin (o) will always be set to something. Here is the precedence:
	 1. if origin cookie (o) exists, use it
	 2. else if origin (o) exists in request, use it
	 3. else if keywords from the referring page exist (k), use them  
	 4. else if an affiliate id (aid) exists, use it to get name of affiliate and use it 
	 5. else if a partner id (r) exists, use it to get name of partner and use it
	 6. else if the referring URL (l) exists, use it
	 7. else use 'Direct'
    */
	var o = getCookie('origin');
	if(o == ""){
	  o = getParameter(queryString, 'o') != "" ? getParameter(queryString, 'o') : "";
	  if (o == ""){
	    o = k!=null && k!=undefined && k!="" ? "keyword:"+k : "";
	    if (o == ""){
		  o = aid!="" ? getAffiliate(aid) : "";
		  if(o != ""){o = "affiliate:" + o;}
		  if (o == ""){
		    o = r != "" ? getPartner(r) : "";
		    if(o != ""){o = "partner:" + o;}
		    if (o == ""){
	          o = l != null && l != undefined && l!="" ? "link:"+l : "";
			}
		  }
		}
	  }
	}
	if (o == ""){o = "Direct";}
    o=URLDecode(o);
    $("#Exposure__c").attr("value",o);
	setCookie('origin', o, expireIn3Months);





/*THIS KEEPS 'lr' SET PROPERLY -- IT CAN BE SET IN THE FOLLOWING WAYS PER TREVOR HAMMOND: 
  Get lr from request whenever it comes in 
*/
  lr = getParameter(queryString, 'lr') != "" ? getParameter(queryString, 'lr') : "";
  k = k != "" ? k : "keyword:UNDEFINED";
  		
		
			
/*THIS APPENDS REQUEST PARAMETERS TO URLS CONTAINING 'offers.attask.com' OR 'http://www.attask.com': 
*/		
  var apendedQueryString = "?o="+o+"&lr="+lr+"&k="+k+"&aid="+aid+"&l="+l+"&r="+r+"&src="+src;
  $("[href*='offers.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);
  });



});
//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();
}



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 getReferringKeywords(){
  var returnValue = ""; 
  var searchEngine = new Array("google.", "yahoo.", "msn.", "aol.", "altavista.", "feedster.", "lycos.", "alltheweb.");
  var queryParameter = new Array("q", "p", "q", "userQuery", "q", "q", "query", "q");
  var queryString = window.top.location.search.substring(1);
  for(var i=0; i<queryParameter.length; i++){
  var parameterValue = getParameter(queryString, queryParameter[i]);
  if(parameterValue != null && parameterValue != undefined && parameterValue != ""){
  returnValue = parameterValue;
  }
  }
  return returnValue; 
}




function getPartner(partnerId){
  var returnValue = "";
  if(partnerId != null && partnerId != undefined && partnerId != ""){
    var partnerIdArray = new Array(122, 116, 41, 115, 107, 126, 127, 117, 110, 92, 1003, 17, 73, 105, 123, 20, 109, 108, 111, 118, 75, 120, 60, 91, 76, 114, 40, 115, 64, 42, 49, 125, 113, 106, 72, 85, 97, 74, 47, 121, 18, 104, 34, 84, 124, 119, 112, 116);
	var companyNameArray = new Array("Keystone Computer Solution",  " SaaSi Solutions",  "BDM Consulting",  "Lumina",  "Morphix",  "Ron deVries Business Development",  "TAREA Management Ltd.",  "Zig Newton SRL",  "ResultsPositive",  "XLNT Optimization",  "Promastar Ltd. Sweden",  "Alliance Technology Partners",  "Bytes of Knowledge",  "Portflio Performance Solutions",  "NPE, LLC",  "DAT Computer Concepts",  "ARTEC",  "ACS-Associates",  "UMG",  "Inevat",  "Project Partners, LLC",  "L-Cube Technologies",  "WORKSMART",  "SysGulf International",  "AdaQuest",  "JM Mahon",  "Sagesse",  "Hospitality Financial Services, LLC",  "Twin Lights Group",  "Mr Systeme",  "Sunbridge Solutions",  "Nwankwo",  "Odese",  "TrueFit Solutions",  "HumanIT",  "Rekar",  "ALDION",  "Adaptive Solutions",  "Revolution IT",  "Nice Enterprises",  "Amtech Technologies",  "ComTec Information Systems",  "Proside",  "CM-Logic",  "The PMO Company",  "Weidenhammer Systems Corporation",  "Xprtez",  "Protegic Pty Ltd");
	for(var i=0; i<partnerIdArray.length; i++){
	  if(partnerId == partnerIdArray[i]){returnValue = companyNameArray[i];}
	}
  }
  return returnValue;
}



function getAffiliate(affiliateId){
  var returnValue = "";
  if(affiliateId != null && affiliateId != undefined && affiliateId != ""){
    var affiliateIdArray = new Array(5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 25, 26, 30, 32, 33, 34, 39, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 52, 53, 54, 55, 56, 57, 58, 59, 62, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 94, 95, 96, 97, 99, 100, 101, 103, 104, 105, 106, 107, 108, 109, 110, 112, 113, 115, 116, 117);
	var companyNameArray = new Array("SmartStaff","eChem, Inc. Delaware.","Line57","Frantisek Kormanak","TopTenREVIEWS","AgentD LLC","Nate Bowler","Sadi","Microcost ICT Sourcing","Technology Solutions for Business, LLC","Pramodh","SalesCapture","Vivek Pinto","CIO Partners, Inc.","CoreTech Web Solutions","Ron Rosen","Contact Solutions of FL","Terex Solutions, Inc.","Family Business Experts","Neat Solutions Limited","LaunchPoint","Q90 Corporation","Mincar Consulting","Abraham Moyal","Bryan Black","Nevada Computer and Data Logistics","Harrison Project Services Inc","Poe, Inc.","Adam Clark","www.sundancedomains.com","PrjctMngr.com","JNT Enterprises LLC","WHY International","Technical Edge, Inc.","Jacqueline Miao","Lifepurposes Consulting, LLC","Business Consulting Services","Carla Romaine","pmStudent","zksoft","Intrawork","FeedTheVillage.com","CollectiveSoft","QualityTalk","ICONICS MEX.","Christine Rotonda","Training International","ResultsPositive","JP Hill","naresh","SolutionInYPocket","Webserver Design Ltd","Analytic Partners, Inc.","Trevor's Ski Shop","BiServ Inc.","Tecc Savvy Ltd","TheSolutionsConsultant.com","Ike Nwankwo","M2A multimedia inc.","Coaching From Spirit Institute","fobos auto ltd","Testco","Ambit Reach, LLC","Andrei Sharutin","DIGITIZER Srl","Common Vision LLC","SimpleKloud","Alta Vista Consulting","pmtoolbox","Power Station, LLC","Lei Yunjun","RedWasp 21, LLC","Alnool International","Terry Deane","Scribewell Ltd","Henning Meyer","Qualifex Ltd","MyBuyOrTry.com","Social Mallard LLC","HUMANsoft Kft","Appdirectory.com","Tony Galliano","Aaron MacDaniel","Dennis Barker","Tyson Then","MacDocs","ACG Ukraine","LEI Consulting Engineers and Surveyors, Inc.","Armaghan Rehman","The Mines Group, Inc.","Aspirez Inc","Chris Quiroz");
	for(var i=0; i<affiliateIdArray.length; i++){
	  if(affiliateId == affiliateIdArray[i]){returnValue = companyNameArray[i];}
	}
  }
  return returnValue;
}


//END HELPER FUNCTIONS