//------------------------------------------------
// action (sale / lead / custom action) object
//------------------------------------------------

var PostAffAction = function(actionCode) {
	this._actionCode = actionCode;
	this._totalCost = '';
	this._orderID = '';
	this._productID = '';
	this._data1 = '';
	this._data2 = '';
	this._data3 = '';
	this._data4 = '';
	this._data5 = '';
	this._affiliateID = '';
	this._campaignID = '';
	this._channelID = '';
	this._customCommission = '';
	this._status = '';
	this._currency = '';
}

PostAffAction.prototype.correctSumChars = function(value) {
	var strValue = new String(value);
	strValue = strValue.replace(/,/g, ".");
	strValue = strValue.replace(/[^0-9\.]/gi, "");
	return strValue;
}

PostAffAction.prototype.correctCommissionChars = function(value) {
	var strValue = new String(value);
	strValue = strValue.replace(/,/g, ".");
	strValue = strValue.replace(/[^0-9\.\%]/gi, "");
	strValue = strValue.replace(/%/gi, "%25");
	return strValue;
}

PostAffAction.prototype.correctTextChars = function(value) {
	var strValue = new String(value);
	strValue = strValue.replace(/ /gi, "+");
	strValue = strValue.replace(/[^a-zA-z0-9\+_-]/gi, "_");
	return strValue;
}

PostAffAction.prototype.setTotalCost = function(value) {
	try {
		if(typeof(value) != 'undefined') { 
			this._totalCost = this.correctSumChars(value);
		}
	} catch (err) { }
}

PostAffAction.prototype.setOrderID = function(value) {
	try {
		if(typeof(value) != 'undefined') { 
			this._orderID = this.correctTextChars(value); 
		}
	} catch (err) { }
}

PostAffAction.prototype.setProductID = function(value) {
	try {
		if(typeof(value) != 'undefined') { 
			this._productID = this.correctTextChars(value); 
		}
	} catch (err) { }
}

PostAffAction.prototype.setAffiliateID = function(value) {
	try {
		if(typeof(value) != 'undefined') { 
			this._affiliateID = this.correctTextChars(value); 
		}
	} catch (err) { }
}

PostAffAction.prototype.setCampaignID = function(value) {
	try {
		if(typeof(value) != 'undefined') { 
			this._campaignID = this.correctTextChars(value); 
		}
	} catch (err) { }
}

PostAffAction.prototype.setChannelID = function(value) {
	try {
		if(typeof(value) != 'undefined') { 
			this._channelID = this.correctTextChars(value); 
		}
	} catch (err) { }
}

PostAffAction.prototype.setCurrency = function(value) {
    try {
        if(typeof(value) != 'undefined') {
            this._currency = this.correctTextChars(value); 
        }
    } catch (err) { }
}

PostAffAction.prototype.setCustomCommission = function(value) {
	try {
		if(typeof(value) != 'undefined') {
			this._customCommission = this.correctCommissionChars(value); 
		}
	} catch (err) { }
}

PostAffAction.prototype.setStatus = function(value) {
	try {
		if(typeof(value) != 'undefined') { this._status = value; }
	} catch (err) { }
}

PostAffAction.prototype.setData1 = function(value) {
	try {
		if(typeof(value) != 'undefined') { 
			this._data1 = this.correctTextChars(value); 
		}
	} catch (err) { this._data1 = 0; }
}

PostAffAction.prototype.setData2 = function(value) {
	try {
		if(typeof(value) != 'undefined') { 
			this._data2 = this.correctTextChars(value); 
		}
	} catch (err) { this._data2 = 0; }
}

PostAffAction.prototype.setData3 = function(value) {
	try {
		if(typeof(value) != 'undefined') { 
			this._data3 = this.correctTextChars(value); 
		}
	} catch (err) { this._data3 = 0; }
}

PostAffAction.prototype.setData4 = function(value) {
	try {
		if(typeof(value) != 'undefined') { 
			this._data4 = this.correctTextChars(value); 
		}
	} catch (err) { this._data4 = 0; }
}

PostAffAction.prototype.setData5 = function(value) {
	try {
		if(typeof(value) != 'undefined') { 
			this._data5 = this.correctTextChars(value); 
		}
	} catch (err) { this._data5 = 0; }
}





//------------------------------------------------
// real tracker object
//------------------------------------------------

