var w = window;
var llRef = getParam(document.location+"", "llref");

//If an ID is assigned
if(w.llId)
{      
  var proto = w.location.protocol.toLowerCase();
  //Set protocol
  if ('http:' != proto && 'https:' != proto) 
    {
      proto = 'http:';
    }
  
  var notRefreshed = isNotRefresh();
  if (notRefreshed)
  {
    var b = getBrowserId();
    //Set image path
    var url = proto +
      "//www.localleaptracking.com/tr/" +
      escape(w.llId) +
      "/?" +
      "ref=" + escape(llRef) +
      "&t=" + (new Date()).getTime() + 
      "&b=" + b;
    
    //Write image
    document.write('<i' + 'mg height="1" width="1" border="0" ' +
                   'src="' + url + '" />');
  }
}

//Gets parameters from the query string
//Thanks Google
function getParam(url, param)
{
  var i;
  var val;
  if ((i = url.indexOf("?" + param + "=")) > -1 ||
      (i = url.indexOf("?" + param.toUpperCase() + "=")) > -1 ||
      (i = url.indexOf("&" + param + "=")) > -1 ||
      (i = url.indexOf("&" + param.toUpperCase() + "=")) > -1) {
    val = url.substring(i + param.length + 2, url.length);
    if ((i = val.indexOf("&")) > -1) {
      val = val.substring(0, i);
    }
  }
  return val;
}

//Checks to see if the page has been refreshed
//If so don't record it
//Props to ConversionRuler
function isNotRefresh()
{
  var nocache = false;
  var allcookies = document.cookie;
  var cookiename = 'ref_' + w.llId + '=';
  var cookievalue = escape(document.location);
  var pos = allcookies.indexOf(cookiename);
  if (pos != -1) 
  {
      var start = pos + cookiename.length;
      var end = allcookies.indexOf(';',start);
      if (end == -1) end=allcookies.length;
      nocache= allcookies.substring(start,end);
      if (nocache != cookievalue) pos = -1;
  }
  if (pos == -1) 
  {
    nocache = (Math.round(Math.random()*100000) + 1);
    document.cookie =cookiename + cookievalue;
    return nocache;
  }
  return false;
}

//Get and/or set a browser cookie
function getBrowserId()
{
  var b = false;
  var allcookies = document.cookie;
  var cookiename = 'b_' + w.llId + '=';
  var pos = allcookies.indexOf(cookiename);
  if(pos != -1)
  {
    var start = pos + cookiename.length;
    var end = allcookies.indexOf(';',start);
    if (end == -1) end = allcookies.length;
    b = allcookies.substring(start,end);
    if (b) return b;
  }
  b = (Math.round(Math.random()*100000) + 1);
  document.cookie = cookiename + b;
  return b;
}
