// JavaScript Document

// Funciones para cookies

// Esta es la función que usa Heinle para recuperar una cookie
// name - nombre de la cookie deseada
// devuelve un string conteniendo el valor de la cookie especificada o null si la cookie no existe

function getCookie(name){
  var cname = name + "=";               
  var dc = document.cookie;             
  if (dc.length > 0) {              
    begin = dc.indexOf(cname);       
    if (begin != -1) {           
      begin += cname.length;       
      end = dc.indexOf(";", begin);
      if (end == -1) end = dc.length;
        return unescape(dc.substring(begin, end));
    } 
  }
  return null;
}


// Esta es una adaptación de la función de Dorcht para colar una cookie
// name - nombre de la cookie
// value - valor de la cookie
// [expires] - fecha de caducidad de la cookie (por defecto, el final de la sesión)
// [path] - camino para el cual la cookie es válida (por defecto, el camino del documento que hace la llamada)
// [domain] - dominio para el cual la cookie es válida (por defecto, el dominio del documento que hace la llamada)
// [secure] - valor booleano que indica si la trasnmisión de la cookie requiere una transmisión segura
// al especificar el valor null, el argumento tomará su valor por defecto

function setCookie(name, value, expires, path, domain, secure) {
  document.cookie = name + "=" + escape(value) + 
  ((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
  ((path == null) ? "" : "; path=" + path) +
  ((domain == null) ? "" : "; domain=" + domain) +
  ((secure == null) ? "" : "; secure");
}

// Esta fn crea un cookie "permanene" (caduca en 15 años)
function setPermanentCookie(name, value) {

	var later = new Date();
	
	later.setTime(later.getTime() + (10 * 365 * 24 * 3600 * 1000) );
	
	setCookie(name, unescape(value), later, "/");
	
}

// Esta es una adaptación de la función de Dorcht para borrar una cookie
// name - nombre de la cookie
// [path] - camino de la cookie (debe ser el mismo camino que el especificado al crear la cookie)
// [domain] - dominio de la cookie (debe ser el mismo dominio que el especificado al crear la cookie)
// se considera el camino y dominio por defecto si se especifica null o no se proporcionan argumentos

function delCookie (name,path,domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path == null) ? "" : "; path=" + path) +
    ((domain == null) ? "" : "; domain=" + domain) +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}


/*
The following is an example how to use that function to list all data 
passed to the page:

<SCRIPT>
var args = parseQueryString ();
for (var arg in args) {
  document.write(arg + ': ' + args[arg] + '<BR>');
}
</SCRIPT>The following is an example how to use that function to list all data 
passed to the page:

<SCRIPT>
var args = parseQueryString ();
for (var arg in args) {
  document.write(arg + ': ' + args[arg] + '<BR>');
}
</SCRIPT>
*/
function parseQueryString (str) {
  str = str ? str : location.search;
  var query = str.charAt(0) == '?' ? str.substring(1) : str;
  var args = new Object();
  if (query) {
    var fields = query.split('&');
    for (var f = 0; f < fields.length; f++) {
      var field = fields[f].split('=');
      args[unescape(field[0].replace(/\+/g, ' '))] = unescape(field[1].replace(/\+/g, ' '));
    }
  }
  return args;
}

// Checks if the non affiliate cookies are present, so we don't overwrite them.
// They should only be written once, at the time of the first visit.
function hasNonAffiliateCookies() {
	var rc = getCookie("hasNonAffiliateCookies");
	
	return (rc != null);
}

// Add the non affiliate cookies. Should only be done the first visit.
// Adds the following information:
//	* dayOfFirstVisit: day month and year of first visit
//	* firstVisitedPage: The first page in easyjob that was visited
//	* firstReferrer: The site it came from for the first time
//	* firstQueryString: The query string (if any) it had when it arrived the first time (will show keywords if coming from SE)
//	* affId: Affiliate cookie
//	* visitorId: a Unique id that is passed to swreg when ordering, so we can track those who buy (that text will be sent in the email)
function addCookies() {

	addAffId();
	
	if (! hasNonAffiliateCookies() ) {
		// the first page the user visited in our site
		setPermanentCookie("firstVisitedPage", document.URL);
	
	
		// Date of first visit
		var today = new Date();
		setPermanentCookie("dayOfFirstVisit", today.getFullYear() + "-" + (today.getMonth() + 1)  + "-" + today.getDate());
	
		// Unique Id for each visitor
		setPermanentCookie("visitorId", today.getTime());
		
		// referrer for fist visit and query string (if any)
		var referrer = "";
		var query = "";
		
		if (document.referrer.length > 0) {
			referrer = document.referrer;
			
			if (document.referrer.indexOf("?") > -1) {
				// hay referrer y query string
				
				var ref = document.referrer.split("?");
				referrer = ref[0];
				query = ref[1];
			}
		}
		
		setPermanentCookie("firstReferrer", referrer);
		setPermanentCookie("firstQueryString", query);
	
		
		// Non aff cookies flag
		setPermanentCookie("hasNonAffiliateCookies", 1);
	}		


}

// Affiliate ID:
// If the url has an affiliate id, we set it as a cookie, even if there was another one  already
// in the cookiejar.
function addAffId() {

	// find the affId in the search string, if any
	var tokens = parseQueryString();
	var affId;
	
	
	for (var token in tokens) {

		if (token.toLowerCase() == "affid") {
			affId = tokens[token];
		}
	}
  	
	// if it was found, save it as a cookie
	if (affId != null) {
		delCookie("affId");
		setPermanentCookie("affId", affId);
		
		
	}
		
}