var PostAffTrackerObject = function() {
	this._lid = '';
	this.appendSeparator = null;

	var trackingUrl = new String(document.getElementById('pap_x2s6df8d').src);
	this._trackingUrl = trackingUrl.substr(0, Math.max(trackingUrl.lastIndexOf('\\'), trackingUrl.lastIndexOf('/'))+1);
	
	this._trackingMethod = '1';
	this._cookieVal = '';
	
	this._flashStarted = false;
	this._actionObjects = new Array();
	this._cookies = new Array();
	
	var cookie = new Object;
	cookie.name = 'PAPCookie_Sale';
	cookie.postname = 'fsc';
	cookie.value = '';
	cookie.del = false;
	this._cookies[0] = cookie;

	var cookie = new Object;
	cookie.name = 'PAPCookie_FirstClick';
	cookie.postname = 'ffcc';
	cookie.value = '';
	cookie.del = false;
	this._cookies[1] = cookie;

	var cookie = new Object;
	cookie.name = 'PAPCookie_LastClick';
	cookie.postname = 'flcc';
	cookie.value = '';
	cookie.del = false;
	this._cookies[2] = cookie;
 
 	this._writeImg();
 	this._loadFirstPartyCookies();
}

PostAffTrackerObject.prototype.createAction = function(actionCode) {
    var obj = new PostAffAction(actionCode);
    var index = this._actionObjects.length;
    this._actionObjects[index] = obj;
    
    return obj;
}

PostAffTrackerObject.prototype.register = function() {
    if (this._isFlashActive()) {
        this._insertFlashObject();
        setTimeout('trackNext()', 1000);
    } else {
        this._trackNext();
    }
    this._deleteFirstPatyCookies();	
}

PostAffTrackerObject.prototype.notifySale = function() {
	this.writeCookieToCustomField('pap_dx8vc2s5');
}


PostAffTrackerObject.prototype._checkIfToRunFlash = function(value) {
	if(this._isFlashActive() && this._flashStarted == false) {
		return true;
	} 
	return false;
}

PostAffTrackerObject.prototype.setLid = function(value) {
	try {
		if(typeof(value) != 'undefined') { this._lid = value; }
	} catch (err) { }
}

PostAffTrackerObject.prototype.setCookieValue = function(value) {
	try {
		if(typeof(value) != 'undefined') { this._cookieVal = value; }
	} catch (err) { }
}

PostAffTrackerObject.prototype._getFlashVersion = function() {
	var version = "", n=navigator;
	if (n.plugins && n.plugins.length) {
		for (var i=0; i < n.plugins.length;i++) {
			if (n.plugins[i].name.indexOf('Shockwave Flash')!=-1) {
	    		version = n.plugins[i].description.split('Shockwave Flash ')[1];
	    		break;
	   		}
	  	}
	 } else if (window.ActiveXObject) {
	 	for (var i=10; i>=4; i--) {
	   		try {
	    		var result = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash."+i+"');");
	    		if (result) {
	    			version = i + '.0';
		    		break;
		    	}
	   		} catch(e) {}
	  	}
	 }
	 return version;
}

PostAffTrackerObject.prototype._isFlashActive = function() {
	var version = this._getFlashVersion();
	var ns4 = document.layers;
    var ns6 = document.getElementById && !document.all || (navigator.userAgent.indexOf('Opera') >= 0);
    var ie4 = document.all;
	if(!ns4 && !ns6 && ie4 && (this._saleType == 1)) {
	   return false;
	}
	return !(version == "" || version < 5);
}

PostAffTrackerObject.prototype._getFlashParams = function() {
	var params = "";
	for(var i=0; i < this._cookies.length; i++) {
		params += "&amp;n" + i + "=" + this._cookies[i].name;
		if (this._cookies[i].del == true) {
			params += "&amp;d" + i + "=1";
		}
	}
	return "?a=r" + params;
}

PostAffTrackerObject.prototype._insertFlashObject = function() {
    if(this._checkIfToRunFlash()) {
    	this._flashStarted = true;
    	
		document.write("<object classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" " +
		"codebase=\"" + ((this._trackingUrl.substr(0, 5) == "https") ? "https" : "http") + "://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0\" " +
		"width=\"1px\" height=\"1px\"> " +
		"<param name=\"allowScriptAccess\" value=\"always\" />" +
		"<param name=\"movie\" value=\"" + this._trackingUrl + "pap.swf"+ this._getFlashParams() +"\" /> " +
		"<embed src=\"" + this._trackingUrl + "pap.swf"+ this._getFlashParams() +"\" width=\"1px\" height=\"1px\" allowScriptAccess=\"always\"/> " +
		"</object>");
	}
}

