/******************************************************************************
NAME:
  TKIntLogger.js
DESC:
  -

LAST CHANGE
	2010-04-14 OL: Removed extra / in address for google analytics

TODO:
  - Make sure https works
  - Escape all values
  - Add page type (&ptp=art|dl|uv|pr|ev|dp|dpsis|att|js|ext|uc)
    Article (art)
    Dealer Locator (dl)    Check JS-variables or HTML contents
    Used Vehicles (uv)
    PressRelease (pr)      Pagemeta <meta name="pagetype" content="pressrelease" />
    Event (ev)             Pagemeta <meta name="pagetype" content="event" />
    Dealer page (dp)      Pagemeta <meta name="DealerCountryID" content="GB03a" />
    SIS Dealer page (dpsis) 
    Attachment (att)
    JsFunction (js)
    external link (ext)
    Uncategorised (uc)
    
 - Add live-check (no siteedit scripts) or ip/name check
 - Implement session id                   OK
 - Implement session start time (ticks)   OK, but not used
 - Add page ID
 - Add template type
 - Page and click counter per user (session cookie) 
 - User comeback-rate (sticky-cookie)
 
REPORT IDEAS:
  Follow user (session) Page A -> PageB -> Click 1, Click 2 -> Page B -> Exit + duration
  Target URLs grouping
  Site, all page loads (per period)
  Total loads
  Unique users
  Page loads/user
  Cache hit rate (check document.response status)
  Cookie support stats
  Browser stats
  - weekly analysis
  - Custom IIS log analysis application?
  - use of Google analytics for reporting?


*******************************************************************************/

var TK_LogURL = document.location.protocol + "//sdc.scania.com/img/wt_dcs.gif";
var TK_ACTIVE = true;  // set to true if live target
var TK_SID = null;
var TK_SIDT = null;
var TK_DEBUG = false;

/*
  Page information
    PageType [press, dealer, event, article]
  URL
  TITLE  
    
  clientInfo:
    Resolution
    Browser
    OS
    
   Cookie
    SessionID
*/
function TK_LogEntryClass(EventType, SessionID, ThisURL, ClientResolution, TargetURL, PageType){
  this.EventType = EventType;          // set serverside
  this.SessionID = SessionID;          // set serverside
  this.ThisURL = ThisURL;                   // Will be referer if load (redundant);
  this.ClientResolution = ClientResolution;        // 
  this.TargetURL = TargetURL; // if the click to a javascript or document (no page onLoad log)
  this.PageType = (PageType=="undefined"?"":PageType);
  this.SessionStart=(TK_SIDT!=null?TK_SIDT:0);
}

/*
  Perhaps escape instead.
*/
function convertValueToURLSafe(strValue){
  if(strValue==null || strValue=="") return "";
  else return strValue.replace(/&/g, "$").replace("?", "$$");
}

function TK_DoLog(objLogProps){
  var strProps = "";
  var strFullURL;
  var strParams = ""
  var objImg = new Image();
  if(objLogProps.TargetURL=="undefined") objLogProps.TargetURL = "";
  strParams = "?SID="+objLogProps.SessionID+"&type=" + objLogProps.EventType + "&u=" + convertValueToURLSafe(objLogProps.ThisURL) + "&tu=" + convertValueToURLSafe(objLogProps.TargetURL)+"&pt=" + objLogProps.PageType+"&res=" + objLogProps.ClientResolution;
  strFullURL = TK_LogURL + strParams;
  dalert(strFullURL);
  objImg.src = strFullURL;
  // GA
  try{
    var pageTracker = _gat._getTracker("UA-15797849-1");
    strLogString = window.location.protocol + "//" + window.location.host + "" + window.location.pathname;
    pageTracker._trackPageview(strLogString);
  }
  catch(err){
  	
  }
}

function getParentA(obj){
  while(obj.parentNode !=null){
    if(obj.parentNode.tagName!="undefined"){
      if(obj.parentNode.tagName=="A"){
        return obj.parentNode;
      }
    }
    obj = obj.parentElement;
  }
}

/*
  function anonymous()
  {
  toggleL('toolbox-dropdown');
  }
*/
function getFunctionHead(strHead){
  var strCleaned = strHead;
  if(strHead!=null){
    if(strHead.length>0){
      if(strHead.indexOf("function anonymous")!=-1){ // IE
        strHead = strHead.replace("function anonymous()\n{", "");
        //alert(strHead);
        var iStartIndex = strHead.length-2;
        var iLength = 2;
        if(strHead.substr(iStartIndex, iLength) == "\n}"){
          strHead = strHead.substr(0, iStartIndex);
        }
      }
    	if(strHead.indexOf("function onclick")!=-1){ // IE8
        strHead = strHead.replace("function onclick()\n{", "");
        //alert(strHead);
        var iStartIndex = strHead.length-2;
        var iLength = 2;
        if(strHead.substr(iStartIndex, iLength) == "\n}"){
          strHead = strHead.substr(0, iStartIndex);
        }
    	}
      var iEndIndex = strHead.indexOf(")");
      if(iEndIndex!=-1){
        if(iEndIndex>1){
          if(iEndIndex<strHead.length){
            strHead = strHead.substring(0, iEndIndex+1);
            strHead = strHead.replace("javascript:", "");
          }
        }
      }      
    }
  }
  return strHead;
}

