/* Get the tracking path out of the pc3LogPath-Metatag */
function getTrackingPath(){
	var trackingPath;
	var metaTags = document.getElementsByTagName('META');
	for(var i=0; i<metaTags.length; i++ ){
		if ( metaTags[i].name != 'pc3LogPath' ) continue;
		trackingPath = metaTags[i].content;
		break;
	}
	if ( !trackingPath ) return '/';
	var pattern = /\/[a-z_-]+(.*)\..*/i;
	var match = pattern.exec(trackingPath);
	if ( !match ) return '/';
	return match[1];
}

/* Get a conntected string with a own specified connector */
function getConnectedString(str,connector){
	var connectedString = '';
	for(var key in str){
		connectedString += (connectedString?connector:'') + key +'='+ encodeURIComponent(str[key]);
	}
	return connectedString;
}

/* Generates a unique ID */
function generateGuid() {
	var	result = '';
	for(var j=0; j<32; j++)	result += Math.floor(Math.random()*16).toString(16);
	return result;
}

/* Generetes debugging output when using &dt=1 GET-parameter */
function debugOutput(objToDebug, strConnector, objTitle) {
	document.write('<div style="overflow: auto; font-family:Verdana; font-size:10px; z-index:100; padding:0px; text-align:left; border: 1px solid red; background-color: #ffffff; margin-bottom:5px;"><ul>');
	document.write('<li><b>' + objTitle + ': ' + getConnectedString(objToDebug, strConnector) + '</b></li><ul>');
	for(var key in objToDebug){
		document.write('<li>' + key + '=' + objToDebug[key]  + '</li>');
	}			
	document.write('</ul></ul></div>');
}

/* Get cookie values */
function getCookieVal (offset) {  
	var endstr = document.cookie.indexOf (";", offset);  
	if (endstr == -1) { endstr = document.cookie.length; }
		return unescape(document.cookie.substring(offset, endstr));
}

/* Get cookies */
function getCookie (name) {  
	var arg = name + "=";  
	var alen = arg.length;  
	var clen = document.cookie.length;  
	var i = 0; 
	while (i < clen) {    
		var j = i + alen;    
		if (document.cookie.substring(i, j) == arg) return getCookieVal (j);    
		i = document.cookie.indexOf(" ", i) + 1;    
		if (i == 0) break;   
	}  
	return null;
}

/* Set cookies */
function setCookie (name, value, expires, path, domain, secure) {
	var expiryDate = new Date();
	expiryDate.setTime(expiryDate.getTime() + (expires * 24 * 60 * 60 * 1000));
	
	document.cookie = name + "=" + escape (value) + //value + 
	((expires == null) ? "" : ("; expires=" + expiryDate.toGMTString())) + 
	((path == null) ? "" : ("; path=" + path)) +  
	((domain == null) ? "" : ("; domain=" + domain)) +    
	((secure == true) ? "; secure" : "");
}