PostAffTrackerObject.prototype._processFlashCookies = function(cookies) {
    var flashCookies = cookies.split('_,_');
    for(var i=0; i< flashCookies.length; i++) {
        var splitIndex = flashCookies[i].indexOf('=');
        if (splitIndex < 0) continue;
        if ((flashCookies[i].substr(splitIndex+1) == null) || (flashCookies[i].substr(splitIndex+1) == '')) continue;
        this._setCookie(flashCookies[i].substr(0, splitIndex), flashCookies[i].substr(splitIndex+1), 'F');
    }
}

PostAffTrackerObject.prototype._setCookie = function(name, value, type) {
    for(var i=0; i < this._cookies.length; i++) {
        if (this._cookies[i].name == name) {
            this._cookies[i].value = value;
            this._trackingMethod = type;
        }
	}
}

PostAffTrackerObject.prototype._setCookieToBeDeleted = function(name) {
	if (this._saleType == 1) return;
	for(var i=0; i < this._cookies.length; i++) {
        if (this._cookies[i].name == name) {
            this._cookies[i].del = true;
        }
	}
}

PostAffTrackerObject.prototype._writeImg = function() {
    document.write('<img id="pap_0x25s6ds" src="'+this._trackingUrl+'pix.gif" width="1" height="1">');
}

PostAffTrackerObject.prototype._loadFirstPartyCookies = function() {
	for(var i=0; i < this._cookies.length; i++) {
	    var cookieValue = this._getNormalCookie(this._cookies[i].name);
	    if (cookieValue != null) {
	       this._cookies[i].value = cookieValue;
	       this._trackingMethod = '1';
	    }
	}
}

PostAffTrackerObject.prototype._deleteFirstPatyCookies = function() {
	for(var i=0; i < this._cookies.length; i++) {
        if (this._cookies[i].del ) {
            document.cookie = this._cookies[i].name+'=;expires=Thu, 01-Jan-1970 00:00:01 GMT;path=/';
        }
	}
}

PostAffTrackerObject.prototype._getNormalCookie = function(name) {
    var nameequals = name + "=";
    var beginpos = 0;
    var beginpos2 = 0;
    while (beginpos < document.cookie.length) {
        beginpos2 = beginpos + name.length + 1;
        if (document.cookie.substring(beginpos, beginpos2) == nameequals) {
            var endpos = document.cookie.indexOf (";", beginpos2);
            if (endpos == -1)
                endpos = document.cookie.length;
            return unescape(document.cookie.substring(beginpos2, endpos));
        }
        beginpos = document.cookie.indexOf(" ", beginpos) + 1;
        if (beginpos == 0) break;
    }

    return null;
}

PostAffTrackerObject.prototype._trackNext = function() {
	var params = this._getParameters();
	document.getElementById("pap_0x25s6ds").src = this._trackingUrl + "sale.php" + params;
}

