//********************************************************************
//
//              Copyright (c) 2002-2008 MindLab GmbH
//                     All rights reserved.
//
//====================================================================
//
// Project    : netmind
// Filename   : nm_tr_remote.js
//
//====================================================================
//
/**
 * @file
 * This script can be used to implement a pixeltracking on your website
 *
 * @author   $Felix Engemann$
 * @version  $0.0.1$
 * @date     $31.08.2006$

 *@listofchanges cha adaption for postbank help-div 2007/09/07
 *@listofchanges cha adaption for postbank clientStat tracking Pixelhelp-div 2007/11/13
 *@listofchanges cha adaption for postbank clientStat tracking Pixelhelp-div 2007/11/16
 *@listofchanges asc generalisation for netmind 4.0 release 2007/12/10
 
 */
//
//********************************************************************


//********************************************************************
//Session-Management
//********************************************************************
//********************************************************************
//Session-Object 
//********************************************************************

//==========================================================
//Constructor for Session-Object
//==========================================================
function cRemoteSession()
{
	//-----------------------------------------------------
	// members
	//-----------------------------------------------------
	//this is the SessionID returned at the end
	this.m_strNetMindSID = "";
}//end function cRemoteSession()
 
//==========================================================
//method for object Session: returns the Session ID 
//==========================================================
function remotesession_getSessionID()
{
	// get cookie string
	var strCookie = document.cookie
	//split into cookies
	var arCookies = strCookie.split("; ");
	//loop through cookies and get NetMind-Cookie
	var nLoopCount       = 0;
	var strActCookieName = "";        
	var strNetMindSID = "";
	
	while (nLoopCount < arCookies.length) {
	  var strActCookie = arCookies[nLoopCount];
	  var arActCookie = strActCookie.split("=");
	  var strActCookieName = arActCookie[0];        
	  if (strActCookieName == "NETMIND_SID") {
	  	strNetMindSID = arActCookie[1];
	  }
	  nLoopCount++;
	}//end while ((strActCookieName != "NETMIND_SID") && (nLoopCount < arCookies.length))
	this.m_strNetMindSID = strNetMindSID;
	
	return this.m_strNetMindSID;
}//end function session_getSessionID()

//==========================================================
//add methods to class cSession 
//==========================================================
cRemoteSession.prototype.getSessionID = remotesession_getSessionID;



//********************************************************************
//Pixel-Object
//********************************************************************
//Contstructor for Pixel-Object
function cRemotePixel(oConfig)
{
	//-----------------------------------------------------
	// members
	//-----------------------------------------------------
	//pixel object constructor
	//this.m_oImage = new Image();
	this.m_arParameterList = new Array();
	this.m_nParameterCount = 0;

	//Configuration
	this.m_oConfig = oConfig;
	this.m_strPixelURL 				= oConfig.getPixelUrl();
	
	var strPixelpath = oConfig.getTrackingJS();
	this.m_strPixelURLPrefix   		= oConfig.getProtocol()+"://"+oConfig.getPixelServer() +  strPixelpath;
	this.m_strPixelURLSuffix	 	= "";
	
	if (strPixelpath.charAt(0) == "/")
	{
	  this.m_strPixelURLSuffix = strPixelpath.substr(1);
	} else {
	  this.m_strPixelURLSuffix = strPixelpath; 
	}//end else (PixelPath.charAt(0) == "/")
	
}//end function cRemotePixel()

//==========================================================
//methode fuer Objekt Pixel: Fuegt einen Parameter hinzu
//==========================================================
function remotepixel_addParameter(key, value)
{
  arPair = new Array(key, value);
  this.m_arParameterList[this.m_nParameterCount] = arPair;
  this.m_nParameterCount++;
}//end function pixel_add_parameter()

//==========================================================
//method for object Pixel: add affiliate
//==========================================================
function remotepixel_addAffiliate(name)
{
  this.addParameter("affiliate", name)  
}//end function remotepixel_addAffiliate(name)

//==========================================================
//method for object Pixel: add url
//==========================================================
function remotepixel_addUrl()
{
  this.addParameter("url", document.URL);
}//end function remotepixel_addAffiliate(name)

//==========================================================
//method for object Pixel: add referrer
//==========================================================
function remotepixel_addReferrer()
{
  this.addParameter("referrer", document.referrer);
}//end function remotepixel_addAffiliate(name)