/* Building cookies and tracking pathes */
function trackUser() {
	var pc3Guid				= generateGuid();
	var nowDate 			= new Date();
	var nowTime 			= nowDate.getTime();	
	var URLQueryString 		= (location.href.indexOf('?')>0)?location.href.split('?')[1].toQueryParams():{};
	var localeInformation 	= getCookie('LocaleInformation')?getCookie('LocaleInformation').toQueryParams('|'):{};
	var userInformation 	= getCookie('UserInformation')?getCookie('UserInformation').toQueryParams('|'):{};
	var debugTracking		= (URLQueryString.dt == 1)?1:0;
	// Check if client accetps cookies
	setCookie('swTime', ''+nowTime, null, '/', null, false);
	if (getCookie('swTime') == (''+nowTime)) var hasCookies = true;
	else var hasCookies = false;
	
	// Checks if user has coockies, otherwise talking to origin and getting GET-SessionID
	if(!hasCookies) {
		if (!URLQueryString.NonCookies) {
			window.location.href = pc3NonCookieLink;
		}
	}	
	
	
	// Landing special tracking (sets ori-parameter for tracking)
	var regexp = '^' + pc3Protocol + '://' + pc3Host + '/' + pc3CountryName  + '/((htm|stage|edit|test|debug)/(' + pc3HomeLinkId + '\/|$|\\?)|\\?|$)';
	var pattern = new RegExp(regexp);
	var match = pattern.exec(document.referrer);
	if (match)	URLQueryString.origin = "landing_asia_" + pc3CountryName;
	
	var pc3LocalInformation = {
		'USERPORTALLANGUAGE':		(localeInformation.USERPORTALLANGUAGE?localeInformation.USERPORTALLANGUAGE:''),
		'USERPROMOTIONLANGUAGE':	(localeInformation.USERPROMOTIONLANGUAGE?localeInformation.USERSHOPLANGUAGE:''),
		'JAVACOUNTRYCODE':			(localeInformation.JAVACOUNTRYCODE?localeInformation.JAVACOUNTRYCODE:''),
		'COUNTRYHAWKCODE':			(localeInformation.COUNTRYHAWKCODE?localeInformation.COUNTRYHAWKCODE:''),	
		'USERSHOPLANGUAGE':			(localeInformation.USERSHOPLANGUAGE?localeInformation.USERSHOPLANGUAGE:''),	
		'INITIALSESSION':			(localeInformation.INITIALSESSION?localeInformation.INITIALSESSION:pc3Guid),	
		'USERASIAMSLANGUAGE':		(localeInformation.USERASIAMSLANGUAGE?localeInformation.USERASIAMSLANGUAGE:pc3Language)
	}
	setCookie('LocaleInformation', getConnectedString(pc3LocalInformation, '|'), 1095, '/', 'swarovski.com', null);
	
	var pc3UserInformation = {
		'SESSIONID':			(userInformation.SESSIONID?userInformation.SESSIONID:pc3Guid),	
		'ROLEID':				(userInformation.ROLEID?userInformation.ROLEID:''),
		'LOGINSTATUS':			(userInformation.LOGINSTATUS?userInformation.LOGINSTATUS:''),
		'BASKETITEMS':			(userInformation.BASKETITEMS?userInformation.BASKETITEMS:''),
		'BASKETCURRENCYCODE':	(userInformation.BASKETCURRENCYCODE?userInformation.BASKETCURRENCYCODE:''),
		'BASKETTOTAL':			(userInformation.BASKETTOTAL?userInformation.BASKETTOTAL:''),
		'BUSINESSPARTNERNO':	(userInformation.BUSINESSPARTNERNO?userInformation.BUSINESSPARTNERNO:''),
		'SEARCHSTRING':			(userInformation.SEARCHSTRING?userInformation.SEARCHSTRING:''),
		'BANNER_ID':			(userInformation.BANNER_ID?userInformation.BANNER_ID:(URLQueryString.Banner_ID?URLQueryString.Banner_ID:''))
	}
	setCookie('UserInformation', getConnectedString(pc3UserInformation, '|'), null, '/', 'swarovski.com', null);
		
	var trackingQuery = {
		'pth':	'/Asia Microsite/',
		'hs':	pc3Host,
		'pt':	pc3Protocol,
		'sid':	(hasCookies?pc3UserInformation.SESSIONID:URLQueryString.SWAROVSKI),
		'is':	(hasCookies?pc3LocalInformation.INITIALSESSION:URLQueryString.SWAROVSKI),
		'ref':	document.referrer,
		'lg':	pc3Language,
		'ck':	(hasCookies?'1':'0'),
		'js':	1,
		'fl':	((swfobject.getFlashPlayerVersion().major >= 8)?'1':'0'),
		'tm':	nowTime,
		'ori':	(URLQueryString.origin?URLQueryString.origin:''),
		'bid':	(pc3UserInformation.BANNER_ID?pc3UserInformation.BANNER_ID:''),
		'chc':	(localeInformation.COUNTRYHAWKCODE?pc3LocalInformation.COUNTRYHAWKCODE:''),
		'cor':	(localeInformation.JAVACOUNTRYCODE?pc3LocalInformation.JAVACOUNTRYCODE:''),
		'hm':	(URLQueryString.hm?URLQueryString.hm:'')		
	}

	// Orion Tracking
	var orionURL = pc3OrionLink + '?'+ getConnectedString(trackingQuery, '&');
	document.write('<img src="' + orionURL + '" height="0" width="0">');
	if(debugTracking) debugOutput(pc3LocalInformation, '|', 'localeInformation');
	if(debugTracking) debugOutput(pc3UserInformation, '|', 'userInformation');
	if(debugTracking) debugOutput(trackingQuery, '&', 'orionURL');

	// Sirius Tracking
	trackingQuery.pth = getTrackingPath();
	var siriusURL = pc3SiriusLink + '?'+ getConnectedString(trackingQuery, '&');
	document.write('<img src="' + siriusURL + '" height="0" width="0">');
	if(debugTracking) debugOutput(trackingQuery, '&','siriusURL');
	
}