PostAffTrackerObject.prototype._getParameters = function() {
	var params = "?lid=" + this._lid;
	params += "&ptm=" + this._trackingMethod;

	if(this._cookieVal != '') {
		params += "&CookieValue=" + this._cookieVal;		
	}
	
	var length = this._actionObjects.length;
	if(length > 0) {
		var actionCode = '';
		var totalCost = '';
		var orderID = '';
		var productID = '';
		var data1 = '';
		var data2 = '';
		var data3 = '';
		var data4 = '';
		var data5 = '';
		var affiliateID = '';
		var campaignID = '';
		var channelID = '';
		var customCommission = '';
		var customStatus = '';
		var currencyCode = '';
		
		for(i=0; i< length; i++) {
    		obj = this._actionObjects[i];
	    
	        actionCode = this._addToInnerParameter(i, actionCode, obj._actionCode);
	    	totalCost = this._addToInnerParameter(i, totalCost, obj._totalCost);
	    	orderID = this._addToInnerParameter(i, orderID, obj._orderID);
	    	productID = this._addToInnerParameter(i, productID, obj._productID);
	    	data1 = this._addToInnerParameter(i, data1, obj._data1);
	    	data2 = this._addToInnerParameter(i, data2, obj._data2);
	    	data3 = this._addToInnerParameter(i, data3, obj._data3);
	    	data4 = this._addToInnerParameter(i, data4, obj._data4);
	    	data5 = this._addToInnerParameter(i, data5, obj._data5);
	    	affiliateID = this._addToInnerParameter(i, affiliateID, obj._affiliateID);
	    	campaignID = this._addToInnerParameter(i, campaignID, obj._campaignID);
	    	channelID = this._addToInnerParameter(i, channelID, obj._channelID);
	    	customCommission = this._addToInnerParameter(i, customCommission, obj._customCommission);
	    	customStatus = this._addToInnerParameter(i, customStatus, obj._status);
	    	currencyCode = this._addToInnerParameter(i, currencyCode, obj._currency);
		}
		
		var somethingExists = false;
		if(actionCode != '') { params += "&ActionCode=" + escape(actionCode); somethingExists = true; }
		if(totalCost != '') { params += "&TotalCost=" + escape(totalCost); somethingExists = true; }
		if(orderID != '') { params += "&OrderID=" + escape(orderID); somethingExists = true; }
		if(productID != '') { params += "&ProductID=" + escape(productID); somethingExists = true; }
		if(data1 != '') { params += "&data1=" + escape(data1); somethingExists = true; }
		if(data2 != '') { params += "&data2=" + escape(data2); somethingExists = true; }
		if(data3 != '') { params += "&data3=" + escape(data3); somethingExists = true; }
		if(data4 != '') { params += "&data4=" + escape(data4); somethingExists = true; }
		if(data5 != '') { params += "&data5=" + escape(data5); somethingExists = true; }
		if(affiliateID != '') { params += "&AffiliateID=" + escape(affiliateID); somethingExists = true; }
		if(campaignID != '') { params += "&CampaignID=" + escape(campaignID); somethingExists = true; }
		if(channelID != '') { params += "&ChannelID=" + escape(channelID); somethingExists = true; }
		if(customCommission != '') { params += "&Commission=" + escape(customCommission); somethingExists = true; }
		if(customStatus != '') { params += "&PStatus=" + escape(customStatus); somethingExists = true; }
		if(currencyCode != '') { params += "&Currency=" + escape(currencyCode); somethingExists = true; }
		
		if(somethingExists == false) {
			params += "&OrderID=";
			for(i=0; i< length-1; i++) {
				params += ":";
			}
		}
	}

	params += this._getCookieParams();
	return params;	
}

PostAffTrackerObject.prototype._addToInnerParameter = function(index, param, value) {
	if(param != '') {
		param += ':';
	}
	if(value != '') {
		if(param == '') {
			for(i=0; i< index; i++) {
				param += ":";
			}
		}
		
		param += value;
	}		
	return param;
}

PostAffTrackerObject.prototype.writeCookieToCustomField = function(id) {
    if (this._isFlashActive()) {
    	// write 1st party cookies immediately
        this._writeCookieToCustomField(id);
        // get flash cookies on delay
        this._insertFlashObject();
        setTimeout('_writeCookieToCustomField(\''+id+'\')', 1000);
    } else {
        this._writeCookieToCustomField(id);
    }
}

PostAffTrackerObject.prototype._writeCookieToCustomField = function(id) {
    cookieVal = this._cookies[0].value;
    if(cookieVal == null || cookieVal == '') {
	    return;
    }
    this._writeValueToCustomField(id, cookieVal);
}

PostAffTrackerObject.prototype.writeAffiliateToCustomField = function(id) {
    if (this._isFlashActive()) {
        this._insertFlashObject();
        setTimeout('_writeAffiliateToCustomField(\''+id+'\')', 1000);
    } else {
        this._writeAffiliateToCustomField(id);
    }
}

PostAffTrackerObject.prototype._writeAffiliateToCustomField = function(id) {
    cookieVal = this._cookies[0].value;
    if(cookieVal == null || cookieVal == '') {
	    return;
    }
    var cookie = eval('(' + cookieVal + ')');
    this._writeValueToCustomField(id, cookie.a);
}

PostAffTrackerObject.prototype.writeCampaignToCustomField = function(id) {
    if (this._isFlashActive()) {
        this._insertFlashObject();
        setTimeout('_writeCampaignToCustomField(\''+id+'\')', 1000);
    } else {
        this._writeCampaignToCustomField(id);
    }
}

