/**
 * 
 */
function PageTrackMessage() {
	var _self = this;
	this._sessionCookieName = 'pageTrackSession';
	
	// Properties to track
	this.uuid = null;
	this.client_ip = null;
	this.url = null;
	this.page_type = null;
	this.session_id = null;
	this.referrer = null;
	this.tour_id = null;
	this.campaign_id = null;
	this.affiliate_id = null;
	this.site_id = null;
	this.custom1 = null;
	this.custom2 = null;
	this.custom3 = null;
	this.custom4 = null;
	this.custom5 = null;
	
	
	this._getSession = function() {
		var sessionCookie = readCookie(_self._sessionCookieName);
		if(!sessionCookie) {
			// Create session
			var sessionCookie = guid();
			createCookie(
					_self._sessionCookieName
					, sessionCookie
					, null
			);
		}
		_self.session_id = sessionCookie;
	}
	
	this._getUrl = function() {
		var url = window.location.toString();
		url.match(/\?(.+)$/);
		var params = RegExp.$1;
		var params = params.split("&");
		var queryStringList = {};
		for(var i=0;i<params.length;i++) {
			var tmp = params[i].split("=");
			queryStringList[tmp[0]] = unescape(tmp[1]);
		}
		
		_self.url = url;
	}
	
	this._getReferrer = function() {
		_self.referrer = document.referrer;
	}
	
	// Load global variables
	this._getPageType = function() {
		_self.page_type = this._checkGlobalAndCookie('_pagetrack_page_type')
	}
	
	this._getSiteId = function() {
		_self.site_id = this._checkGlobalAndCookie('_pagetrack_site');
	}
	
	this._getAffiliateId = function() {
		_self.affiliate_id = this._checkGlobalAndCookie('_pagetrack_affiliate');
	}
	
	this._getCampaignId = function() {
		_self.campaign_id = this._checkGlobalAndCookie('_pagetrack_campaign');
	}
	
	this._getTourId = function() {
		_self.tour_id = this._checkGlobalAndCookie('_pagetrack_tour');
	}
	
	this._getCustom1 = function() {
		_self.custom1 = this._checkGlobalAndCookie('_pagetrack_custom1');
	}
	
	this._getCustom2 = function() {
		_self.custom2 = this._checkGlobalAndCookie('_pagetrack_custom2');
	}
	
	this._getCustom3 = function() {
		_self.custom3 = this._checkGlobalAndCookie('_pagetrack_custom3');
	}
	
	this._getCustom4 = function() {
		_self.custom4 = this._checkGlobalAndCookie('_pagetrack_custom4');
	}
	
	this._getCustom5 = function() {
		_self.custom5 = this._checkGlobalAndCookie('_pagetrack_custom5');
	}
	
	/**
	 * Searches for variable in the global variables scope and if found saves
	 * that varible to cookie for the session and returns the found value.
	 * 
	 * If the variable is not found in the global variable scope the cookie
	 * scope is searched and the value is returned if found.
	 * 
	 * If the variable is neither found in the global or cookie scope then
	 * null is returned. 
	 */
	this._checkGlobalAndCookie = function(variableName) {
		var variableValue = '';
		if(typeof(window[variableName]) != "undefined" && window[variableName]!=null) {
			variableValue = window[variableName];
		} else if(typeof(_getQueryParam(variableName)) != "undefined" && _getQueryParam(variableName)!=null) {
			variableValue = _getQueryParam(variableName);
		} else if(typeof(readCookie(variableName)) != "undefined" && readCookie(variableName)!=null) {
			variableValue = readCookie(variableName);
		} else {
			variableValue =  '';
		}
		if(variableValue=='null' || variableValue==null) {
			variableValue='';
		} else {
			createCookie(variableName, variableValue, null);
		}
		return variableValue;
	} 
	
	this._build = function() {
		_self._getSession();
		_self._getUrl();
		_self._getPageType();
		_self._getReferrer();
		_self._getCampaignId();
		_self._getTourId();
		_self._getAffiliateId();
		_self._getSiteId();
		_self._getCustom1();
		_self._getCustom2();
		_self._getCustom3();
		_self._getCustom4();
		_self._getCustom5();
	}
	
	this.getNvpArgs = function() {
		var params = { };
		for(var i in this) {
			if(typeof this[i] != 'function' && i.substring(0,1)!='_') {
				params[i] = this[i];
			}
		}
		return jQuery.param(params);
	}
	
	this._build();
	
}
/**
 * 
 * @returns {PageTrack}
 */
