/*
  Checker objects.
*/

//var serviceBase = "ksours-xp.carsdirect.win/dev/eventLogger/rest/logAdWords.php";
var serviceBase = "webservices2.internetbrands.com/tracker/rest/logAdWords.php";

function trkGetUrlParam(url, field) {
  var re = new RegExp(field + "=([^&]*)(?:&|$)");
  var matches = url.match(re);
  if(matches && matches.length == 2) {
    return matches[1];
  }
  return "";
}

var trkUrlChecker = new Class({
  initialize : function (re, map) {
    this.m_re = re;
    if(!this.m_re) {
      this.m_re = new RegExp("cid=([^&]+)&.*aid=([^&]+)&.*kw=([^&]+)(?:&|$)");
    }

    this.m_map = map;
    if(!this.m_map) {
      this.m_map = {cid:1,aid:2,kw:3}
    }

    var url = window.location.href;
    var matches = url.match(this.m_re);
    if(matches && matches.length == 4) {
      this.cid = matches[this.m_map["cid"]];
      this.aid = matches[this.m_map["aid"]];
      this.kw = matches[this.m_map["kw"]].replace(/%20/g, " ");
      this.gclid = trkGetUrlParam(url, "gclid");
      this.ntc = trkGetUrlParam(url, "ntc");
      this.crid = trkGetUrlParam(url, "crid");
      this.matched = true;
    }
    else {
      this.cid = "";
      this.aid = "";
      this.kw = "";
      this.gclid = "";
      this.ntc = "";
      this.crid = "";
      this.matched = false;
    }
  },

  check : function () {
    return this.matched;
  }
});

var trkNullChecker = new Class({
  check : function() {return false;}
});


var trkCookieBase = new Class({
  initialize : function(name) {
    this.m_name; 
  },
  
  set : function (cval, options) {
    cval = cval.map(encodeURIComponent);
    cval = cval.join("&");
    //console.debug("save", cval);
    Cookie.set(this.m_name, cval, options);
  },

  get : function () {
    var cvalstr = Cookie.get(this.m_name);
    //console.log("load", cval);
    if(cvalstr) {
      cval = cvalstr.split("&");
      cval = cval.map(decodeURIComponent);
    }
    else {
      cval = new Array();
    }
    return cval;
  }
});

/*
  Cookie Handling
*/
var trkCookie = new Class({
  initialize : function() {
    this.m_name = "adentry";
    this.m_duration = 30;

    //new fields need to go to the end.
    this.m_fields = Array("cid", "aid", "kw", "ntc", "ref", "sid", "clid", "crid");
    this.initCookieFields();
  },

  initCookieFields : function () {
    for(var i = 0; i < this.m_fields.length; i++) {
      this[this.m_fields[i]] = "";
    }
    this.m_paramCount = this.m_fields.length;
  },

  update : function (c) {
    if(c.check()) {
      this.load();
      this.setFromChecker(c); 
      this.save();
    }
    else {
      this.load();
      //update the timestamp
      this.save();
    }
  },

  setFromChecker : function (c) {
    if(c.check()) {
      this.cid = c.cid;
      this.aid = c.aid;
      this.kw = c.kw;
      this.ntc = c.ntc;
      this.clid = c.gclid;
      this.crid = c.crid;

      //The session id is really the first click id that we've seen for this 
      //session. 
      if(!this.sid) {
        this.sid = c.gclid;
      }
      this.ref = document.referrer;
      this.isAdwords = true;
    }
  },

  load : function() {
    this.initCookieFields();
    var cval = Cookie.get(this.m_name);
    if(cval) {
      cval = cval.split("&");
      //sanity check the cookie.  
      //allow a bit of slop for older cookies.  For this to work we 
      //always need to add fields to the end of the cookie.
      if(cval.length > this.m_paramCount-1 && cval.length <= this.m_paramCount) {
        cval = cval.map(decodeURIComponent);
        for(var i = 0; i < cval.length; i++) {
          this[this.m_fields[i]] = cval[i];
        }
        this.isAdwords = true;
      }
    }
  
  },

  save : function() {
    var cval = "";
    if(this.isAdwords) {
      cval = new Array();
      for(var i = 0; i < this.m_fields.length; i++) {
        cval.push(this[this.m_fields[i]]);
      }
      cval = cval.map(encodeURIComponent);
      cval = cval.join("&");
      //console.debug("save", cval);
      Cookie.set(this.m_name, cval, {path:"/", duration:this.m_duration});
    }
  }

});

