function Cookie(the_name) {
	
	this.the_name = the_name;
	
	var domain;
	var path;
	var expires = 10; // default in giorni
	var secure = false; // cookie in ssl
	
	// prendo il contenuto del cookieu
	this.get = function() {
		var start = document.cookie.indexOf( this.the_name + "=" );
		var len = start + this.the_name.length + 1;
		if ( ( !start ) && ( this.the_name != document.cookie.substring( 0, this.the_name.length ) ) ) {
			return null;
		}
		if ( start == -1 ) { 
			return null;
		}
		var end = document.cookie.indexOf( ";", len );
		
		if ( end == -1 ) end = document.cookie.length;

		return unescape( document.cookie.substring( len, end ) );
	}
	
	// creo il cookie
	this.create = function() {
		document.cookie = this.createContent();
	}
	
	// non funziona devo capire perche'!?
	this.destroy = function() {
		if(this.get()) {
			document.cookie = this.the_name + "=" +
				( ( this.path ) ? ";path=" + this.path : "") +
				( ( this.domain ) ? ";domain=" + this.domain : "" ) +
				";expires=Thu, 01-Jan-1970 00:00:01 GMT";
		}
	}
	
	// creo il contenuto del cookie
	this.createContent = function() {
		var content = "";
		
		content += this.the_name + "=" + escape( this.value ) + ";";
		
		if(this.expires) {
			content += "expires=" + this.buildExpiration().toGMTString() + ";";
		}
		
		if(this.domain) {
			content += "domain=" + this.domain + ";";
		}

		if(this.path) {
			content += "path=" + this.path + ";";
		}
		
		if(this.secure) {
			content += "secure;";
		}
		return content;
	}
	
	// creo la data di scadenza per il cookie
	this.buildExpiration = function() {
		var today = new Date();
		today.setTime( today.getTime() );
		if ( this.expires && this.expires > 0 ) {
			this.expires = this.expires * 1000 * 60 * 60 * 24;
		}
		return expires_date = new Date( today.getTime() + (this.expires) );
	}
	
	// setto il valore (content) del cookie
	this.setValue = function(value) {
		this.value = escape(value);
	}			
	
	// sretto la scadenza
	this.setExpires = function(value) {
		this.expires = value;
	}
	
	// setto il path di riferimento
	this.setPath = function(value) {
		this.path = value;
	}
	
	// setto il dominio
	this.setDomain = function(value) {
		this.domain = value;
	}
	
	// settaggio per https (ssl)
	this.setSecure = function(value) {
		this.secure = value;
	}
}
function Params() {
	
	// constuisco i parametri "interni"
	this.inner = function() {
		var params = "";
		
		try {
	 		if(!isNaN(_i1)) {
				params += "&_i1=" + _i1;
	 		}
		} catch(e) {}
	
		try {
		 	if(!isNaN(_i2)) {
		 		params += "&_i2=" + _i2;
		 	}
		} catch(e) {}
	
		try {
		 	if(!isNaN(_i3)) {
	 			params += "&_i3=" + _i3;
	 		}
		} catch(e) {}
	
		return params;
	}
	
	// costruisco i parametri 
	// passati in modo "extra"
	this.extra = function() {
		var params = "";
		
		try {
			//params += "&" + escape(_e);
			params += "&" + _e;
		} catch (e) {} 
		
		return params;
	}
	
}
function InitTrack(key, alias) {
	try {
		this.key = key;	
	} catch(e) {
		this.key = "";
	}
	
	try {
		this.alias = alias;	
	} catch(e) {
		this.alias = "";
	}
	track = new Track(this);	
}
//-- **** INIZIO CONFIGURAZIONE **** --
//-- Configurazione track
var MODE = "auto" // (contactlab|user|auto) metodo di registrazione dati

var SEND_DATA = "all";

//-- Configurazione passaggio parametri
var returnAlias = 1; // (0|1) restituisce l'alias definito nel costruttore
var keyAlias = "tpagealias"; // definisce la chiave di ritorno per l'alias

var returnCurrent = 1; // (0|1) restituisce la pagina corrente 
var keyCurrent = "tpage"; // definisce la chiave di ritorno per la pagina corrente 

