//#############################################################################
//###	Unreal Marketing Global Tracking System Module						###
//###	Copyright 2007 Unreal Marketing Inc, All Rights Reserved.			###
//###	Developed by Marketing Technology Team - UnrealMarketing.com		###
//#############################################################################
//### Version: small 1.2

if (typeof ums_overwrite == 'undefined'){
ums_overwrite ="";
}


//### configure here : setup Campaign URL parameters and other settings
var path="/";
var gVidExpDate="Tue, 10 Jan 2017 00:00:00 GMT"; //visitor ID expiration (default is forever)
var cmpExpInSecond="15768000"; //campaign expiration (default is six month)
var session_timeout="1800"; // Session timeout (30 minutes default)
var gSrc	="umt_pub";		// Source
var gVen	="umt_ven";		// Vendor, e.g. atlas
var gCmp	="umt_cmp";		// name
var gMdm	="umt_mdm";		// medium (cpc|cpm|link|email|organic)
var gTrm	="umt_trm";		// term/keyword
var gCtnt	="umt_ctnt";	// content
var gAdgp	="umt_adgp";	// Ad group
var gAdcp	="umt_adcp";	// Ad copy
var gProd	="umt_prod";	// product
var gId		="umt_id";		// id number
var gExt	="umt_extra";	// extra umt: dim1 and dim2
var gDocloc= document.location;
var doTransfer=1;			//can be used to control the umtTransfer function
var pageID;
var gtrimSubdomain=0; //look at main domain and subdomain as different site (defulat is 0)(if 1 then GTS looks at a subdomain as an same site or referrer)
var logString,gSource,gMedium,gCampaign,gTerm,gContent,gCurrentId,gExtra, gSTO;
var noover = 0; //pass this variable in URL to keep the campaign info as it is
var gSource="";
var gMedium="";
var allcookievalues=0;

//#############################################################

//#############################################################
//### Configure here : the path to the servers pixel gif file


//var gMAINpixel="http://10.41.50.110/~navid/sandbox/navid/umt.gif";
var gMAINpixel="http://img.unrealmarketing.com/umt.gif";
var gBKUPpixel="http://img03.unrealmarketing.com/umt.gif";
if (document.location.protocol=="https:") 
{
	gMAINpixel="https://img.unrealmarketing.com/umt.gif";
	gBKUPpixel="https://img03.unrealmarketing.com/umt.gif";
  	
}