//==========================================================
//method for object Pixel: returns the Perm Session ID 
//==========================================================
function remotepixel_addPERMSID()
{
	// get cookie string
	var strCookie = document.cookie
	//split into cookies
	var arCookies = strCookie.split("; ");
	//loop through cookies and get NetMind-Cookie
	var nLoopCount       = 0;
	var strActCookieName = "";        
	var strNetMindPERMSID = "";
	
	while (nLoopCount < arCookies.length) {
	  var strActCookie = arCookies[nLoopCount];
	  var arActCookie = strActCookie.split("=");
	  var strActCookieName = arActCookie[0];        
	  if (strActCookieName == "NETMIND_PERMSID") {
	  	strNetMindPERMSID = arActCookie[1];
	  }
	  nLoopCount++;
	}//end while ((strActCookieName != "NETMIND_PERMSID") && (nLoopCount < arCookies.length))
	if(strNetMindPERMSID) {
        	this.addParameter("NETMIND_PERMSID", strNetMindPERMSID);
        }
}//end function session_getSessionID()


//==========================================================
//method for object Pixel: add referrer
//==========================================================


function remotepixel_addParamToUrl(strUrl, arParameterList)
{
	if (strUrl.indexOf ("?") == -1)
		strUrl = strUrl + "?";
		
	for(i=0; i<arParameterList.length; i++)
	{
		if (i>0) strUrl += "&";
		strUrl += escape(arParameterList[i][0])+"="+escape(arParameterList[i][1]);
	}//end for(i=0; i<this.m_arParameterList.length; i++) 
	//now set URL on Pixel
	
	return strUrl;
}//end function remotepixel_addAffiliate(name)

//==========================================================
//methode fuer Objekt Pixel: senden des Pixels
//==========================================================
function remotepixel_sendData(oRemoteSession)
{
	var bCookieTracking = this.m_oConfig.isCookieTracking();
	

	if (bCookieTracking) {
		//-----------------------------------------------------
		// Cookie Tracking Variante
		//-----------------------------------------------------	 
		var strUrl = this.m_strPixelURL;
		strUrl = remotepixel_addParamToUrl(strUrl,this.m_arParameterList);
		var oTrackingImg = new Image();
		oTrackingImg.src = strUrl;
	} else {
  		var strSID = oRemoteSession.getSessionID();
   		
  		if (strSID != "" ) {
  			strSID = "-snm-" + strSID + "-enm-";
  		}
 
        var strUrl = this.m_strPixelURLPrefix+strSID+this.m_strPixelURLSuffix;
 
		strUrl = remotepixel_addParamToUrl(strUrl,this.m_arParameterList);

		var oHead = document.getElementsByTagName("head")[0];
		var aSidScript = document.getElementById ('sidscript');
		if (aSidScript) { // Already exists
		  for (var j = 0; j < aSidScript.length; j++) {
		    oHead.removeChild(aSidScript[j]);
		  }//end for (var j = 0; j < aMetatag.length; j++)   
		}
		oScript = document.createElement('script');
		oScript.id = 'sidscript';
		oScript.type = 'text/javascript';
		oScript.src = strUrl;
		
		//-----------------------------------------------------
		// Set an Evant Handler to Set the Valid Variable and
		// the SessionID
		//-----------------------------------------------------
		//oScript.addEventListener('load',remotepixel_setCookie,false);
		oHead.appendChild(oScript);
		//alert(oScript.src);
	} // end else if (bCookieTracking)
}//end function remotepixel_sendData()

//==========================================================
//method setSidReady 
//==========================================================
function remotepixel_setCookie()
{
  //alert ("remotepixel_setCookie");
  //-----------------------------------------------------
  // this function is used as an event Handler
  // for the loading of the SID containing Javascript
  // the function does nothing but checking the
  // Javascript Variable containing the 
  //-----------------------------------------------------
}//end function remotesession_waitSidReady()

