({
	name:"Cookie",
	set:function(n,v,c,dm){var d,e,domain="";if(dm){domain="domain="+dm;}if(c){d=new Date();d.setTime(d.getTime()+c*24*60*60*1000);e="; expires="+d.toGMTString()}document.cookie=escape(n)+"="+v+e+"; path=/;"+domain},
	get:function(n){var e,b,p,c=document.cookie;p=n+"=";b=c.indexOf(";"+" "+p);if(b==-1){b=c.indexOf(p);if(b!=0)return ""}else b+=2;e=c.indexOf(";",b);if(e==-1)e=c.length;return unescape(c.substring(b+p.length,e))},
	unset:function(n){return this.set(n,"",1,"")},
	init:function(){window[this.name]=this}
}).init();

function __getCookie(_cid)
{ 
	if (document.cookie.length > 0)
	{ 
		var begin = document.cookie.indexOf(_cid+"=");
		if (begin != -1)
		{ 
			begin += _cid.length+1;
			var end = document.cookie.indexOf(";", begin);
			if (end == -1) end = document.cookie.length;
			return unescape(document.cookie.substring(begin, end));
		}
	}
	return "no_cookie";
}

function recodeCategories(categories){
	var result="";
	var catList = categories.split(",");
	for(var i=0;i<catList.length;i++){
		var curCat = catList[i].replace(/^\s+/, "").replace(/\s+$/, "").toLowerCase();					
		result+=escape(curCat)+",";
	}
	if(result.charAt(result.length-1)==",")result = result.substring(0,result.length-1);
	//it will replace all special chars by encoded values i.e. & by %26 etc.
	return result;
}

function __getMetaData(tag)
{
	if(!document.getElementsByTagName) return;
	
	var metaColl = document.getElementsByTagName('meta');
	var content = 'no_category';
	for (var i=0; i < metaColl.length; i++)
	{
		var attr_name = metaColl[i].getAttribute('name');
		if(!attr_name) continue;
		if(attr_name.toLowerCase() == tag)
		{ 
			content = metaColl[i].getAttribute('content');
			break;
		}
	}
	return content;
};

// 	Generates Guid - Global Unique Identifier
function __newGuid()
{
    var g = "";
    for(var i = 0; i < 32; i++)
    	g += Math.floor(Math.random() * 0xF).toString(0xF) + (i == 8 || i == 12 || i == 16 || i == 20 ? "-" : "");
    return g;
};

function _onunload() {
	Cookie.unset("ca_cat_sent");
	Cookie.unset("visitted_set");
};
window.attachEvent ? window.attachEvent("onbeforeunload", _onunload) : window.addEventListener("unload", _onunload, false);