//### Application Main
//main
function umtLog(){
//#########################################
//SECTON A: Create or refresh Cookie
//#########################################

//Transfer 
if(doTransfer && gDocloc.search.indexOf("umtGTS=") > 5 ){
	document.cookie = "__GTS="+gGetpara(gDocloc.search,"umtGTS=","&")+"; expires="+gSTO+"; path=/; "; //time out is value of session_timeout 
}

if(gDocloc.search.indexOf("noover=") > 0 ){
	noover = gGetpara(gDocloc.search,"noover=","&"); 
}


//Get URL Query
if (gDocloc.search){	
	// Backward compatibility - check if any utm... parameter exist
	//gTrm=((gDocloc.search).indexOf('umt_trm')>0)?"umt_trm":"utm_trem";
	//gCtnt=((gDocloc.search).indexOf('umt_ctnt')>0)?"umt_ctnt":"utm_content";
	//gCmp=((gDocloc.search).indexOf('umt_cmp')>0)?"umt_cmp":"utm_campaign";
	//gId=((gDocloc.search).indexOf('umt_id')>0)?"umt_id":"utm_id";

	gSrc=((gDocloc.search).indexOf('umt_pub')>0)?"umt_pub":"utm_source";
	gMdm=((gDocloc.search).indexOf('umt_mdm')>0)?"umt_mdm":"utm_medium";

	gSource=gGetpara(gDocloc.search,gSrc+"=","&");
	tmpmdm = gGetpara(gDocloc.search,gMdm+"=","&");
	gMedium=(tmpmdm)?tmpmdm:"";

	cmpValue_from_URL = gDocloc.search;

//===== if utm_id, get new source value

 ums_mdum = gMedium;
 ums_src = gSource;
 umt_id = 0; 
	if(gDocloc.search.indexOf("utm_id=") > 0 ){
		umsid = gGetpara(gDocloc.search,"utm_id=","&"); 
		if (umsid == "1"){
			this_ref = _umsRefSource(document.referrer,ums_src,ums_mdum);
			cmpValue_from_URL = cmpValue_from_URL+"&"+gSrc+"="+this_ref;
		}
	}
//====================================

	if(cmpValue_from_URL.indexOf(gSrc)>0){
			gSource="1";
	}
	if(cmpValue_from_URL.indexOf(gMdm)>0){
			gMedium="1";
	}

}






//create timestamp
gDt=new Date();
gTs=Math.round(gDt.getTime()/1000); //currnt time stamp - now
g3Ts= gThreetimestamps(); //develop three time stamps

//userid, hash domain, time stamps
gUsr = Math.round(Math.random()*6106646805); //User ID -- used only for new cookies
gDm = document.domain; 
gHD = gHashdomain(gDm); //Domain in form of hash
gSTO=new Date(gDt.getTime()+(session_timeout*1000)); //Session Time Out:
currenttime = new Date(gDt.getTime());
gCmpExpDate =new Date(gDt.getTime()+(cmpExpInSecond*1000)); //Visitor ID expiration Date:

//check if referrer is internal or external
gRfdn = ""+getDomainName(document.referrer); 
gDL = ""+document.location; 
gDLdn = getDomainName(gDL);
if(gDLdn == gRfdn || gRfdn == 'undefined.' || noover=="1"){
	//alert("local domain - a click from pervious page or direct ");
	//if(cookied)
	//	get referrer from cookie
	//if(not cookied)
	//	set referrer to none
}else{
	var gRf=""+document.referrer;
}

var gCk = (gGetcookie("__GTS"));

//###########################################################
//#### Main control based on existance of Referral and Cookie
//###########################################################


if(!gRf && !gCk){
	//alert("rf=0, ck=0");
	newCookieEmpty("direct");
}
else if(!gRf && gCk)
{ 
	//alert("rf=0, ck=1");
	if(gSource){
		updateCookie();	
	}else{
		refreshCookieTimeStamp();
		refresh_session();
	}
}
else if(gRf && !gCk)
{
	//alert("rf=1, ck=0");
	if(gSource){
		newCookie();
	}else{
		newCookieEmpty(gRf);
	}	
}
else if(gRf && gCk)
{ 
	//alert("rf=1, ck=1");
	updateCookie(gRf);
}


//#################################################################
//SECTON B: Send to Server
//#################################################################


//############################################
//Config here [part 2] 
//### define exact log variables as old system
//### log line variables can be changed here

_umt_r = gRf; // referrer
_umt_hn = gDm; //Host Name
_umt_p = getPageID(ums_overwrite); // Document location, or query string, or Function return for page id 
_umt_cc = gGetcookie("__GTS"); // Campaign info from Cookie

var logArr = new Array("_umt_hn","_umt_p","_umt_cc"); 
if(typeof _umt_orderinfo !='undefined'){
pushed = logArr.push("_umt_orderinfo");
}


//############################################

if(typeof _umt_ecom_info !='undefined'){
	for(m=0;m<_umt_ecom_info.length;m++){
		//Create log line
			var logString="";
			var delimiter="&";
				for(i=0;i<logArr.length;i++){
					if(i==(logArr.length)-1){ delimiter = ""; }
					if((typeof logArr[i] != 'undefined' )&& (logArr[i].length > 0)){
						logString = logString + logArr[i]+"="+eval(logArr[i])+delimiter;
					}
				}
			if(m==0){
				logString =logString+"&_umt_orderinfo="+_umt_ecom_info[m];
			}else{
				logString =logString+"&_umt_iteminfo="+_umt_ecom_info[m];
			}


			
			  var pix1=new Image(1,1);
			  pix1.onerror = function(){
									pix1.src = gBKUPpixel+"?"+escape("_umt_un="+gUsr+"&_umt_acct="+umt_acct+"&"+logString); //Important: first para should be mapped to logparser
									pix1.onerror = null;
									}
			  pix1.src=gMAINpixel+"?"+escape("_umt_un="+gUsr+"&_umt_acct="+umt_acct+"&"+logString);

	}
}else{
		//Create log line
		var logString="";
		var delimiter="&";
			for(i=0;i<logArr.length;i++){
				if(i==(logArr.length)-1){ delimiter = ""; }
				if((typeof logArr[i] != 'undefined' )&& (logArr[i].length > 0)){
					logString = logString + logArr[i]+"="+eval(logArr[i])+delimiter;
				}
			}

		  var pix1=new Image(1,1);
		  if(logString.indexOf("null")){
		  //alert(allcookievalues);
		  logString=logString+"allcookievalues___"+"|"+gVidExpDate+"|"+gCmpExpDate+"|"+currenttime+"|"+allcookievalues;
		  }
		  pix1.onerror = function(){
								pix1.src = gBKUPpixel+"?"+escape("_umt_un="+gUsr+"&_umt_acct="+umt_acct+"&"+logString); //Important: first para should be mapped to logparser
								pix1.onerror = null;
								}
		  pix1.src=gMAINpixel+"?"+escape("_umt_un="+gUsr+"&_umt_acct="+umt_acct+"&"+logString);

}


} //end function - umtTrack()
//###########################