function bIsAttachment(strURL){                                                                                                                                                                         
  var i;                                                                                                                                                                                                
  var aExtensions = new Array(".pdf", ".doc", ".xls", ".ppt", ".zip");                                                                                                                                  
  for(i=0;i<aExtensions.length;i++){                                                                                                                                                                    
    if(strURL.toLowerCase().indexOf(aExtensions[i])!=-1) return true;                                                                                                                                   
  }                                                                                                                                                                                                     
  return false;                                                                                                                                                                                         
}       

function getHostName(){                                                                                                                                                                                 
  var strHostName, iStart, iEnd;                                                                                                                                                                        
  strHostName = window.location.toString();                                                                                                                                                             
  iStart = strHostName.indexOf("://");                                                                                                                                                                  
  if(iStart!=-1){                                                                                                                                                                                       
    iStart+=3;                                                                                                                                                                                          
    strHostName = strHostName.substring(iStart, strHostName.length)                                                                                                                                     
    iEnd = strHostName.indexOf("/");                                                                                                                                                                    
    if(iEnd!=-1){                                                                                                                                                                                       
      strHostName = strHostName.substring(0, iEnd)                                                                                                                                                      
      return strHostName                                                                                                                                                                                
    }                                                                                                                                                                                                   
    else{                                                                                                                                                                                               
      return strHostName                                                                                                                                                                                
    }                                                                                                                                                                                                   
  }                                                                                                                                                                                                     
  else{                                                                                                                                                                                                 
    return ""                                                                                                                                                                                           
  }                                                                                                                                                                                                     
                                                                                                                                                                                                        
}                                                                                                                                                                                                       

/*
  - Click to documents, javascript onclick methods and external links (not same site).

  1. Check if the link links to the same page (#)
  1.1 Check if the link has a onclick eventhandler assigned (other than this)
  1.1.3 Log the event handler and function arguments
  2. Check if the link is an internal link (not logged)
  3. Check if the link is an external link (logged)
  3.1 Log the URL
*/
function TK_LogClick(){
  var strURL = document.location.protocol + "//" + document.location.host + "" + document.location.pathname + "" + document.location.search;
  dalert("TK_LogClick");
  if(this){                                                                                                                                                                                             
    if(this.tagName){                                                                                                                                                                                   
      if(this.tagName == "A"){
        var strClickHandler = this.getAttribute("onclick");
        if(strClickHandler==null && this.onclick!=null){ // FF on docs
          strClickHandler = this.onclick;
        }
        if(strClickHandler!=null){
          strClickHandler += ""; // turn it into a string
          
          if(strClickHandler.length > 0){
            if(strClickHandler.indexOf("TK_LogClick")==-1){
              strClickHandler = getFunctionHead(strClickHandler);
              //alert(strClickHandler)

              var objLogProps = new TK_LogEntryClass("Click", TK_GetSessionID(), TK_GetCurrentPageURL(), TK_GetResolution(), strClickHandler, "js");
              TK_DoLog(objLogProps);
              return;
            }
            else{ // this method is the only clickhandler, log the URL if doc or ext.
              var strHref = this.href;
              if(strHref.length  > 0){
                if(bIsAttachment(strHref)){

                  var objLogProps = new TK_LogEntryClass("Click", TK_GetSessionID(), TK_GetCurrentPageURL(), TK_GetResolution(), strHref, "att");
                  TK_DoLog(objLogProps);                  
                }
                else if(strHref.indexOf(getHostName()) ==-1){ // not same host

                  var objLogProps = new TK_LogEntryClass("Click", TK_GetSessionID(), TK_GetCurrentPageURL(), TK_GetResolution(), strHref, "ext");
                  TK_DoLog(objLogProps);                  
                }
                else{
                  //alert("none of the above!")
                  ; // same host                
                }
              }
            }
          }
        }
        else{ // no click handler at all
          dalert("Where is my clickHandler?"); 
          dalert(this.parentNode.innerHTML);
          dalert(this.onclick);
        }
      }                                                                                                                                                                                                 
    }                                                                                                                                                                                                   
  }
	else{
		dalert("TK_LogClick, this not defined")
	}
  return true;                                                          
}