//==========================================================
//methode fuer Objekt Pixel: auslesen der techdaten
//==========================================================
function remotepixel_getTechData () {
  
  //--------------------------------------------------------
  // variables for general settings
  //--------------------------------------------------------
  var javaOK    = "unknown";
  var cookiesOK = "unknown";
  var browsLang = "unknown";
  var availheight = screen.availHeight;
  var availwidth  = screen.availWidth;
  var colordepth  = screen.colorDepth + " bit";
  var height      = screen.height;
  var width       = screen.width;
  var title       = document.title;
  
  //--------------------------------------------------------
  // variables for plugins
  //--------------------------------------------------------
  var flashPlugin     = "-";
  var flashVersion    = "0";
  var directorPlugin  = "-";
  var wmplayerPlugin  = "-";
  var realplayerPlugin= "-";
  var quicktimePlugin = "-";
  var adobe_svgPlugin = "-";
  var adobe_pdfPlugin = "-";
  
  var agt = navigator.userAgent.toLowerCase();
  var ie  = (agt.indexOf("msie") != -1);
  //accept only higher than MSIE 4
  //otherwise the detectIE() function would not work
  if(ie) {
    ie  = (agt.indexOf("msie 4") == -1) && (agt.indexOf("msie 3") == -1);
  }//end if(ie)
  
  var win = ((agt.indexOf("win")!=-1) || (agt.indexOf("32bit")!=-1));
    
  //--------------------------------------------------------
  // Java and Cookies
  //--------------------------------------------------------
  if (navigator.javaEnabled()==true){javaOK="yes"}else{javaOK="no"}
  
  //--------------------------------------------------------
  //-- cookieEnabled only works in MSIE.
  //--------------------------------------------------------
  if ((navigator.cookieEnabled) && (navigator.cookieEnabled==true)) {cookiesOK="yes"} else {cookiesOK="no"}
  
  //--------------------------------------------------------
  // language
  //--------------------------------------------------------
  if (navigator.language)
    browsLang = navigator.language;
  
  //--------------------------------------------------------
  // Plugins
  // 
  // SVG and Quicktime are not certified Plugins and cause a warning
  // in MSIE 7. Because of this fact those two plugins are not detected.
  //--------------------------------------------------------
  if (ie && win) {   
    directorPlugin = detectIE("SWCtl.SWCtl.1");
    flashPlugin = detectIE("ShockwaveFlash.ShockwaveFlash.1");
    realplayerPlugin = detectIE("rmocx.RealPlayer G2 Control.1");
    //wmplayerPlugin = detectIE("MediaPlayer.MediaPlayer.1"); 
    adobe_pdfPlugin = detectIEAcrobat("Acrobat Reader");
  }//end if (ie && win) 

  else {
    nse = ""; 
    for (var i=0;i<navigator.mimeTypes.length;i++) 
    nse += navigator.mimeTypes[i].type.toLowerCase();
    directorPlugin = detectNS(nse, "application/x-director");
    flashPlugin = detectNS(nse, "application/x-shockwave-flash");
    realplayerPlugin = detectNS(nse, "audio/x-pn-realaudio-plugin");
    //wmplayerPlugin = detectNS(nse, "application/x-mplayer2");     
    adobe_pdfPlugin = detectNS(nse, "application/pdf");  }

	
  //save paramters into pixel
  this.addParameter("nm_java", javaOK);
  this.addParameter("nm_cookies", cookiesOK);
  this.addParameter("nm_screen", width + "x" + height);
  this.addParameter("nm_colordepth", colordepth);
  this.addParameter("nm_plugin_flash", flashPlugin);
  this.addParameter("nm_plugin_director", directorPlugin);
  //this.addParameter("nm_plugin_wmplayer", wmplayerPlugin);
  this.addParameter("nm_plugin_realplayer", realplayerPlugin);
  this.addParameter("nm_plugin_acroread", adobe_pdfPlugin);
  this.addParameter("nm_title", title);
	

}//end function pixel_getTechData ()

//==========================================================
//methode zum Auslesen der metatags
//==========================================================
// setzen eines leeren Metatags auf "-"
function remotepixel_getMetTags () {
	

	var aMetatag = this.m_oConfig.m_aMetatag;
	
	//Save metatags to track into pixel-parameter-list. validation with regexp match
	var strMetaTags = "";
	var rec_req = "";
	var rec_trg = "";
	var rec_trgname = "";
	var rec_prodid = "";
	for (var i = 0; i < document.getElementsByTagName('meta').length; i++) {
		for (var j = 0; j < aMetatag.length; j++) {
			var re = new RegExp(WildToReg(aMetatag[j]));
			if (document.getElementsByTagName('meta')[i].getAttribute('name')) {
				if ( document.getElementsByTagName('meta')[i].getAttribute('name').match(re) ) {
				    var metaname = document.getElementsByTagName('meta')[i].getAttribute('name');
						if(metaname == this.m_oConfig.m_recommendation_request) {
								var rec_req = document.getElementsByTagName('meta')[i].getAttribute('content');
						} else if (metaname == this.m_oConfig.m_recommendation_target) {
								var rec_trg = document.getElementsByTagName('meta')[i].getAttribute('content');
						} else if (metaname == this.m_oConfig.m_recommendation_targetname) {
								var rec_trgname = document.getElementsByTagName('meta')[i].getAttribute('content');
						} else if (metaname == this.m_oConfig.m_recommendation_prodid) {
								var rec_prodid = document.getElementsByTagName('meta')[i].getAttribute('content');
						} else if (document.getElementsByTagName('meta')[i].getAttribute('content')) {
							this.addParameter(document.getElementsByTagName('meta')[i].getAttribute('name'), document.getElementsByTagName('meta')[i].getAttribute('content'));
						} else {
							this.addParameter(document.getElementsByTagName('meta')[i].getAttribute('name'), "-");
						}							
				} // end if document.getElementsByTagName('meta')[i].getAttribute('name').match(re
			} // end if (document.getElementsByTagName('meta')[i].getAttribute('name'))
		}//end for (var j = 0; j < aMetatag.length; j++)
	}//end for (var i = 0; i < document.getElementsByTagName('meta').length; i++)
	if(rec_req.toLowerCase() == "true") {
	   sendRCRequest(this.m_oConfig.m_strPixelProtocol, this.m_oConfig.m_strPixelServer, this.m_oConfig.m_recommendationPath, rec_prodid, rec_trg, rec_trgname);
	}
	
}// end method remotepixel_getMetTag