var returnReferrer = 1; // (0|1) restituisce la pagina referrer 
var keyReferrer = "treferrer"; // definisce la chiave di ritorno per il referrer 

var returnPageTitle = 1; // (0|1) restituisce il titolo della pagina
var keyPageTitle = "title"; // definisce la chiave di ritorno per il titlo pagina

var keySource = "clabtrack"; // definisce la chiave di ritorno per il sorgente

//-- Configurazione cookie
var cookieDomainName = ""; // dominio per il quale e' attivo il cookie (vuoto indica il dominio in corso)
var cookiePath = "/"; // path dal quale e' attivo il cookie (/ tutto il dominio)
var cookieLifetime = 730; // (n) viene espressa in giorni (0 indica la durata per una sola sessione)
var cookieSSL = false; // (true|false) // true per utilizzo con SSL

//-- **** FINE CONFIGURAZIONE **** --

var AUTO_VALUE;
var AUTO_KEY = "tid";
var MASTER_KEY = "key";
var PUBLIC_EXTENSION = "pex";

function Track(InitTrack) {
	try {
		this.key = InitTrack.key;	
	} catch(e) {
		this.key = "";
	}
	
	try {
		this.alias = InitTrack.alias;	
	} catch(e) {
		this.alias = "";
	}
	

	var the_keys = new Array();
	
	the_keys["alias"] = new Array(returnAlias, keyAlias, this.alias);
	the_keys["current"] = new Array(returnCurrent, keyCurrent, document.URL.split("?")[0]);
	the_keys["referrer"] = new Array(returnReferrer, keyReferrer,  document.referrer.split("?")[0]);
	the_keys["pagetitle"] = new Array(returnPageTitle, keyPageTitle, document.title);
	
	// converto l'array di byte in stringa
	this.reverseByteArray = function(value) {
		var result = "";
	  	for(var i = 0; i <= value.length; i++) {
	    	if (value[i] != 0) {
	    		result += String.fromCharCode(value[i]);
	    	}
	  	}
	  	return result;
	}

	this.makeTrackSystemLocation = function() {
		theDomain = String.fromCharCode(104, 116, 116, 112, 58, 47, 47, 97, 110, 97, 108, 121, 116, 105, 99, 115, 46, 99, 111, 110, 116, 97, 99, 116, 108, 97, 98, 46, 105, 116);
		thePath = String.fromCharCode(47);
		thePage = String.fromCharCode(105, 110, 100, 101, 120, 46, 103, 105, 102);
		
		theRealUrl = theDomain + thePath + thePage;
		return theRealUrl
	}
	
	// creazione dei parametri base secondo configurazione 
	this.buildBasicParams = function() {
		var outValue = new Array();
		var i = 0;
		for (var isActive in the_keys) {
			if(the_keys[isActive][0]) {
				outValue[i] = the_keys[isActive][1] + "=" + escape(the_keys[isActive][2]);
				i++;
			}
		}
		return outValue.join("&");
	}
	
	this.buildExtraParams = function() {
		this.link = "l";
		var outValue = new Array();
			
		if (location.search.length > 0) {
			launchstring = location.search.substring(1, location.search.length);
			var launchstringArray = launchstring.split("&");
			var c = 0;
			for (var i = 0; i <= launchstringArray.length - 1; i++) {
				var left = launchstringArray[i].substring(0, launchstringArray[i].indexOf("="));
				var right = launchstringArray[i].substring(launchstringArray[i].indexOf("=") + 1, launchstring.length);
				
				switch(left) {
					case this.link:
						outValue[c] = left + "=" + right;
						c++;
					break;
					case keySource:
						outValue[c] = left + "=" + right;
						c++;
					break;
					default: null;
				}
			}
			
		}
		if( outValue.length > 0 ) {
			return "&"+outValue.join("&");
		} else {
			return "";
		}
	}
	
	// nome cookie	
	var the_cookie_name = "CTrack";
	
	// istanza cookie
	var cookie = new Cookie(the_cookie_name);
	
	this.innerObj = new Contactlab(this);
	

	// verifico se sono presenti i dati clab
	if(this.innerObj.validateRequest() == null) {
		
		// tento la via della chiave definita dal cliente
		// se non la trovo ho una eccezione di tipo nullpointer
		try {
	 		if(userKey) {
				this.innerObj = new ThirdPartyID(this);
	 		}
		} catch(e) {
			// id autogestito, ultima spiaggia
			this.innerObj = new SelfControl(this);
		}		
	}
	
	// valido e prendo i parametri per questa richiesta
	var receivedParam = this.innerObj.validateRequest()
	
	// richiesta non valida
	if(receivedParam == false) {
		return;
	}
	
	// esegue la chiamata al sistema di track remoto e manda i dati
	this.invoke = function() {
		var params = new Params();
		var addQueryString = "";
		
		try {
			addQueryString =  params.inner() + params.extra();
		} catch(e) {}
		
		var thecall = this.makeTrackSystemLocation() + "?" + unescape(cookie.get()) + "&" + this.buildBasicParams() + this.buildExtraParams() + addQueryString;
		
		pix = new Image(1,1);
		pix.src = thecall;
	}
	
	// imposto il cookie solo se non c'e' o se clab invia parametri differenti da quelli registrati
	// in precedenza
	var rewrite = false;
	
	if(this.innerObj instanceof Contactlab) {
		var recived = unescape(receivedParam).replace(/pex=([0-9]+)\&/i,'');
		var stored = unescape(cookie.get()).replace(/pex=([0-9]+)\&/i,'');
		
		if(recived != stored) {
			rewrite = true; 
		}
	}
	
	
	if((cookie.get() == null && receivedParam != null) || rewrite == true) {
		cookie.setValue( receivedParam );
		cookie.setExpires( cookieLifetime );
		cookie.setPath( cookiePath );
		cookie.setDomain( cookieDomainName );
		cookie.setSecure( cookieSSL );
		cookie.create();
	}
	
	// chiamo il track
	this.invoke();
	/*
	switch(SEND_DATA) {
		case "contactlab":
			if(this.innerObj instanceof Contactlab) {
				// chiamo il track
				this.invoke();
			}		
		break;
		case "all":
		default:
			// chiamo il track
			this.invoke();
	}
	*/
	
}
// questa e' dedicata a contactlab
// vengono passati 4 parametri necessari al sistema che riceve i dati
function Contactlab(Track) {
	this.req = 2;
	
	this.q = "q";
	this.g = "g";
	
	this.validateRequest = function() {
		var outValue = new Array();
			
		if (location.search.length > 0) {
			launchstring = location.search.substring(1, location.search.length);
			var launchstringArray = launchstring.split("&");
			var c = 0;
			for (var i = 0; i <= launchstringArray.length - 1; i++) {
				var left = launchstringArray[i].substring(0, launchstringArray[i].indexOf("="));
				var right = launchstringArray[i].substring(launchstringArray[i].indexOf("=") + 1, launchstring.length);
				
				switch(left) {
					case this.q:
					case this.g:
						outValue[c] = left + "=" + right;
						c++;
					break;
					default: null;
				}
			}
			
			
			if( outValue.length == this.req ) {
				this.uniqueid = (new Date()).getTime() + "" + Math.floor((Math.random()*8999)+1000);
				return MASTER_KEY + "=" + Track.key + "&" + PUBLIC_EXTENSION + "=" + this.uniqueid + "&" + outValue.join("&");
			}
			return null;
		}
	}
}

// questa crea un id in autonomia in caso di trak "generico"
function SelfControl(Track) {
		
	this.masterKey = AUTO_KEY;	
	this.uniqueid = (new Date()).getTime() + "" + Math.floor((Math.random()*8999)+1000);
	
	this.validateRequest = function() {
		return MASTER_KEY + "=" + Track.key + "&" + this.masterKey + "=" + this.uniqueid; 
	}

}

// prende un id passato come parametro dal sistema
// che ospita il js. 
function ThirdPartyID(Track) {
	this.masterKey = AUTO_KEY;
	
	this.validateRequest = function() {
		
		if(Track.key == "undefined" || Track.key == null) {
			alert(Track.key + "nonvalido");
			return false;
		}
		this.uniqueid = (new Date()).getTime() + "" + Math.floor((Math.random()*8999)+1000);
		return MASTER_KEY + "=" + Track.key + "&" + PUBLIC_EXTENSION + "=" + this.uniqueid + "&" + this.masterKey + "=" + userKey; 
	}
}