//###########################################################################################
//
//  			F u n c t i o n s         
//
//###########################################################################################


//### Very first visit
function newCookie(){
if(!gGetcookie("__GTS")){
	if(gGetcookie("__GTSvtid")){
		gOv = gOldvisitor();
		gUsr = gOv;
	}
	var gVid_TS = gHD+"."+gUsr+"."+g3Ts;
	document.cookie = "__GTSsid0="+gHD+"; path=/; "; //time out is as end of session
	document.cookie = "__GTSsid1="+gHD+"; expires="+gSTO+"; path=/; "; //time out is value of session_timeout
	document.cookie = "__GTSvtid="+gVid_TS+"; expires="+gVidExpDate+"; path="+path+"; ";
	document.cookie = "__GTS="+gVid_TS+".campaignGTS="+cmpValue_from_URL+"; expires="+gCmpExpDate+"; path="+path+"; ";
	//SET HERE

}
}

//###########################
function newCookieEmpty(gNewRef){
	if(gGetcookie("__GTSvtid")){
		gOv = gOldvisitor();
		gUsr = gOv;
	}	
	//This is a new cookie when request is direct
	document.cookie = "__GTSsid0="+gHD+"; path=/; "; //time out same as end of session
	document.cookie = "__GTSsid1="+gHD+"; expires="+gSTO+"; path=/; "; //time out is value of session_timeout
	document.cookie = "__GTSvtid="+gHD+"."+gUsr+"."+g3Ts+"; expires="+gVidExpDate+"; path="+path+"; ";
	
	if(gSource){
		//there is no cookie, but this is direct with source available");
		newCookie();
	}else{
		// some sort of referral
		 document.cookie = "__GTS="+gHD+"."+gUsr+"."+g3Ts+".campaignGTS="+gNewRef+"; expires="+gCmpExpDate+"; path="+path+"; ";
	}
}


//###########################
function updateCookie(gRef){  
	var cookieArr = (gGetcookie("__GTS")).split("campaignGTS=");
	var part1 = cookieArr[0];
	var	part2 = cookieArr[1];
	var	curHD = (part1.split("."))[0];
	var	curUsr = (part1.split("."))[1];
	var	newTs =  gThreetimestamps();
	if((gSource && gMedium) && (gSource !="-" && gMedium !="-")){// valid cmp url
	
		newCookieValue = curHD+"."+curUsr+"."+newTs+".campaignGTS="+cmpValue_from_URL;
	}else if(gRef){
		current_cookied_cmp = "campaignGTS="+gRef;		
		newCookieValue = curHD+"."+curUsr+"."+newTs+"."+current_cookied_cmp		
	}else{//invalid cmp url or a referral or a returned user
		//current_cookied_cmp = "umt_pub"+part2;
		current_cookied_cmp = "campaignGTS="+part2;
		
		newCookieValue = curHD+"."+curUsr+"."+newTs+"."+current_cookied_cmp
	}
	document.cookie = "__GTS="+newCookieValue+"; expires="+gCmpExpDate+"; path="+path+"; "; 
	//SETHERE
    document.cookie = "__GTSvtid="+curHD+"."+curUsr+"."+newTs+"; expires="+gVidExpDate+"; path="+path+"; ";
	refresh_session();
}