adapt_cn_start = new function()
{  
	this.categorySent = 0;
	this.eraseStatisticCookie=false;
	this.failover=false;
	// techworld.idg.se params
	var _cid = "user_carnegie";
	var _fid = "carnegie_login";
	var _aid = "carnegie";
	
	// basic configuration
	var BASE_URL = 'http://pec3.adaptlogic.com/';
	var ROOT = __newGuid();
	var DOMAIN_HASH = "142812208";
	
	// for load control
	var _peload = 100;
	var _maloadprob=Math.floor(Math.random()*101);

	// for data fetching
	var response_timeout = 4000;//ms
	var frequency = 50;//ms

	// for image fetching
	var currentRequest = null;
	var timer = null;
	var params = null;
	var reload_pause = 400;//ms
	
	//	Google Analytics configs
	var is_GA_enabled = false;	// or false
	var _segmentation_cookie;

	function __requestContent() 
	{
		/*var _user = __getCookie(_cid);
		if (_user == 'no_cookie') {
			//	doesn't make sense to send request - no cookie detected
			showFailoverContent();
			return;
		}
		*/
		var meta = __getMetaData("keywords");
		meta=recodeCategories(meta);
		var cb = 'adapt_dataRequest_cn_start.callback';
		var url = BASE_URL + 'Adapt-0.1/adapt/personalizeList?user=server_cookie&customer=' + _aid + '&function=' + _fid
		if (!adapt_cn_start.categorySent && meta && meta != "no_category"){
			url+='&category='+escape(meta);
		}
		url+= '&callback=' + cb;
		adapt_dataRequest_cn_start.send( url );
		
		var delay = response_timeout * 0.8;//	when 80% of time is out
		setTimeout(function() {
			__waitForResponse(adapt_dataRequest_cn_start);
		}, delay);
	}

	function __waitForResponse(_req){
		if (new Date().getTime() > _req.start_time + response_timeout) {
			_req.abort();
			if (!_req.ready){
	    		showFailoverContent();
	    	}
			return;
		} else {
			if (_req.aborted){
				showFailoverContent();
			 	return;
			}
			if (_req.ready) return;
			
			setTimeout(function() {
				__waitForResponse(_req);
			}, frequency);
		}
	}
	
	function showFailoverContent(){
		var div = document.getElementById(ROOT);
		div.innerHTML='<div class="cb fc Teaser_X3 box box-Nav"><div class="boxHead fc"><h2>Logga in</h2></div>'+
		'<div class="boxBody fc" style="height: auto;"><div class="boxInnerBody fc">'+
		'<a href="http://www.carnegie.se/sv/Logga-in1/?=/login/control/adaptlogic.htm?=/login/control/adaptlogic.htm">'+
		'<img src="http://www.carnegie.se/DocGlobal/online_white_90.jpg" title="" style="border: medium none ;" class="Image"/></a>'+
		'<h3>Internettjänster</h3><div><p>Kunder till Carnegie f&aring;r tillg&auml;ng till v&aring;ra internettj&auml;nster: Carnegie Online och Carnegie Edge.</p></div></div>'+
		'<div class="fill" style="height: 17px;"/><div class="Footer"><a href="http://www.carnegie.se/sv/Bli-kund-2/?=/login/control/adaptlogic.htm">Bli kund</a>'+
		'<span class="VerticalBar"/><a href="http://www.carnegie.se/sv/Logga-in1/?=/login/control/adaptlogic.htm"><span class="LoginButtonLink noLink">'+
		'<img src="http://www.carnegie.se/Temp/ImagePack/IT2073723674.gif" alt="Logga in"/></span></a></div></div></div>';

    	// make wrapping DIV visible
		div.style.display = 'block'; 		
		div.style.visibility = 'visible'; 
	}

	//	sending request for image and setting callback
	function __sendRPC( url, callback ) 
	{
		if (currentRequest) {
			clearTimeout(timer);
		}
		currentRequest = new Image();
		currentRequest.src = url;
		setTimeout(callback, reload_pause);
	}
	
	//	callback function used when image is loaded completely
	function __readResponse() {
		if (!currentRequest.complete) {
			timer = setTimeout(__readResponse, reload_pause);
			return;
		}
		//	are params ready ?
		if (params) {
			if (params.length < 2) {	// at least 2 params required
				return;
			}
		} else {
			return;
		}
		// detecting image's size
		if (currentRequest.width < 5 || currentRequest.height < 5) {
			//	no image or too small image - nothing to do
			
		} else {
			//	fetching params
			var divToUpdate = params[0];
			var articleId = params[1];
			
			var img = document.createElement("img");
			img.src = currentRequest.src;
			img.title = "";
			img.style.border = "medium none";
			img.className = "Image";
			var link = divToUpdate.getElementsByTagName("a")[0];
			link.appendChild( img );
		}
	}

	//	setting GA's custom segmentation
	function __setGASegmentation(){
		if (!is_GA_enabled || adapt_cn_start.categorySent) {
			return;
		}
		
		var domainName = document.domain.replace("www.","");
		var cookieValue = DOMAIN_HASH+"."+_segmentation_cookie;
		var cookieCheckValue = "ga."+domainName+"."+cookieValue;
		if(document.cookie && document.cookie.length > 0 && document.cookie.indexOf("__utmv=")>-1 
			&& Cookie.get(domainName) && document.cookie.indexOf(cookieCheckValue) > -1) {
			return;
		}
		
		Cookie.set("__utmv",cookieValue, 365*2,"."+domainName);		
		Cookie.set(domainName,cookieCheckValue,365*2);
	}

	this.serverResponse = function(data) {
		var failover = false;
	    if (!data || !data.list || adapt_dataRequest_cn_start.aborted){
			failover = true;
	    }
	    this.failover = failover;
	    
	    if(!failover){
			//	creating custom segmentation for GA by setting cookie
			if (data.pc){
				switch (data.pc) {
					case 1:
						_segmentation_cookie = "Adapted_group";
						break;
					case 2:
						_segmentation_cookie = "Control_group";
						break;
					default:
						//	do nothing
						break;
				}
			}
		}

		var gaSuffix = "";
		
		//**********************************************************************************
		//		Single_Push
		//**********************************************************************************
	    var div = document.getElementById(ROOT);	
		var sub_array = null;
		eval( 'sub_array = ' + data.list[0] );
		if(sub_array.mp==0)
			failover = true;
		if(!failover){
			var articleIdVal = sub_array.articleId;
				
			var mpVal = Math.round(sub_array.mp*100);
			if(mpVal>10)
				mpVal = Math.round(mpVal / 10);
			if(mpVal>9) 
				mpVal = 1;
			else
				mpVal = "0."+mpVal;
			gaSuffix = "?=/"+mpVal+"/login/adapted/adaptlogic.htm";
			contentSelector = "online"==articleIdVal ? 1 : 2;
		}else{
			gaSuffix = "?=/login/control/adaptlogic.htm";
		}
		
	    var containerDiv = document.createElement("div");
	    containerDiv.className="cb fc Teaser_X3 box box-Nav";
	    
	    var headerDiv = document.createElement("div");
	    headerDiv.className="boxHead fc";
	    var headerText = document.createElement("h2");
	    headerText.innerHTML = failover ? "Logga in" : (contentSelector==1?"Logga in till Carnegie Online":"Logga in till Carnegie Edge")
	    headerDiv.appendChild(headerText);
	    containerDiv.appendChild(headerDiv);
	    
		var teaserDiv = document.createElement("div");
		teaserDiv.className = "boxBody fc";
		teaserDiv.style.height="auto";
		
		var innerDiv = document.createElement("div");
		innerDiv.className="boxInnerBody fc";
		
		var link = document.createElement("a");
		link.href = (failover ? "http://www.carnegie.se/sv/Logga-in1/?=/login/control/adaptlogic.htm" : (contentSelector==1? "http://www.carnegie.se/online" : 
			"http://nordic.carnegie.se/Nordic/login.aspx") + gaSuffix);
		innerDiv.appendChild(link);		
		
		var articleTitle = document.createElement("h3");
		articleTitle.innerHTML = failover ? "Internettj&auml;nster" : (contentSelector==1?"Carnegie Online":"Carnegie Edge")
		innerDiv.appendChild(articleTitle);
		
		var descriptionBlock = document.createElement("div");
		var description = document.createElement("p");
		description.innerHTML = failover ? "Kunder till Carnegie f&aring;r tillg&aring;ng till v&aring;ra internettj&auml;nster: Carnegie Online och Carnegie Edge." : 
			(contentSelector==1?"H&auml;r f&aring;r du st&auml;ndig tillg&aring;ng till dina investeringar, analyser och nyheter, prenumerationsprodukter och &ouml;vrig marknadsinformation.":
				"Ta del av &ouml;ver 10 000 analyser och aktuella estimat f&ouml;r mer &auml;n 300 nordiska f&ouml;retag.");
		descriptionBlock.appendChild(description);
		innerDiv.appendChild(descriptionBlock);
		
		teaserDiv.appendChild(innerDiv);
		
		var splitDiv = document.createElement("div");
		splitDiv.className="fill";
		splitDiv.style.height="17px";
		teaserDiv.appendChild(splitDiv);
		
		var footerDiv = document.createElement("div");
		footerDiv.className="Footer";
		
		var footerLink1 = document.createElement("a");
		footerLink1.href= (failover ? "http://www.carnegie.se/sv/Bli-kund-2/?=/login/control/adaptlogic.htm" : 
			(contentSelector==1?"http://nordic.carnegie.se/Nordic/login.aspx":"http://www.carnegie.se/online") + gaSuffix);
		footerLink1.innerHTML=failover ? "Bli kund" : (contentSelector==1? "S&ouml;kte du Edge?" : "S&ouml;kte du Online?");
		footerDiv.appendChild(footerLink1);
		
		var splitterSpan = document.createElement("span");
		splitterSpan.className = "VerticalBar";
		footerDiv.appendChild(splitterSpan);
		
		var footerLink2 = document.createElement("a");
		footerLink2.href= (failover ? "http://www.carnegie.se/sv/Logga-in1/?=/login/control/adaptlogic.htm" : 
			(contentSelector==1?"http://www.carnegie.se/online":"http://nordic.carnegie.se/Nordic/login.aspx") + gaSuffix );
		footerLink2.innerHTML='<span class="LoginButtonLink noLink"><img alt="Logga in" src="http://www.carnegie.se/Temp/ImagePack/IT2073723674.gif"/></span>';
		footerDiv.appendChild(footerLink2);
		
		teaserDiv.appendChild(footerDiv);
		
		containerDiv.appendChild(teaserDiv);
		div.appendChild( containerDiv );
	
		//	preparing parameters for image-loading callback
		params = [];	//Array()
		params.push( innerDiv );
		params.push( link.href);

		__sendRPC("http://www.carnegie.se/DocGlobal/online_white_90.jpg", __readResponse);		

		// make wrapping DIV visible
		div.style.display = 'block'; 		
		div.style.visibility = 'visible'; 	
		
	};	
	
	function storeVisitedArticles(shownArticlesArr, visittedArticlesArr, articleVisitsStatistic, max_visitted_articles_cached, expireDays)
	{
		var	visittedArticles = "";
		var max_article_visits = 3;
		var curArticleId = location.href;
		var daysBedoreExpiration = expireDays ? expireDays : 365;
		
		if(curArticleId)
			shownArticlesArr[shownArticlesArr.length] = curArticleId;
			
		for(var j=0; j<shownArticlesArr.length; j++){
			var containsCurArticle = false;
			for (var i=0; i < visittedArticlesArr.length; i++){
				if(visittedArticlesArr[i]==shownArticlesArr[j]){
					containsCurArticle = true;
					break;
				}
			}
			if(!containsCurArticle){
				if(visittedArticlesArr.length >= max_visitted_articles_cached){
					visittedArticlesArr = visittedArticlesArr.splice(1,max_visitted_articles_cached-1);
				}
				visittedArticlesArr[visittedArticlesArr.length] = shownArticlesArr[j];
			}
		}
		for(var i=0;i<visittedArticlesArr.length;i++){
			var curArticleIdVal = visittedArticlesArr[i];
			var articleStatValue = articleVisitsStatistic[curArticleIdVal];
			if(articleStatValue){	
				for(var j=0;j<shownArticlesArr.length;j++){
					if(shownArticlesArr[j]==curArticleIdVal){
						articleStatValue= 1 + parseInt(articleStatValue);
						break;
					}
				}
			}else{
				if(curArticleIdVal==curArticleId)
					articleStatValue=max_article_visits;
				else
					articleStatValue=1;
			}
				
			visittedArticles+=visittedArticlesArr[i]+","+articleStatValue;
			if(i < visittedArticlesArr.length-1)
				visittedArticles+=",";
		}
		if(visittedArticles)
			Cookie.set("cn_art_lst", visittedArticles, daysBedoreExpiration);
	}	
	
	this.init = function() 
	{
		//	server-load control
		if (_maloadprob > _peload)
		{
			document.write("<div id='" + ROOT + "' style='display: none; visibility: hidden;'>"+
				"<a href=\"http://carnegieinc.test.dropit.se/sv/om/Tobias-test/Privatpersoner/\">"+
				"<img src=\"http://carnegieinc.test.dropit.se/sandbox/images/personalizedimage_default_284px.jpg\"></a></div>");
			return;
		}
		if (Cookie.get("ca_cat_sent")) {			
			adapt_cn_start.categorySent=1;
		}else{
			Cookie.set("ca_cat_sent", "is_set", 1);
		}
		
		if (Cookie.get("visitted_set")) {		
			adapt_cn_start.visitted_set=1;
		}else{
			Cookie.set("visitted_set", "is_set", 1);
		}

		//	just return if there is no cookie
		if (__getCookie(_cid)=='no_cookie') 
		{
			//	config values
			var _cdomain = "carnegie.se";
			var _cpath = "/";
			
			//	processing cookie
			var now = new Date();
			var exp_date = new Date(Date.UTC(now.getUTCFullYear()+2, now.getUTCMonth(), now.getUTCDate()));
			//create & set cookie with name as _cid value
			document.cookie = _cid+"="+escape(__newGuid())+"; expires="+exp_date.toGMTString()+"; path="+_cpath+"; domain="+_cdomain;
		}
		
 		// creating  wrapping invisible DIV  without <p> element
		var html_excerpt = '';
		document.write("<div id='" + ROOT + "' style='display: none; visibility: hidden;'>"+ html_excerpt +"</div>");
		
		var parentEl = document.getElementById(ROOT).parentNode;
		while(parentEl.firstChild.nodeName!="DIV")
		{
			parentEl.removeChild(parentEl.firstChild);
		}
		
		__requestContent();
	};
	
};

function DataRequest() {
		
	this.bearer = null;
	this.ready = false;
	this.aborted = false;
	this.start_time = 0;
	
	this.send = function(url)
	{
		var me = this;
		window.onerror = function(msg, url, line) 
		{
			return me.onerror(msg, url, line);
		};
		this.start_time = new Date().getTime();
		
		this.bearer = document.createElement("script");
		this.bearer.setAttribute("type", "text/javascript");
	    this.bearer.setAttribute("charset", "utf-8");
		this.bearer.setAttribute("src", url);
		document.getElementsByTagName("head")[0].appendChild(this.bearer);
	};
	
	this.callback = function(data)
	{
		if (this.aborted) return;
		
		this.ready = true;
		adapt_cn_start.serverResponse(data);		
	};

	this.onerror = function(msg, url, line) {
		this.abort();
		//alert("DataRequest:  Wrong data format !");
		return true;
	};
	
	this.abort = function() {
		this.aborted = true;
		if (this.bearer)
			if (this.bearer.parentNode)
				this.bearer.parentNode.removeChild(this.bearer);
	};
}

// This is the entry point
var adapt_dataRequest_cn_start = new DataRequest();
adapt_cn_start.init();