//==========================================================
//methode zum Auslesen der per Hash angehängten Parameter
//==========================================================
// setzen eines leeren Hashparameter auf "-"
function remotepixel_getHashParameter () {

	var aParamList = this.m_oConfig.m_aHashParameter;

	var strLoc=(document.location+""); 
	var nPos=strLoc.indexOf("#");
	if (nPos != -1) {
		var strHashQs=strLoc.substring(nPos+1, strLoc.length);
		aParams =  remotepixel_SplitParams(strHashQs);
		//Save metatags to track into pixel-parameter-list. validation with regexp match
		var strHashParam = "";
		for (var j = 0; j < aParamList.length; j++) {
			if ( aParams[aParamList[j]] ) {
				this.addParameter(aParamList[j],aParams[aParamList[j]]);					
			} // end if( aParams[aParamList[j]] )
		}//end for (var j = 0; j < aMetatag.length; j++)
	} // end if nPos != -1)
}// end method remotepixel_getMetTag

//==========================================================
//remotepixel_SplitParams
//==========================================================
function remotepixel_SplitParams(params) {
	var result=[];
	var pairs=params.split("&");
	for (var i=0; i < pairs.length; i++) {
		var kv=pairs[i].split("=");
		if (kv[1] && kv[1] != "")
			result[kv[0]]=kv[1];
		else 
			result[kv[0]]="-";			
	}
	return result;
}


//==========================================================
//Definition of Prototypes
//==========================================================

//methoden zur Klasse hinzufuegen
cRemotePixel.prototype.addParameter = remotepixel_addParameter;
cRemotePixel.prototype.addAffiliate = remotepixel_addAffiliate;
cRemotePixel.prototype.addUrl       = remotepixel_addUrl;
cRemotePixel.prototype.addReferrer  = remotepixel_addReferrer;
cRemotePixel.prototype.addPERMSID  = remotepixel_addPERMSID;
cRemotePixel.prototype.sendData     = remotepixel_sendData;
cRemotePixel.prototype.getTechData  = remotepixel_getTechData;
cRemotePixel.prototype.getMetTags   = remotepixel_getMetTags;
cRemotePixel.prototype.getHashParameter	= remotepixel_getHashParameter;

//==========================================================
// Acrobat
//==========================================================
function detectIEAcrobat(name) {

  var acrobat=new Object();
  if (window.ActiveXObject) {
    for (x=2; x<10; x++) {
      try {
        oAcro=eval("new ActiveXObject('PDF.PdfCtrl."+x+"');");
        if (oAcro) {
          return 'yes';
        }
      }
      catch(e) {}
    } 

    try {
      oAcro4=new ActiveXObject('PDF.PdfCtrl.1');
      if (oAcro4) {
        return 'yes';
      }
    }
    catch(e) {}

    try {
      oAcro7=new ActiveXObject('AcroPDF.PDF.1');
      if (oAcro7) {
        return 'yes';
      }
    }
    catch(e) {}
  }  return 'no';		
}//end function detectIEAcrobat(name)

//==========================================================
// IE Plugins
//==========================================================

function detectIE(ClassID) { 

  try {
    new ActiveXObject(ClassID);
    return 'yes'; 
  }
  
  catch(e) {
    return 'no';
  }   
}//end function detectIE(ClassID)

//==========================================================
// Netscape and Firefox Plugins
//==========================================================
function detectNS(strMimetypes, ClassID) { 
  if (strMimetypes.indexOf(ClassID) != -1) 
    if (navigator.mimeTypes[ClassID].enabledPlugin != null) 
      return 'yes'; 
  return 'no';

}//end function detectNS(strMimetypes, ClassID)


