/**
File     : auto.js                                             
Author   : Nils Chr. Hofgaard Dahl <nils@onsite.no>                                         
Date     : 20050228
Copyright: OnSite Solutions AS http://www.onsite.no                                      
Comment  :                                                 
------------------------------------------------------------
SVN properties                                              
------------------------------------------------------------
 $LastChangedDate$                                           
 $Revision: 25 $                                                  
 $Author: nilschd $                                                    
 $HeadURL: https://svn.onsite.no/lp3/autotagger/auto.js $#                                                  
 $Id: auto.js 25 2007-05-14 05:59:17Z nilschd $                                                        
------------------------------------------------------------
 */
var _lpAutoVersion="2.19 ($Revision: 25 $)";
var _eventRegister = null;
var _loaded=false;

if(lpAutoConfig.bootsTrapped == null) {
    lpAutoConfig.bootsTrapped=false;
}
//-----------------------------------------------------------------------------------------
if(lpAutoConfig.browser == null) {
    lpAutoConfig.browser = _detectBrowser();
}
//debug mode
if ( lpAutoConfig.debugMode == null ) {
 if ( window.location.href.indexOf("lpDebug=") != -1 ) { lpAutoConfig.debugMode = true; }
 else { lpAutoConfig.debugMode = false; }
}
// Bootstrap 
if(!lpAutoConfig.bootsTrapped && window.location.href.indexOf('lpBootstrap') != -1 ) {
    var l = window.location.href; var s = l.indexOf('lpBootstrap=')+"lpBootstrap".length;
    var e = l.indexOf('&',s)-1; if(e <= -1) {e = l.length} var bootsTrapUrl = l.substr(s+1,e);
    if(!lpAutoConfig.bootsTrapped && bootsTrapUrl.indexOf('http://')== 0) {
        if(lpAutoConfig.debugMode) { alert("LP bootstrapped to: "+bootsTrapUrl); }
        lpAutoConfig.bootsTrapped=true;
        _loaded=true; //ok, this script is done
	document.write('<scr' + 'ipt language="javascript" src="'+bootsTrapUrl+'"></scr'+'ipt>');
    }
}
//-----------------------------------------------------------------------------------------
function _lpInit() {
    if(_loaded){return true;}
    _loaded=true;
    var sm = new Date();
    try {
	if(lpAutoConfig==null) {

	    return;
	}
    } catch(e) {
	alert("LPAuto error:\n- no lpAutoConfig object supplied");
	return;
    }

    //opera v>=9.x and safari v>=2will not use this method 
    if(  (lpAutoConfig.browser == 'opera' && (lpAutoConfig.operaCompat == null || !lpAutoConfig.operaCompat)) || lpAutoConfig.browser == 'safari1' ) {
	_tagHrefs(); 
    }
    else if( lpAutoConfig.registerMode == null || lpAutoConfig.registerMode == 'registerOnclick') {
	if(document.onclick) { _pushMethod("document","onmousedown","_cEvent()"); }
	else { 
	    try { document.addEventListener("mousedown",_cEvent,true);	}
	    catch(e) {	document.onmousedown= _cEvent; 	}	
	}
    }
    else if (lpAutoConfig.registerMode == 'registerLinks') {
	for(var i=0; i < document.links.length;i++) {
	    if( (document.links[i].onclick==null || document.links[i].onclick=='') && document.links[i].href!='#' && document.links[i].href!='') {
		document.links[i].onclick=_cEvent;
	    }
	}
    }
    else if (lpAutoConfig.registerMode == 'tagLinks') {
       _tagHrefs()
    }

    if(lpAutoConfig.pageViewUrl != null){
        var url=lpAutoConfig.pageViewUrl+"u="+(new Date).getTime()*(Math.random()*100);
	if(lpAutoConfig.browser == 'opera') {
	    var img = document.createElement("IMG");
            img.id="vgo";
            img.style.height="1px";
            img.style.width="1px";
	    img.style.border="0px";
            img.src=url;
            document.body.appendChild(img);
	}
	else {
	 document.writeln('<div style="display:none"><img border="0"  id="vgo" height="1px" width="1px" src="'+url+'"></div>');
	}
    }
    //    alert("ok");    
    if( window.location.href.indexOf("lpDebug=2") != -1) {
	alert("LP v"+_lpAutoVersion+" setup done, approx. time used "+( ((new Date()).getTime()-sm.getTime())/1000 )+"s");
    }
    
   
   return true;
}
//-----------------------------------------------------------------------------------------
function _tagHrefs() {
    for(var i=0; i < document.links.length;i++) {
 	if(
	   (lpAutoConfig.excludeUrls != null && lpAutoConfig.excludeUrls.length > 0 && !_testExclusion(document.links[i].href)) &&
	   ((lpAutoConfig.registerModeAllowOnClick==null || !lpAutoConfig.registerModeAllowOnClick)?(document.links[i].onclick==''||document.links[i].onclick==null):true) &&
	   //document.links[i].href.indexOf("#") == -1 &&
	   _getAttribute(document.links[i],"lpNoTag") == -1 ||
	   document.links[i].href.toLowerCase().indexOf("javascript") == -1 &&
	   document.links[i].href.toLowerCase().indexOf("mailto") == -1 
	   ) {
	    var link = _researchLink(document.links[i],lpAutoConfig);
	    //	    if(link) {if(lpAutoConfig.debugMode) { document.links[i].href="javascript:void(_debugLPUrl('"+unescape(link)+"'));";}else {	document.links[i].href = unescape(link); }}
	    if(link) {if(lpAutoConfig.debugMode) { document.links[i].href="javascript:void(_debugLPUrl('"+unescape(link)+"'));";}else {	document.links[i].href = link; }}
	}
    }

}
//-----------------------------------------------------------------------------------------
function _cEvent(e) {
    e = _parseEvent(e); //Cross browser manip	
    if( 
       (e.type != 'click' && e.type != 'mousedown') || 
       //e.target.onclick != null || 
       _getAttribute(e.target,"lpNoTag") == 1 ||
       e.target.href==null ||  
       e.target.href=='' ||  
       e.target.href=='#' || 
       e.target.href==document.location+'#' ||
       (e.target.href==document.location && !lpAutoConfig.debugMode)|| //hm this one is a bit uncertain
       e.target.href.match(/mailto/i) || 
       e.target.href.match(/javascript\:/i) || 
       //       e.target.href.match(/.+\(.*\)\;*/) ||
       e.target.href.match(/^[a-z0-9\_\:A-Z]+\([^\)]*\)\;*$/) ||
       (lpAutoConfig.excludeUrls != null && lpAutoConfig.excludeUrls.length > 0 && _testExclusion(e.target.href))  
       ) {
	return true; // should work on all browser
    }

    var link = _researchLink(e.target,lpAutoConfig);

    if(link) {
	return _goUrl(e.target,link);
    }
    return true;
}
//-----------------------------------------------------------------------------------------
function _goUrl(a,uri) {
    if(lpAutoConfig.debugMode) { uri="javascript:void(_debugLPUrl('"+unescape(uri)+"'));"; a.target=''; }
    if(lpAutoConfig.browser == 'ie7' || lpAutoConfig.browser == 'ie6') { // taking care of IE buggy handling when links are like this: <a href="http://www.foobar.no">www.foobar.no</a>
	var linkText = a.innerHTML; 
	a.href=uri;
        // IE fix to avoid that links like this <a href="http://www.foobar.com">www.foobar.com</a> becomes corrupt
	//if(a.href == a.innerHTML) { a.innerHTML=linkText; }
	if(a.href == a.innerHTML || linkText.substr(0,4).toLowerCase() == 'http' ) { a.innerHTML=linkText; }
	//a.innerHTML=linkText;
    }
    else {a.href=uri;}
    return true;
}
//-----------------------------------------------------------------------------------------
function _testExclusion(uri) {
    var exclude = false;
    for(var i=0; i <lpAutoConfig.excludeUrls.length;i++) {
	var r = uri.match(lpAutoConfig.excludeUrls[i]);
	if(r != null) {
	    exclude=true;
	    break;
	}
    }
    return exclude;
}
//-----------------------------------------------------------------------------------------
function logAction(action) {
    
    if(action['toUrl']==null || action['toUrl']=='') {
	alert("LP auto error:\n-Missing toUrl in logAction call.");
	return false;
    }
    
    if(lpAutoConfig.excludeUrls != null && lpAutoConfig.excludeUrls.length > 0 && _testExclusion(action['toUrl'])) {
	return false;
    }  

    if(action['category']==null || action['category']=='') {
	action['category']= (lpAutoConfig.defaultCategory!=null?lpAutoConfig.defaultCategory:'unknown');
    }
    if(action['logType']==null || action['logType']=='' || lpAutoConfig.logtypeUrls[action['logType']]==null ||lpAutoConfig.logtypeUrls[action['logType']]=='' ) {
	action['logType']= (lpAutoConfig.defaultLogtype!=null?lpAutoConfig.defaultLogtype:'ego');
    }

    var clickAttributes = new Array();
    if(lpAutoConfig.siteId != null) {
	if(lpAutoConfig.siteId == 'auto') { clickAttributes.push('siteId='+(_getHostParts(location.href)).join('.')); }
	else { clickAttributes.push('siteId='+lpAutoConfig.siteId); }
    }
    
    if(action['fromUrl']) {
	action['afu'] =  action['fromUrl'];
	action['fromUrl'] = null;
    }
    else if(action['fromUrl'] == null) {action['afu']=location.href; }
    if(action['afu'].substr(0,4).toLowerCase() == 'http') { // some proxies and cliens get confused by some extra https?://
	action['afu'] = action['afu'].replace(/^https?\:\/\//,'');
    }
    //    action['fromUrl'] = action['fromUrl'].replace(/\//g,'\\');
    var excludes = {toUrl:true,category:true,logType:true};
    var dd = '';
    for(elm in action) {
	if(excludes[elm]!=null) continue;
	clickAttributes.push(elm+"="+escape(action[elm]));
    } 

    //need a rnd number to avoid caching
    var uniq = (Math.floor(Math.random()*1000)*Math.floor(Math.random()*1000))+''+(new Date()).getTime();
    clickAttributes.push("u3="+uniq);

    var goUri=  lpAutoConfig.logtypeUrls[action['logType']]+'/'+action['category']+(clickAttributes.length>0?';'+clickAttributes.join(";"):'')+'/'+action['toUrl'];
    
    if( lpAutoConfig._logImageIdx == null) {  lpAutoConfig._logImageIdx = 0; lpAutoConfig._logImageCnt = 0; }

    if(  lpAutoConfig._logImageIdx >= lpAutoConfig._logImageCnt-5 && lpAutoConfig._logImageCnt < 50) { // we want to make sure that we have enough image to "fire" on request
	    //since IE is slow on createElement, we create 5 at the time
	    var i=0;
	    while( i++ < 5 ){ 
		var img = document.createElement("IMG");
		img.id="_LPgoImage"+lpAutoConfig._logImageCnt;
		img.style.height="0px";
		img.style.width="0px";
		img.style.border="0px";
		lpAutoConfig._logImageCnt++;
		document.body.appendChild(img);
	    }
    }

	
    if(lpAutoConfig.debugMode) {_debugLPUrl(goUri);return false;}
    document.getElementById('_LPgoImage'+lpAutoConfig._logImageIdx).src=goUri;
    lpAutoConfig._logImageIdx++;
    if( lpAutoConfig._logImageIdx >= 50 )
	lpAutoConfig._logImageIdx=0;
    return true;

}
//--------------------------------------------------------------------------------------
function getGoUrl(aHrefObj) {
    if( typeof(aHrefObj) != 'object' || aHrefObj.tagName.toLowerCase() != 'a' ) {
	alert("LP Error:\n- parameter to getGoUrl must be an A tag!");
	return false;
    }
    return  _researchLink(aHrefObj, lpAutoConfig);
}
//--------------------------------------------------------------------------------------
function setGoUrl(aHrefObj) {
    var url = getGoUrl(aHrefObj);
    if(url!=false) {
	aHrefObj.href=url;
	return true;
    }
    return false;
}
//--------------------------------------------------------------------------------------
function _goFormUrl(uri,target) {
    try {
	var goForm = document.createElement("FORM");
	goForm.action=uri;
	//		goForm.method="get"
	if(target!=null) { goForm.target=target;	}
	document.body.appendChild(goForm);
	goForm.submit();
    } catch(e) {
	if(lpAutoConfig.debugMode)
	    alert("LPAuto error 'Could not create goForm':"+e);
	return true; // not ok
    }
    return false; //ok
}
//-----------------------------------------------------------------------------------------
function _debugLPUrl(uri) {
    var dd = {};
    dd["lpAutoVersion"] =  "v"+_lpAutoVersion+" [browser: "+lpAutoConfig.browser+"]";
    for(lp in lpAutoConfig.logtypeUrls) {if(uri.indexOf(lpAutoConfig.logtypeUrls[lp]) > -1) {dd["lpGoUrl"]= lpAutoConfig.logtypeUrls[lp];}}
    
    var clickAttribs = uri.slice(dd["lpGoUrl"].length+1, uri.lastIndexOf("http")-1).split(';');
    dd["lpCategory"] = clickAttribs[0];
    for(var i=1; i < clickAttribs.length;i++) {
	var d = clickAttribs[i].split('=');
	if(d.length == 2) 
          dd['lp'+d[0]]=d[1];
    }
    dd["lpToUrl"] = unescape(uri.slice(uri.lastIndexOf("http"), uri.length));
    dd["lpFromUrl"] = document.location;
    var lpEntry=_getCookie(lpEntryConfig.cookieName);
    dd["lpEntry"] = (lpEntry?lpEntry:'n/a');
    dd["lpGoUrl"] = "\n"+uri+"\n";
    //    dd["lpSiteId"] = (lpAutoConfig.siteId?lpAutoConfig.siteId:'n/a');
    var d = "";	for(s in dd) {if(s.substring(0,2) == 'lp') {d+=s+" : "+dd[s]+"\n";}}
    alert(d);
}
//-----------------------------------------------------------------------------------------
function _researchLink(node,cfg) {
    if(_getAttribute(node,'lpNoTag')==1) {
	return false;
    }

    for(elm in cfg.logtypeUrls) {
	if( (''+node).substr(0,cfg.logtypeUrls[elm].length) == cfg.logtypeUrls[elm]) {
	    return ;
	}
    }

    var tmpNode = node;
    var goUri = null;
    var goCat = null;
    var goSubCat = null;
    var subCatCnt = 0;
    var tagDef = {
      lpSubCategory:'lpSubCategory',
      lpCategory:'lpCategory',
      lpSubLevelLimit:9,
      lpLogtype:'lpLogtype',
      lpDelim:'/',
      lpAttributeDelim:';',
      lpCatDelim:'_',
      lpClassPrefix:'',
      lpClassLogTypePrefix:''
    };

    //do we have custom tags to merge into tagDefs?
    if(cfg.customTags != null) {
      for(elm in cfg.customTags) {
	if(tagDef[elm]!=null && cfg.customTags[elm]!=null && cfg.customTags[elm]!='') {
	  tagDef[elm]=cfg.customTags[elm];
	}
	//alert(elm+": "+tagDef[elm]);      
      }
    }
    
    
    while( (goUri==null||goCat==null) && tmpNode!=document) {
      var foundSub = false;
      // no need to look for sub when we have a goCat 
      if(goCat == null && subCatCnt < tagDef['lpSubLevelLimit']) { 
	var atr = _getAttribute(tmpNode,tagDef['lpSubCategory']);
	//	var t=atr;
	atr = _parseAttribute(atr,cfg.categoryTranslations,tagDef['lpClassPrefix'],'subCategories');
	//alert(t+"="+atr+" "+tmpNode.id+" "+tmpNode.nodeName);
	if(atr != null) {
	    goSubCat=(goSubCat!=null?atr+tagDef['lpCatDelim']+goSubCat:atr);
	    foundSub = true;
	    subCatCnt++;
	}
      }
      
      if(goCat == null && !foundSub) {
	  var atr = _getAttribute(tmpNode,tagDef['lpCategory']);
	  atr = _parseAttribute(atr,cfg.categoryTranslations,tagDef['lpClassPrefix'],'top');
	  if(atr!=null) {
	      goCat=atr;
	      if(goSubCat != null) {
		  goCat+=tagDef['lpCatDelim']+goSubCat;
	      }
	  }
      }
      
      if(goUri == null) {
	var atr = _getAttribute(tmpNode,tagDef['lpLogtype']);
	// need function to parse lpLogType_ego
	atr = _parseAttribute(atr,cfg.categoryTranslations,tagDef['lpClassLogTypePrefix'],'logType');
	if(atr!=null && cfg.logtypeUrls[atr] != null && cfg.logtypeUrls[atr]!='') {
	    goUri=atr;
	}
      }
      tmpNode = tmpNode.parentNode;
    } //end while goUri==null

    if(goUri == null) { goUri = cfg.defaultLogtype; }
    if(goCat == null) {
      if(goSubCat != null) {
	goCat=(goCat!=null?goCat+tagDef['lpCatDelim']:'')+goSubCat;
      }
      if(goCat == null && cfg.defaultCategory != null) {
	goCat=  cfg.defaultCategory;
      }

    }
    goCat = goCat.replace(/\s/g,tagDef['lpCatDelim']);
    //goCat = 'category='+goCat;
    //ok, we don't want to tag this link somewhere lp_noTag was defined
    if(goCat.indexOf('noTag') > -1) { return false; }

    //extra attributes
    var clickAttributes = new Array();
    if(lpAutoConfig.siteId != null) {
	//_resolveReferrer
    	if(lpAutoConfig.siteId == 'auto') { clickAttributes.push('siteId='+(_getHostParts(location.href)).join('.')); }
	else { clickAttributes.push('siteId='+lpAutoConfig.siteId); }
    }

    if( lpAutoConfig.trackClickElement && lpAutoConfig._clickSource != null && lpAutoConfig._clickSource !='') {
	var metaName=_parseAttribute (lpAutoConfig._clickSource.toLowerCase(),lpAutoConfig.categoryTranslations,'','clickSource');
	clickAttributes.push('cs='+(metaName!=null?metaName:lpAutoConfig._clickSource));
    }
    if(cfg.plugins != null) {
	for(var i=0;i<cfg.plugins.length;i++) {
	    try {
		var result = eval(cfg.plugins[i]+'()');
		if(result != null) {clickAttributes.push((cfg.plugins[i]+"="+result));}
	    } catch(e) {
		alert("LP auto error:\nCould not execute plugin :'"+cfg.plugins[i]+"'\n"+e.toString());
		return false;
	    }
	}
    }
    
    if( clickAttributes.length > 0) {    
	goCat+=tagDef['lpAttributeDelim']+clickAttributes.join(tagDef['lpAttributeDelim']); //+tagDef['lpAttributeDelim']; 
    }

    return cfg.logtypeUrls[goUri]+tagDef['lpDelim']+goCat+tagDef['lpDelim']+node;
}
//-----------------------------------------------------------------------------------------
function _parseAttribute (atr,categoryTranslations,lpClassPrefix,type) {
    if(atr == null) return null;

    var classes = atr.split(' ');

    if(categoryTranslations == null && lpClassPrefix==null) { return atr; }
    else if( categoryTranslations == null || categoryTranslations[type] == null && lpClassPrefix!=null && lpClassPrefix !='') {
       for (var i=0;i<classes.length;i++) {	
	   //         if( atr.substr(0,lpClassPrefix.length)==lpClassPrefix) { 
         if( classes[i].substr(0,lpClassPrefix.length)==lpClassPrefix) { 
          return classes[i].substr(lpClassPrefix.length); 
         }
       }
       return null;
    }

    if(categoryTranslations[type] == null){ return null;}

    for (var i=0;i<classes.length;i++) {
	if (categoryTranslations[type][classes[i]]) {
	    return categoryTranslations[type][classes[i]];
	}
	else if (classes[i].match(lpClassPrefix)) {
	    
	  var lpRawCat = classes[i].substr(lpClassPrefix.length);
	  if( categoryTranslations[type][lpRawCat]) {return categoryTranslations[type][lpRawCat];}
	}

	for(k in categoryTranslations[type]){
            if(k.substr(0,7) == 'regexp:') {
		var re = k.substr(7);
		if(classes[i].match(re)){
		    return  categoryTranslations[type][k];
		}
		
	    }
	}

    }
    return null;
}
//-----------------------------------------------------------------------------------------
function _getAttribute(elm,key) {
    
    var keys = new Array();
    if(key.indexOf(',') !=-1) {keys = key.split(',');}
    else {keys.push(key);}
    var atr=null;
    for(kk in keys) {
	if( (lpAutoConfig.browser == 'ie7' || lpAutoConfig.browser == 'ie6') && keys[kk] == 'class') {keys[kk]= 'className';}
	try {atr = elm.getAttribute(keys[kk]);} catch(e) { atr=null;}
	if(atr!=null && atr!='') {break;}
    }
    if(atr!=null && atr=='') {
	atr=null; //opera fix, actually getAttribute should return '' and not null
    }
    return atr;
}
//-----------------------------------------------------------------------------------------
function _parseEvent(e) {
    if(e == null) e = window.event;
    var ev = new Object();
    ev.type=e.type;
    if(e.target) ev.target=e.target;
    else if(e.srcElement) ev.target = e.srcElement;

    if( lpAutoConfig.trackClickElement != null && lpAutoConfig.trackClickElement ) {
	lpAutoConfig._clickSource = ev.target.nodeName;
    }

    if (ev.target.nodeType == 3) // Safari bug
	ev.target = ev.target.parentNode;
    while(ev.target != null && ev.target.tagName  != null && ev.target.tagName.toLowerCase() != 'a') {
	ev.target = ev.target.parentNode;
    }

    return ev;
}
//-----------------------------------------------------------------------------------------
function _pushMethod(elmId,event,method) {
	var elm=null;
	var elmEvent=null;
	
	if(elmId == 'window') {
		elm = window;
		elmEvent  = elmId+'.'+event
	}
	else {
		elm = document.getElementById(elmId);  
		elmEvent = elm.id+'.'+event;
	}
	try {
		var eventSrc = eval(elmEvent);  
    } catch(e) { 
		if(lpAutoConfig.debugMode)
			alert("LPAuto eventregister error:\n"+elmEvent+"\ne: "+e.toString());  
	}

	if(_eventRegister == null) {
		_eventRegister= new Array();
	}
	if(_eventRegister[elmId] == null) {
         _eventRegister[elmId] = new Array();
  } 
  
  if(_eventRegister[elmId][event] == null) {
	_eventRegister[elmId][event] = new Array();
	if(eventSrc) {
	    var eventStr = ""+eventSrc;
	    var startIdx = eventStr.indexOf("{");
	    var endIdx   = eventStr.lastIndexOf("}");
            var eventBody= eventStr.substring(startIdx+1,endIdx);

            //if(eventBody.indexOf('return') > -1) {
		//eventBody=eventBody.replace(/(\r|\n)/g,' ');
		//eventBody =' alert(\'hei\');'+eventBody;
		//eventBody = new Function("alert(\'hei\');");
		
	    //}
   	    _eventRegister[elmId][event].push(eventBody);
     }	
  }

  _eventRegister[elmId][event].push(method);
  try {
      eval(elmEvent+" = new Function(\"_executeEvent('"+elmId+"','"+event+"')\");"); 
      //val(elmEvent+" = _executeEvent('"+elmId+"','"+event+"');");
  } catch(e) {
	  //if(lpAutoConfig.debugMode)
	  //	  alert("LPAuto eventregister error:\n"+elmEvent+" = _executeEvent('"+elmId+"','"+event+"');"+"\ne: "+e.toString());  
		  
  }
//alert(window.onload);
}
//-----------------------------------------------------------------------------------------
function _executeEvent(elmId,eventType) {

    if(_eventRegister==null||_eventRegister[elmId]==null||_eventRegister[elmId][eventType]==null) return;

    for(var i=0; i < _eventRegister[elmId][eventType].length;i++) {
	try {
	    //    if(lpAutoConfig.debugMode)
	    //	alert("hm:"+_eventRegister[elmId][eventType][i]);
	    var func = new Function(_eventRegister[elmId][eventType][i]);
	    func();
	    //eval(_eventRegister[elmId][eventType][i]);
	} catch(e) {
	    if(lpAutoConfig.debugMode && !lpAutoConfig.bootsTrapped)
		alert("LPAuto eventregister execute:\n"+_eventRegister[elmId][eventType][i]+"\n"+e);
	}
    }

}


function _removeMethod(elmId,event,method) {
    if(_eventRegister==null||_eventRegister[elmId]==null||_eventRegister[elmId][event]==null) return;
    for(var i=0; i < _eventRegister[elmId][event].length;i++) {
	if(_eventRegister[elmId][event][i]!=null && _eventRegister[elmId][event][i] == method) {
	    _eventRegister[elmId][event][i]=null;
	    return;
	}
    }
}
//-----------------------------------------------------------------------------------------
function _detectBrowser() {
	var b='';
	var ua = navigator.userAgent.toLowerCase();
	if(window.opera != null) { b="opera"; if(window.opera.version() != null) {b+=parseInt(window.opera.version());}	}
	else if(ua.indexOf("safari") != -1) { b="safari";var s=ua.indexOf('applewebkit/')+12;var v=parseFloat(ua.substring(s,ua.indexOf('(',s)));b+=(v>411?2:1);}
	else if(ua.indexOf("msie 7") != -1) { b="ie7";}
	else if(ua.indexOf("msie 6") != -1) { b="ie6";}
	else if(ua.indexOf("msie 5") != -1) { b="ie5";}
	else if(ua.indexOf("netscape") != -1) { b="netscape";}
	else if(ua.indexOf("firefox") != -1) { b="mozilla";}
	else if(ua.indexOf("gecko") != -1) { b="mozilla";}
	return b;
}
//-----------------------------------------------------------------------------------------
// LP Entrypoint
//-----------------------------------------------------------------------------------------
function _getHostParts (host) {
  var start = host.indexOf('://');
  if (start==-1) {return false;}
  var end  = host.indexOf('/', start+3);
  if (end==-1) {end = host.length;}
  var hostExtract = host.substring(start+3,end);
  var hostParts=hostExtract.split('.');
  return hostParts;
}
//-----------------------------------------------------------------------------------------
function _resolveReferrer(referrer, config) {
  if (!referrer) {return false;}
  if (lpEntryConfig.exluded) {
    for (var i=0; i<lpEntryConfig.exluded.length; i++) {
      if (referrer.indexOf(lpEntryConfig.exluded[i])!=-1) {return false;}
    }
  }

  if (lpEntryConfig.included) {
    var included = false;
    for (var i=0; i<lpEntryConfig.included.length; i++) {
      if (referrer.indexOf(lpEntryConfig.included[i])!=-1) {included = true;}
    }
    if (!included) {return false}
  }

  var hostParts = _getHostParts(referrer);
  var thisHost  = _getHostParts(location.href);
  if (hostParts.join('.') == thisHost.join('.')) {return false;} // Same host - bailing out


  var referrerValue = '';

  if (lpEntryConfig.entryBase=='basic' || lpEntryConfig.entryBase=='domain') {
    if (hostParts.length > 3 && hostParts[hostParts.length-2].length < 4) { // Most likely, this is a host ala [something.]www.domain.co.uk or similar
      if (lpEntryConfig.entryBase=='basic') {referrerValue = hostParts[hostParts.length-3];}
      else {referrerValue = hostParts[hostParts.length-3] +'.'+hostParts[hostParts.length-2] +'.'+hostParts[hostParts.length-1];}
    }
    else {
      if (lpEntryConfig.entryBase=='basic') {referrerValue = hostParts[hostParts.length-2];}
      else {referrerValue = hostParts[hostParts.length-2] +'.'+hostParts[hostParts.length-1];}
    }
  }
  else { referrerValue = hostParts.join('.'); }
  return referrerValue;
}
//-----------------------------------------------------------------------------------------
function _getCookie(name) {
  var sPos=document.cookie.indexOf(name+'=');
  if (sPos==-1) {return false}
  var ePos=document.cookie.indexOf(';', sPos);
  if(ePos==-1) {ePos=document.cookie.length}
  return unescape(document.cookie.substring(sPos+name.length+1, ePos));
}
//-----------------------------------------------------------------------------------------
function _setCookie(name, value, domain, expires, debug) {
  if (expires>0) {
    var tmp = new Date;
    var now = new Date(tmp.getTime()+(expires*1000));
    expires = '; expires='+now.toGMTString();
  }
  else {expires=''}
  
  var cookie = name + '='+escape(value)+expires+'; domain='+domain;
  if(debug) {alert("Set-cookie: "+cookie);}
  document.cookie = cookie;
}
//-----------------------------------------------------------------------------------------
// Init block
//-----------------------------------------------------------------------------------------
if(window.lpEntryConfig==null) {
	window.lpEntryConfig = new Object();
}
var lpEntryConfig = window.lpEntryConfig;
lpEntryConfig.cookieName='LPENTRY';
if (!lpEntryConfig.debug)          {lpEntryConfig.debug=false;}
if (!lpEntryConfig.entryBase)    {lpEntryConfig.entryBase='basic';}
if (!lpEntryConfig.overridable)  {lpEntryConfig.overridable='yes';}
if (!lpEntryConfig.cookieTtl)      {lpEntryConfig.cookieTtl=0;}
if (!lpEntryConfig.cookieDomain) {
	var hostParts = _getHostParts(location.href);
	lpEntryConfig.cookieDomain='.'+hostParts[hostParts.length-2]+'.'+hostParts[hostParts.length-1];
}

if (lpEntryConfig.overridable=='yes' || !_getCookie(cookieName)) {
  var entryPoint = _resolveReferrer(eval("document.ref"+"errer"), lpEntryConfig);
  if (entryPoint) {
	  _setCookie(lpEntryConfig.cookieName, entryPoint, lpEntryConfig.cookieDomain, lpEntryConfig.cookieTtl, lpEntryConfig.debug);
  }
}

if(lpAutoConfig.browser != 'opera') {_lpInit();}
try { if(window.onload) {_pushMethod("window","onload","_lpInit()"); } else {window.onload = _lpInit;}
} catch(e) {if(lpAutoConfig.debugMode) alert("LPAuto Error at init:\n"+e); window.onload = _lpInit; }
// -->