/*
  Channel 
*/
var trkChannel = new Class({
  initialize : function() {
  },

  channel : function(checker, cadw, cdef) {
    var c = new trkCookie();
    c.update(checker);

    if(c.isAdwords) {
      return cadw;
    }
    else {
      return cdef;
    }
  }  
});

//cover functions for the common cases.
function trkSelect(cadw, cdef) {
  return new trkChannel().channel(new trkUrlChecker(), cadw, cdef);
}

function trkLog(re, channel, site, type, value) {
  var cookie = new trkCookie();
  cookie.update(new trkUrlChecker(re));
  if(cookie.isAdwords) {
    var q = {
      sid : cookie.sid,
      clid : cookie.clid,
      cid : cookie.cid,
      aid : cookie.aid,
      kw : cookie.kw,
      ntc : cookie.ntc,
      crid : cookie.crid,
      referrerUrl : cookie.ref,
      channel : channel,
      site : site, 
      eventType : type,
      value : value,
      buster : Math.random()
    };
    /*
    var opt = {
      data : Object.toQueryString(q),
      method : 'get',
      onComplete : function(text) {alert("I finished " + text)},
      onFailure : function() {alert("I am a failure");}
    }
    */
    
    //var A = new Ajax(serviceBase, opt)
    //A.request();
    var I = new Image();
    I.src = window.location.protocol + "//" + serviceBase + "?" + Object.toQueryString(q);
  //  console.log(I.src);
  }
}


function trkASSetup(site, type, value) {
  var re = undefined;
  if (document.all) {
    var el = document.getElementsByTagName("iframe");
    for(var i = 0; i < el.length; i++) {
      if(el[i].src.indexOf('googlesyndication.com') > -1) {
        el[i].onfocus = trkGetLogFunction(re, trkGetUrlParam(el[i].src, "channel"), site, type, value);
      } 
    }
  } 
  else {
//    trkGetLogFunction(re, "1234", site, type, value)();
//    window.onbeforeunload = trkGetPageLogFunction(re, site, type, value);
//    window.addEventListener('mousemove', getMouse, true);
    trkSetupFirefox(trkGetPageLogFunction(re, site, type, value));
  }
}

function trkSetupIE(site, type, value) {
    var el = document.getElementsByTagName("iframe");
    for(var i = 0; i < el.length; i++) {
      if(el[i].src.indexOf('googlesyndication.com') > -1) {
        el[i].onfocus = trkGetLogFunction(re, trkGetUrlParam(el[i].src, "channel"), site, type, value);
      }
    }
}

function trkSetupFirefox(pagecallback) {
  var frame = document.getElementsByTagName("iframe");
  window.onbeforeunload = pagecallback ;
  for(var i = 0; i < frame.length; i++) {
    if(frame[i].src.indexOf('googlesyndication.com') > -1) {
      trkSetupWrapFrame(frame[i]);
    } 
  }
}

function trkSetupWrapFrame(frame) {
  var e = document.createElement('div');
  e.setStyle("display", "inline");
  e.addEvent("mouseover", trkOnMouseover);
  e.addEvent("mouseout", trkOnMouseout);

  $(e).injectBefore(frame);
  $(frame).injectInside(e);
}

function trkOnMouseover() {
  window.trkDiv = this;
}

function trkOnMouseout() {
  window.trkDiv = undefined;
}

function trkGetLogFunction(re, channel, site, type, value) {
  return function() {
    trkLog(re, channel, site, type, value);  
  }
}
 
function trkGetPageLogFunction(re, site, type, value) {
  return function() {
    //var found = false;
    if(window.trkDiv) {
      var ad = window.trkDiv.getElementsByTagName("iframe");
      if(ad.length > 0) {
        trkLog(re, trkGetUrlParam(ad[0].src, "channel"), site, type, value);     
      }
    }
  }
}