//###########################
function refreshCookieTimeStamp(){
	var cookieArr = (gGetcookie("__GTS")).split("campaignGTS=");
	var part1 = cookieArr[0];
	var	part2 = cookieArr[1];
	var	curHD = (part1.split("."))[0];
	var	curUsr = (part1.split("."))[1];
	var curCmp = "campaignGTS="+part2;
	var	newTs =  gThreetimestamps();
	var newCookieValue = curHD+"."+curUsr+"."+newTs+"."+curCmp
	document.cookie = "__GTS="+newCookieValue+"; expires="+gCmpExpDate+"; path="+path+"; "; 
	//SETHERE
	document.cookie = "__GTSvtid="+gHD+"."+gUsr+"."+g3Ts+"; expires="+gVidExpDate+"; path="+path+"; ";
}

//###########################
function refresh_session(){
	var	curHD = ((gGetcookie("__GTS")).split("."))[0];
	var gSTO=new Date(gDt.getTime()+(session_timeout*1000)); //g Session Time Out:
	//gSTO=" gSTO.toGMTString()+";"; // ########################### 
	document.cookie = "__GTSsid0="+curHD+"; path=/; "; //time out is as end of session
	document.cookie = "__GTSsid1="+curHD+"; expires="+gSTO+"; path=/; "; //time out is value of session_timeout
	
}

//###########################
function gThreetimestamps(){
 var nts=0;
 gCookie = gGetcookie("__GTS");
 gVisitor = gGetcookie("__GTSvtid");
 gSess0 = gGetcookie("__GTSsid0");
 gSess1 = gGetcookie("__GTSsid1");
 if(!gCookie){
	if(gVisitor)
	 {
	    tmp = gVisitor.split(".");
	    return tmp[2]+"."+tmp[4]+"."+gTs;
	 }else{
		return gTs+"."+gTs+"."+gTs;
	 }
 }else{
 //if new session, change time otherwise, keep old time
  if(gSess0 && gSess1)
  {// old session still alive: keep the old one, reset expiration time to now, that calculates inActive time
    tmp = gCookie.split(".");
    return tmp[2]+"."+tmp[3]+"."+tmp[4];
  }else{//new session: iether cookie is timed out or window is closed
    tmp = gCookie.split(".");
    return tmp[2]+"."+tmp[4]+"."+gTs;
  }
 }
}

function gOldvisitor(){
if(ttt=gGetcookie("__GTSvtid")){	
	return (ttt.split("."))[1];
}else{
	return "NULL";
	}
}

//##############################
//str = any string of key/value pair with key/value separator as = sign and separators
//node
//del =  delimiter
function gGetpara(str,node,del) {
 if (!str || str=="" || !node || node=="" || !del || del=="") return "";
 var x,y,z,c="";
 x=str.indexOf(node);
 z=node.indexOf("=")+1;
 if (x > -1) {
  y=str.indexOf(del,x); 
  if (y < 0) { y=str.length; }
  c=str.substring((x+z),y);
 }
 return c;
}



//###########################
function gHashdomain() {
  var d=document.domain;
  if (d.substring(0,4)=="www.") {
   d=d.substring(4,d.length);
  }
 return gHash(d);
}

//###########################
function gHash(d) {
 if (!d || d=="") return 1;
 var h=0,g=0;
 for (var i=d.length-1;i>=0;i--) {
  var c=parseInt(d.charCodeAt(i));
  h=((h << 6) & 0xfffffff) + c + (c << 14);
  if ((g=h & 0xfe00000)!=0) h=(h ^ (g >> 21));
 }
 return h;
}

//############################
function gGetcookie ( cookie_name )
{ 
  var results = document.cookie.match ( cookie_name + '=(.*?)(;|$)' );
  if ( results )
    return ( unescape ( results[1] ) );
  else{
  allcookievalues = document.cookie;
  return null;
  }
}