PostAffTrackerObject.prototype._writeCampaignToCustomField = function(id) {
    cookieVal = this._cookies[0].value;
    if(cookieVal == null || cookieVal == '') {
	    return;
    }
    var cookie = eval('(' + cookieVal + ')');
    this._writeValueToCustomField(id, cookie.c);
}

PostAffTrackerObject.prototype.getElementsById = function(id) {
	var nodes = new Array();
	var tmpNode = document.getElementById(id);
	while(tmpNode) {
		nodes.push(tmpNode);
		tmpNode.id = "";
		tmpNode = document.getElementById(id);
	}
	for(var x=0; x<nodes.length; x++) {
		nodes[x].id = id;
    }
    
    return nodes;
}

PostAffTrackerObject.prototype._replaceHttpInText = function(text) {
	text = text.replace("http://", "H_");
	text = text.replace("https://", "S_");
	return text;
}

PostAffTrackerObject.prototype._getCookieParams = function() {
	var params = "";
	for(var i=0; i < this._cookies.length; i++) {
		params += "&" + this._cookies[i].postname + "=" + escape(this._replaceHttpInText(this._cookies[i].value));
	}
	return params;
}

PostAffTrackerObject.prototype.setAppendValuesToField = function(separator) {
	this.appendSeparator = separator;
}

PostAffTrackerObject.prototype._writeValueToCustomField = function(id, value) {
    if(value == null || value == '') {
	    return;
    }
    var customInputs = this.getElementsById(id);
	for (i=0;i<customInputs.length;i++) {
        if (customInputs[i].id == id) {
        	if (this.appendSeparator != null) {
                oldValue = customInputs[i].value.split(this.appendSeparator, 2);
                customInputs[i].value = oldValue[0] + this.appendSeparator + value;
        	} else {
        		customInputs[i].value = value;
        	}
        }
	}
}

//------------------------------------------------
// singleton tracker object
//------------------------------------------------

var PostAffTracker = new function(lid) {
	this._instance = new PostAffTrackerObject();
		
	this.createSale = function() {
		return this._instance.createAction('');
	}
	
	this.createAction = function(actionCode) {
        return this._instance.createAction(actionCode);
    }

	this.register = function() {
		return this._instance.register();
	}

	this.notifySale = function() {
		return this._instance.notifySale();
	}
	
	this.setLid = function(value) {
		return this._instance.setLid(value);
	}

	this.setChannel = function(value) {
		return this._instance.setChannel(value);
	}
	
	this.setCookieValue = function(value) {
		return this._instance.setCookieValue(value);
	}	
	
	this.writeCookieToCustomField = function(id) {
		return this._instance.writeCookieToCustomField(id);
	}

	this._writeCookieToCustomField = function(id) {
		return this._instance._writeCookieToCustomField(id);
	}

	this.writeAffiliateToCustomField = function(id) {
		return this._instance.writeAffiliateToCustomField(id);
	}

	this._writeAffiliateToCustomField = function(id) {
		return this._instance._writeAffiliateToCustomField(id);
	}

	this.writeCampaignToCustomField = function(id) {
		return this._instance.writeCampaignToCustomField(id);
	}

	this._writeCampaignToCustomField = function(id) {
		return this._instance._writeCampaignToCustomField(id);
	}

	this._processFlashCookies = function(cookies) {
		return this._instance._processFlashCookies(cookies);
	}
	
	this._setCookieToBeDeleted = function(name) {
		return this._instance._setCookieToBeDeleted(name);
	}
	
	this.setAppendValuesToField = function(separator) {
		return this._instance.setAppendValuesToField(separator);
	}

	this._trackNext = function() {
		return this._instance._trackNext();
	}
}

//------------------------------------------------
// global functions
//------------------------------------------------

function rpap(cookies) {
//alert('RPAP ' + cookies);
	PostAffTracker._processFlashCookies(cookies);
}

function trackNext() {
    PostAffTracker._trackNext();
}

function _writeCookieToCustomField(id) {
    PostAffTracker._writeCookieToCustomField(id);
}

function _writeAffiliateToCustomField(id) {
    PostAffTracker._writeAffiliateToCustomField(id);
}

function _writeCampaignToCustomField(id) {
    PostAffTracker._writeCampaignToCustomField(id);
}
PostAffTracker.notifySale();
