/**
File     : auto.js                                             
Author   : Nils Chr. Hofgaard Dahl <nils@onsite.no>                                         
Date     : 20050228
Copyright: OnSite Solutions AS http://www.onsite.no                                      
------------------------------------------------------------
 */
var _lpAutoVersion="2.54";
var _eventRegister = null;
var _loaded=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; }
}

//-----------------------------------------------------------------------------------------
function _lpInit() {
    if(_loaded){return true;}
    _loaded=true;
    if(lpAutoConfig.debugMode) 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') {
      
        try { 
            _attachEvent(document,"mousedown",_cEvent,false);
        }
        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( window.location.href.indexOf("lpDebug=2") != -1) {
	alert("LP v"+_lpAutoVersion+" setup done, approx. time used "+( ((new Date()).getTime()-sm.getTime())/1000 )+"s");
    }
    //console.log("LP Init done!");
   return true;
}
//-----------------------------------------------------------------------------------------
function _lpPostInit() {
    if(lpAutoConfig.debugMode) var sm = new Date();
    if(!_loaded){ _lpInit(); }
    if(lpAutoConfig.pageViewUrl != null){
	var pr = _execPlugins(lpAutoConfig,'vgo');
        logAction({
		'toUrl':lpAutoConfig.pageViewUrl,
                'afu':_getAFUrl(),
		'logType':'vgo',
                'category':(lpAutoConfig.pageViewCategory!=null?lpAutoConfig.pageViewCategory:'pageview')+';'+(pr!=null?pr:'')
                 });
    }

    if(lpAutoConfig.entryClickLogtype!=null) {
	var ref=document.referrer.toString();
	if(ref!=null && ref != '') {
            var c=_getTopDomain(location.href);
            var r=_getTopDomain(ref);
            if(c==null || c != r) {
                logAction({
                        'toUrl':lpAutoConfig.pageViewUrl,
                        'fromUrl':ref,
                        'logType':lpAutoConfig.entryClickLogtype,
                        'category':(lpAutoConfig.entryClickCategory!=null?lpAutoConfig.entryClickCategory:'entryclick'),
                       '_ise':1, //for the parser to be able to identify this as an entry click
                       '_iseToUrl':_getAFUrl()
                        });
            }
        }
    }
    if( window.location.href.indexOf("lpDebug=2") != -1) {
	alert("LP v"+_lpAutoVersion+" post init done, approx. time used "+( ((new Date()).getTime()-sm.getTime())/1000 )+"s");
    }
}
//-----------------------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------
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) &&
	   _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 = link; }}
	}
    }

}
//-----------------------------------------------------------------------------------------
function _cEvent(e) {
    //console.log("_cEvent");
    if(lpAutoConfig.debugMode) {
        lpAutoConfig.debugLinkParseTime = new Date().getTime();
    }
    e = _parseEvent(e); //Cross browser manip	
    if( 
       (e.type != 'click' && e.type != 'mousedown') || 
       _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(/^[a-z0-9\_\:A-Z]+\([^\)]*\)\;*$/) ||
       (lpAutoConfig.excludeUrls != null && lpAutoConfig.excludeUrls.length > 0 && _testExclusion(e.target.href))  
       ) {
        if(lpAutoConfig.debugMode) {
            lpAutoConfig.debugLinkParseTime = ( (new Date().getTime()) - lpAutoConfig.debugLinkParseTime );
        }
	return true; // should work on all browser
    }

    if(e.target.href != null && lpAutoConfig.plugins != null && lpAutoConfig.plugins['click']!=null) {
        _execClickPlugins(e.target.href);
    }
    
    var link = _researchLink(e.target,lpAutoConfig);

    if(link) {

        //if( lpAutoConfig.browser == 'ie6'  && lpAutoConfig.utfInUrl ){
        //      link=fixUtf8InIE(link);
        //    }

	var res =  _goUrl(e.target,link);
        if(lpAutoConfig.debugMode) {
            lpAutoConfig.debugLinkParseTime = ( (new Date().getTime()) - lpAutoConfig.debugLinkParseTime );
        }
        return res;
    }
    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;
	if(a.href == a.innerHTML || linkText.substr(0,4).toLowerCase() == 'http' ) { a.innerHTML=linkText; }
    }
    else {a.href=uri;}

    if(lpAutoConfig.browser == 'ie6' && lpAutoConfig.utfInUrl ){
        a.href=fixUtf8InIE(a.href);
    }
    
    return true;
}
//-----------------------------------------------------------------------------------------
//This method is for buggy utf-8 support in ie6.
function fixUtf8InIE(uri){
    var goUri = uri.slice(0, uri.lastIndexOf("http"));
    var url = uri.slice(uri.lastIndexOf("http"), uri.length);
    url = url.substring(7, url.length);
    if( url.indexOf('%') < 0) {
        url = escape(escape(url));
    }
    else {
        url = escape(url);
    }
    url = goUri+"http://"+url;
    return(url);
}
//-----------------------------------------------------------------------------------------
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'] =  _getAFUrl(action['fromUrl']);
	action['fromUrl'] = null;
    }
    else if(action['fromUrl'] == null && action['afu']!='') {action['afu']=_getAFUrl(); }
    var excludes = {toUrl:true,category:true,logType:true};
    var dd = '';
    for(elm in action) {
	if(excludes[elm]!=null || action[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("_u"+uniq.substring(0,1)+"="+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 images 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;
	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"] = (dd['lpafu']!=null?dd['lpafu']:document.location);
    var lpEntry=_getCookie(lpEntryConfig.cookieName);
    dd["lpEntry"] = (lpEntry?lpEntry:'n/a');
    dd["lpGoUrl"] = "\n"+uri+"\n";
   
    dd["lp Link setup time"] = (lpAutoConfig.debugLinkParseTime/1000)+'s';
   
    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];
	}
      }
    }
    
    
    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']);
	atr = _parseAttribute(atr,cfg.categoryTranslations,tagDef['lpClassPrefix'],'subCategories');
	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']);
    //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) {
	var pr = _execPlugins(cfg,goUri);
	if(pr != null) {clickAttributes.push(pr);}
    }
    
    if(lpAutoConfig.logAFU!=null && lpAutoConfig.logAFU){
        clickAttributes.push('afu='+_getAFUrl());
    }

    if( clickAttributes.length > 0) {    
	goCat+=tagDef['lpAttributeDelim']+clickAttributes.join(tagDef['lpAttributeDelim']); //+tagDef['lpAttributeDelim']; 
    }
    
    return cfg.logtypeUrls[goUri]+tagDef['lpDelim']+goCat+tagDef['lpDelim']+node;
}
//-----------------------------------------------------------------------------------------
function _execPlugins(cfg,logType) {
    if( cfg.plugins != null && cfg.plugins[logType] != null) {
	var result = new Array();
        for(var i=0;i<cfg.plugins[logType].length;i++) {
	    try {
		var plugRes = eval(cfg.plugins[logType][i]+'(lpAutoConfig)');
		if(plugRes != null) {
		    for(elm in plugRes) {result.push(elm+"="+plugRes[elm]);}
		}
	    } catch(e) {
		alert("LP auto error:\nCould not execute plugin :'"+cfg.plugins[logType][i]+"'\n"+e.toString());
		return null;
	    }
	}
	
	return result.join(';');
    }
    return null;
}
//-----------------------------------------------------------------------------------------
function _execClickPlugins(url) {
    //   alert(url);
    url = url.substr(url.toString().lastIndexOf("http"),url.length);

    for(var i=0; i < lpAutoConfig.plugins['click'].length;i++) {
        try {
            eval(lpAutoConfig.plugins['click'][i]+'(lpAutoConfig,url)');
        } catch(e) {
            alert("LP auto error:\nCould not execute plugin :'"+lpAutoConfig.plugins['click'][i]+"'\n"+e.toString());
            return null;
        }
    }
}
//-----------------------------------------------------------------------------------------
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( 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) {
    for(var kk=0; kk < keys.length;kk++) {
	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 (e.pageX || e.pageY) 	{
	lpAutoConfig.clickX = e.pageX;
	lpAutoConfig.clickY = e.pageY;
    }
    else if (e.clientX || e.clientY) 	{
	lpAutoConfig.clickX = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
	lpAutoConfig.clickY = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }

    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 _attachEvent(obj,event,func,capture) {
    if (obj.addEventListener) {
        obj.addEventListener(event,func,capture);
    }
    else if (obj.attachEvent) {
        obj.attachEvent('on'+event,func)
                }
    else {
        _pushMethod(obj,'on'+event, func);
    }
}
//-----------------------------------------------------------------------------------------
function _pushMethod(elmId,event,method) {
    var elm=null;
    var elmEvent=null;

    if(elmId == 'window') {
	elm = window;
	elmEvent  = elmId+'.'+event
	
    }
    else if (elmId = 'document'){
        elm = document;
	elmEvent  = elmId+'.'+event;
    }
    else {
	elm = document.getElementById(elmId);
	if(!elm) return; //XXX - Instead of crashing the script
        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();
    }
    _eventRegister[elmId][event].push(method);
    try {
        var code = elmEvent+" = new Function(['e'],\"if(!e) e=window.event;  _executeEvent('"+elmId+"','"+event+"',e)\");";
        eval(code);
    } catch(e) {
	//if(lpAutoConfig.debugMode)
	//	  alert("LPAuto eventregister error:\n"+elmEvent+" = _executeEvent('"+elmId+"','"+event+"');"+"\ne: "+e.toString());  	
    }
}
//-----------------------------------------------------------------------------------------
function _executeEvent(elmId,eventType, e) {
    if(_eventRegister==null||_eventRegister[elmId]==null||_eventRegister[elmId][eventType]==null) return;

    for(var i=0; i < _eventRegister[elmId][eventType].length;i++) {
	try {
	    _eventRegister[elmId][eventType][i](e);
	} 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("chrome") != -1) { b='chrome'}
    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;
}
//-----------------------------------------------------------------------------------------
function _getAFUrl(afu) {
    if(afu == null) afu=location.href;
     if(afu.substr(0,4).toLowerCase()== 'http') { 
         afu=afu.replace(/^https?\:\/\//,'');
     }
     if(afu.charAt(afu.length-1) == '/') {
         afu=afu.substring(0,afu.length-1);
     }
     afu=afu.replace(/\//g,'a47'); // &#27; = '/';
     afu=afu.replace(/\;/g,'a59'); // &#59; = ';'
     return escape(afu);
}
//-----------------------------------------------------------------------------------------
// 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 _getTopDomain(host) {
    var h = _getHostParts(host);
    var td = new Array();
    for(var i=1;i < h.length;i++) {
        td.push(h[i]);
    }
    return td.join('.');
}
//-----------------------------------------------------------------------------------------
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(lpAutoConfig.noEntryCookie){
        _setCookie(lpEntryConfig.cookieName, entryPoint, lpEntryConfig.cookieDomain, (new Date(1)), lpEntryConfig.debug);
    }
    else {
        if (entryPoint) {
	    _setCookie(lpEntryConfig.cookieName, entryPoint, lpEntryConfig.cookieDomain, lpEntryConfig.cookieTtl, lpEntryConfig.debug);
        }
    }
}
_lpInit();
_attachEvent(window,'load',_lpPostInit,false);
// -->