function PageTrack() { 
	var _self = this;
}
PageTrack.prototype.uuid = '4a412738-e78d-11df-b66c-000c293a788d';
PageTrack.prototype.pageTrackURI = '/producer.php';
PageTrack.prototype.pageTrackPixel = 'track.api.stat-trak.com/PageTrack/track.gif';
PageTrack.prototype.tracked = false;
PageTrack.prototype.message = null;
PageTrack.prototype.track = function() {
	var _self = this;
	_self.message = this._buildMessage();
	this._sendMessage(_self.message);
}
PageTrack.prototype._buildMessage = function() {
	var ptm = new PageTrackMessage();
	ptm.uuid = this.uuid;
	return ptm;
}
PageTrack.prototype._getTrackingPixelPath = function() {
	var _self = this;
	var protocol = (isSecure()) ? 'https://' : 'http://';
	var fullUrl = protocol + _self.pageTrackPixel;
	return fullUrl;
}
PageTrack.prototype._sendMessage = function(pageTrackMessage) {
	var _self = this;
	
	_self._sendMessagePixel(pageTrackMessage);
}
PageTrack.prototype._sendMessagePixel = function(pageTrackMessage) {
	var _self = this;
	if(!this.tracked) {
		var params = pageTrackMessage.getNvpArgs();
		var imgElement = document.createElement('img');
		var img = jQuery(imgElement);
		img.attr('id','_pagetrackPixelImg');
		img.width(0);
		img.height(0);
		img.hide();7
		img.attr('src', _self._getTrackingPixelPath() + "?" + params);
		jQuery(document.body).append(img);
		this.tracked = true;
	}
}
PageTrack.prototype._sendMessageRest = function(pageTrackMessage) {
	var _self = this;
	if(jQuery && !this.tracked) {
		jQuery.ajax({
			cache: false
			, dataType: 'text'
			, type: 'POST'
			, url: _self.pageTrackURI
			, data: jQuery.param(pageTrackMessage,true)
			, context: this
			, success: function(data, textStatus) {
				this._sendMessageRestSuccess(data, textStatus);
			}
			, error: function(data, textStatus) {
				this._sendMessageRestFail(data, textStatus);
			}
			
		});
	}
}
PageTrack.prototype._sendMessageRestSuccess = function(data, textStatus) {
	this.tracked = true;
	jQuery('#pagetrack_status').text('Success!!!');
}
PageTrack.prototype._sendMessageRestFail = function(data, textStatus) {
	jQuery('#pagetrack_status').text('Fail!!!');
}

PageTrack.prototype.updateJoinLinks = function(selector) {
	var _self = this;
    var urlPattern =  new RegExp(".*'(https:\/\/.*)'.*");
	var urlParams = 'affiliate='+_self.message._checkGlobalAndCookie('_pagetrack_affiliate')+'&campaign='+_self.message._checkGlobalAndCookie('_pagetrack_campaign');
	if(jQuery) {
		jQuery('a.'+selector).each(function() {
			var urlOrig = jQuery(this).attr('href');
			var seperator = (urlOrig.indexOf('?')>0) ? '&': '?';
			var urlMod = urlOrig + seperator + urlParams;
			jQuery(this).attr('href', urlMod);
		});
	}
}

/*
 * Cookie Handling
 * http://www.quirksmode.org/js/cookies.html
 */
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	var domain = '.' + getDomain(window.location.hostname);
	document.cookie = name+"="+value+expires+"; path=/; domain="+domain;
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function _getQueryParam(name) {
	var query = window.location.search.substring(1);
	var kvpairs = query.split("&");
	for(var i=0; i< kvpairs.length; i++) {
		var kv = kvpairs[i].split("=");
		if(kv[0] == name && kv[0] != 'null') {
			var kvalue = kv[1];
			return kvalue;
		}
	}
	return null;
}

function getDomain(domain) {
	//alert(domain);
	//var cleaned = domain.match(/(:\/\/)?(.[^/]+)/)[1];
	//alert(cleaned);
    var split = domain.split('.');
    return split[split.length-2] + '.' + split[split.length-1]
}

/*
 * GUID Creation
 * http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
 */
function S4() {
   return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
}
function guid() {
   return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

/*
 * Detect if request is over SSL
 */
function isSecure()
{
   return window.location.protocol == 'https:';
}

/*
 * Enable PageTrack
 */
var pageTrack = new PageTrack();
pageTrack.track();