//==========================================================
// Convert Wildcard to RegEx
//==========================================================
function WildToReg(str) {

  s = "";
  for (i = 0; i < str.length; i++) {
    c = str.charAt(i);
    switch(c) {
      case '*':
        s = s + ".*";
        break;
      case '?':
        s = s + ".";
        break;
                
        case '(': case ')': case '[': case ']': case '$':
        case '^': case '.': case '{': case '}': case '|':
        case '\\':
          s = s + "\\";
          s = s + c;
          break;
        
        default:
          s = s + c;
          break;
      }//end switch(c)
    }//end for (i = 0; i < str.length; i++)
    s =  "^" + s + "$";
   return s;
}//end function WildToReg(str)  

//==========================================================
//function Pixel-Instanz anlegen
//==========================================================
function doPixelInstance(oEvent) {
	oNMConfig      = new cConfigPixel();
	oNMRemotePixel = new cRemotePixel(oNMConfig);
	//Send PartnerName as parameter?
	if(oNMConfig.getAutoParams()) {
		//Send Url as parameter?
		if (oNMConfig.getSendUrl()) {
			oNMRemotePixel.addUrl();
		}//end if (SendUrl)
		//Send Hash Parameter as parameter?
		if (oNMConfig.getSendUrlHash()) {
			oNMRemotePixel.getHashParameter();
		}//end if (SendUrlHash)
		//Send referrer as parameter?
		if (oNMConfig.getSendReferrer()) {
			oNMRemotePixel.addReferrer();
		}//end if (SendReferrer)
		if(oNMConfig.getSendMetatags()) {
			oNMRemotePixel.getMetTags();
		}
		if(oNMConfig.getSendTech()) {
			oNMRemotePixel.getTechData();
		}
		if(oNMConfig.getSendPERMSID()) {
			oNMRemotePixel.addPERMSID();
		}
	} // end autoparams
	if(oNMConfig.getAutoSend()) {
		oNMRemotePixel.sendData(oNMRemoteSession);
	}
} // end function doPixelInstance


//======================================================================================
// Load Time Execution
//======================================================================================

oNMRemoteSession = new cRemoteSession();
//doPixelInstance("");

//addEventListener()  element.addEventListener('<event>', 'function', false)     Mozilla, Safari, Opera
//attachEvent()       element.attachEvent('on<event>', 'function')               MSIE (nicht IE Mac)

if( window.addEventListener ) {
	//alert ("window.addEventListener");
	window.addEventListener('load',doPixelInstance,false);
} else if( document.addEventListener ) {
	//alert ("document.addEventListener");
	document.addEventListener('load',doPixelInstance,false);
} else if (window.attachEvent) {
	//alert ("window.attachEvent");
	window.attachEvent('onload', doPixelInstance);
}	else if (document.attachEvent) {
	//alert ("document.attachEvent");
	document.attachEvent('onload', doPixelInstance);
} else {
  alert('Hallo');
	doPixelInstance("");
}

function sendRCRequest(prot,server,file,prod,trg,trgname) {
		var oHead = document.getElementsByTagName("head")[0];
		var aSidScript = document.getElementById ('rcscript');
		if (aSidScript) { // Already exists
		  for (var j = 0; j < aSidScript.length; j++) {
		    oHead.removeChild(aSidScript[j]);
		  }//end for (var j = 0; j < aMetatag.length; j++)   
		}
		oScript = document.createElement('script');
		oScript.id = 'rcdscript';
		oScript.type = 'text/javascript';
		strUrl = prot + "://" + server + "/" + file + "?prod_id=" + prod + "&trg=" + encodeURI(trg) + "&trgname=" + trgname; 
    //alert(strUrl);
		oScript.src = strUrl;
		oHead.appendChild(oScript);
}

function trackDownload(e) {
		var targ;
		if (!e)
  	{
  		var e=window.event;
  	}
		if (e.target)
  	{
  		targ=e.target;
  	}
		else if (e.srcElement)
  	{
  		targ=e.srcElement;
  	}
		if (targ.nodeType==3) // defeat Safari bug
  	{
  		targ = targ.parentNode;
  	}
		var tnsrc;
	  tref=targ.href;
    oNMRemotePixel.addParameter ("nm_download", tref);
          
    // Information an netmind Tracker übermitteln
    // Das oNMRemoteSession exisitert in jedem Fall
    oNMRemotePixel.sendData (oNMRemoteSession);
}