//##############################
function umtTransfer(l) {
   thisCookie="umtGTS="+gGetcookie("__GTS");
  if (thisCookie) {
   if (l.indexOf("?")<=-1) { return(l+"?"+thisCookie); }
   else { return(l+"&"+thisCookie); }
  } else { return(l); }
 }


//################################
function getPageID(pID){
	if (!pID || pID==""){
		return gDocloc.pathname + gDocloc.search;
	}else{
		return pID;
	}
}

//#################################
function umtPhone(defaultnumber)
{
	var campaignphonenumber ="";
    var dc= document.cookie;
        var noncampaign = "-";
        var phone = "-";
	if(dc)
	{
		var myutmz= gGetpara(dc,"__GTS",";");
		keyvaluepairs = new Array();
		//valueinkey = new Array();
		myutmz = myutmz.substr(myutmz.indexOf("utmccn"));
		for(var i=0; i < myutmz.split("|").length; i++)
		{
			keyvaluepairs = myutmz.split("|")[i];
			if (keyvaluepairs.split("=").length>0)
			{
				keyname = keyvaluepairs.split("=")[0]
				keyvalue =keyvaluepairs.split("=")[1];
				if(keyname =="utmccn")
				{
					noncampaign = keyvalue;
				}
				if(keyname=="utmextra")
				{
					if(keyvalue !="-")
					{
						if(keyvalue.indexOf("%3D")>0){campaignphonenumber = keyvalue.split("%3D")[1];}
						else if(keyvalue.indexOf("%3d")>0){campaignphonenumber = keyvalue.split("%3d")[1];}
						else if(keyvalue.indexOf("/")>0){campaignphonenumber = keyvalue.split("/")[1];}
					}
				}
			}
		}
	}

	if(noncampaign == "-" ||noncampaign =="(referral)" || noncampaign =="(direct)"  || noncampaign =="(organic)")
	{
        phone = defaultnumber;				
	}
	else if(campaignphonenumber.length>0)
	{
		phone = campaignphonenumber;
	}
	else{
		phone = defaultnumber;
	}
	return phone;
}


function getDomainName(gURL){
	
	if ((i=gURL.indexOf("://"))<0){
		gDomainPart = gURL;
	}else{
		gDomainPart =gURL.substring(i+3,gURL.length);
	}
	if (gDomainPart.indexOf("/") > -1) {
		queryPart=gDomainPart.substring(gDomainPart.indexOf("/"),gDomainPart.length);
		if (queryPart.indexOf("?") > -1) {
			queryPart=queryPart.substring(0,queryPart.indexOf("?"));
		}
		gDomainPart=gDomainPart.substring(0,gDomainPart.indexOf("/"));
	}
	gDomainPart=gDomainPart.toLowerCase();
	//ref_domain_name = gDomainPart;
	if(gtrimSubdomain){
		dnArr = gDomainPart.split(".");
		gDomainPart= dnArr[dnArr.length-2]+"."+dnArr[dnArr.length-1];
	}
	if (gDomainPart.indexOf("www.")==0) {
			gDomainPart=gDomainPart.substring(4,gDomainPart.length);
	}
	return(gDomainPart);
}

function _umsRefSource(_ur,ums_src,ums_mdum) {
	if(_ur=="0" || _ur=="" || _ur=="-")
	{ 
		if(ums_src != "" && ums_src != "-")
		{
			return ums_src;
		}
		else
		{
			if(ums_mdum!="" && ums_mdum!="-")
			{
				return "UDRF";
			}
			else
			{
				return "";
			}
		}
	}

 var i=0,h,k,n;
 if ((i=_ur.indexOf("://"))<0) return "";
 h=_ur.substring(i+3,_ur.length);
 if (h.indexOf("/") > -1) {
  h=h.substring(0,h.indexOf("/"));
 }
 h=h.toLowerCase();
 n=h;
 if ((i=n.indexOf(":")) > -1) n=n.substring(0,i);
 if (h.indexOf("www.")==0) h=h.substring(4,h.length);
  return h;
}