function TK_GetPageType(){
  var strPT = "uc";
  var i;
  var aMeta = document.getElementsByTagName("META");
  
  for(i=0;i<aMeta.length;i++){
    if(aMeta[i].name=="pagetype"){
      if(aMeta[i].content=="pressrelease"){
        //alert("Press release");
        return "pr";
      }
      else if(aMeta[i].content=="event"){
        //alert("Event");
        return "ev";
      }
    }
    else if(aMeta[i].name=="DealerCountryID"){
      if(aMeta[i].content.length > 4){
        //alert("Dealer Page");
        return "dp";
      }
    }
  }
  if(document.location.pathname.indexOf("/_inc/ShowDealer.aspx")!=-1){
    return "dpsis";
  }
  
  return strPT;
}

function TK_GetResolution(){
  return screen.width+'x'+screen.height;
}

function TK_GetSessionID(){
  var strRet = "0";
  //alert(TK_SID);
  if(TK_SID!=null){
    strRet = TK_SID;
  }
  return strRet;
}

function TK_GetCurrentPageURL(){
  return document.location.protocol + "//" + document.location.host + "" + document.location.pathname + "" + document.location.search;
}

function TK_LogPageLoad(){
  //TK_LogEntryClass(EventType, SessionID, ThisURL, ClientResolution, TargetURL, PageType)
  var objLogProps = new TK_LogEntryClass("Load", TK_GetSessionID(), TK_GetCurrentPageURL(), TK_GetResolution(), "", TK_GetPageType());
  TK_DoLog(objLogProps);
}

/*
  NAME: 
    TK_PageOnLoad
  DESCRIPTION:
    Assigns eventHandlers (ie onclick, and logs the page load)

*/
function TK_PageOnLoad(){
	if(TK_STAGING) return; // set in dcs_tag.js / dwPT WebTrends
	
	dalert("TK_PageOnLoad()");
  //var aAllAHref = document.getElementsByName("A");
  var aAllAHref = document.getElementsByTagName("A");
  
  var i;
  var strDebug = "";
  //window.status = ("found " + aAllAHref.length + " links");
  for(i=0;i<aAllAHref.length;i++){
    objA = aAllAHref[i];
    
    if(objA.onclick==null){                                                                                                                                                                               
      objA.onclick = TK_LogClick                                                                                                                                                                         
    }                                                                                                                                                                                                     
    else if(objA.onmousedown==null){                                                                                                                                                                      
      objA.onmousedown = TK_LogClick                                                                                                                                                                     
    }                                                                                                                                                                                                     
    else if(objA.onmouseup==null){                                                                                                                                                                        
      objA.onmouseup = TK_LogClick                                                                                                                                                                       
    }                                                                                                                                                                                                     
    else{                                                                                                                                                                                                 
      dalert("TK_PageOnLoad: no available click handlers")                                                                                                                                                                                                   
    }     
  }
  TK_SID = GetSession();
  //TK_SIDT = GetSessionDurationMs
  TK_LogPageLoad();
  //alert(GetSessionDurationMs());
}

// Sets cookie values. Expiration date is optional
//
function setCookie(name, value, expire) {
  var cVal = "";
   cVal = name + "=" + escape(value) + (  (expire==null) ? "" : ( "; expires=" + expire.toGMTString() )  );
   document.cookie = cVal;
}

function getCookie(Name) {
   var search = Name + "="
   if (document.cookie.length > 0) { // if there are any cookies
      offset = document.cookie.indexOf(search)
      if (offset != -1) { // if cookie exists
         offset += search.length
         // set index of beginning of value
         end = document.cookie.indexOf(";", offset)
         // set index of end of cookie value
         if (end == -1)
            end = document.cookie.length
         return unescape(document.cookie.substring(offset, end))
      }
   }
	 return null
}

function register(name,value) {
	var today = new Date()
	var expires = new Date()
	expires.setTime(today.getTime() + 1000*60*60*24*365)
	setCookie(name, value, expires)
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
  	dalert("no old load");
    window.onload = func;
    alert(window.onload);
  } 
  else{
  	//alert("oldload already defined:" + oldonload);
    window.onload = new function() {
      if (oldonload){
        oldonload();
      }
      func();
    }
  }
}

function FormSID(){
  return Math.random()*100000000000000000;
}

function GetSessionDurationMs(){
  var strRet=null;
  var SIDT = getCookie("SIDT");
  if(SIDT!=null){
    if( (!isNaN(SIDT)) ){
      return (new Date().getTime()-parseInt(SIDT));
    }
    else{
      dalert("" + SIDT + " is not a number");
      return 0;
    }
  }
  return 0;
}

function dalert(str){
  if(TK_DEBUG){
    alert(str);
  }
	else{
		// window.status = str;
	}
}

function GetSession(){
  var strRet=null;
  var SID = getCookie("SID");
  if(SID==null){
    SID = FormSID();
    setCookie("SID", SID);
    setCookie("SIDT", new Date().getTime());
  }
  return SID;
}

if(TK_ACTIVE){
	dalert("TK_ACTIVE");
	/*
  addLoadEvent(function() {
    TK_PageOnLoad();
  })
  */
}