// v2.1

var url = 'http://analytics.legalandgeneral.com/sce-analytics/';
var amountResults = '5';

var expires = new Date();
var cookieExpireTime = (60*60*24*7);
var path = '/';
var amountPreviousResults = '5'; 
var rankCookieName = 'lg-rank-data';

function rank (rank) {
	document.getElementById('ranktext').innerHTML =  '[Saved]';
	var servlet = url + "Rank?";
	servlet = servlet + 'rank=' + rank + '&page=' + window.location.href;
	
	var httpRequest = getHttpRequest();
		
	try {
		httpRequest.open("POST", servlet, true);
		httpRequest.setRequestHeader( "Content-type", "text/xml" );
		
	    httpRequest.onreadystatechange = function () {
		    if (httpRequest.readyState == 4) {
		        if (httpRequest.status == 200 || httpRequest.status == 0) {
		        	document.getElementById('ranktext').innerHTML =  '[Saved]';
		        	updateCookie(rankCookieName, window.location.href, rank);
		        } else {
		        	//document.getElementById('ranktext').innerHTML = '[Please try again soon]';
		        	document.getElementById('ranktext').innerHTML = '[Saved]';
		        	updateCookie(rankCookieName, window.location.href, rank);
		        }
		        storerank(rank);
		    }
		};
		httpRequest.send(null);
	} catch (e) { // Fail Gracefully if host not available
	}
}

function storerank (rank) {
	var type;
	
	if (rank == 1)
		type = 'onestar';
	else if (rank == 2)
		type = 'twostar';
	else if (rank == 3)
		type = 'threestar';
	else if (rank == 4)
		type = 'fourstar';
	else if (rank == 5)
		type = 'fivestar';
				
	var html = '<ul class="rating ' + type + '"><li class="one"><a href="#" title="1 Star">1</a></li><li class="two"><a href="#" title="2 Stars">2</a></li><li class="three"><a href="#" title="3 Stars">3</a></li><li class="four"><a href="#" title="4 Stars">4</a></li><li class="five"><a href="#" title="5 Stars">5</a></li></ul>';
	document.getElementById('ranklist').innerHTML = html;
}

function isRanked () {
	var href = window.location.href;
	var cookieData = readCookie(rankCookieName);
	var rankedPages = cookieData.split(',');
	for (var i=0; i<rankedPages.length; i++) {
	    var page = rankedPages[i].substring (0, rankedPages[i].length-2);
	    var rank = rankedPages[i].substring (rankedPages[i].length-1, rankedPages[i].length);
	    if (href == page) {
	    	document.getElementById('ranktext').innerHTML =  '[Saved]';
	    	storerank(rank);
	    	return;
	    }
	}
}

function fetchhits(json) { 	
	processJsonHits (json);
}

function fetchranks(json) { 
	processJsonRanks (json);
}

function processJsonRanks(jsonObjectString) {		
	var divdisplay = document.getElementById("topratedarticles");
	var html = '<ul class="links">';
	var jsonObject = jsonObjectString;
	
	if (divdisplay != null) {
		for (var index = 0; index < jsonObject.items.length; index ++) {
	    	var page = jsonObject.items[index];
	    	var rate = 0;
	    	html = html + '<li><a href="';
	    	for (var i in page) {
	    		if (i == 'pageurl') {
	    			html = html + page[i] + '">';
	    		} else if (i == 'pagetitle') {
	    			html = html + page[i];
	    		} else if (i == 'pagerank') {
	    			rate = Math.round(page[i]);
	    		}
	    	}
	    	html = html + '</a><p class="rating">User rating: <img src="/web_resources/lgrb/images/content/rating-' + rate 
	    		+ '.gif" alt="' + rate
	    		+ ' out of 5" width="53" height="10" /></p></li>';
	 	}
		
		html = html + '</ul>';
		divdisplay.innerHTML = html;
	}
}

function processJsonHits(jsonObjectString) {		
	var divdisplay = document.getElementById("populararticles");
	var html = '<ul class="links">';
	var jsonObject = jsonObjectString;
			
	if (divdisplay != null) {
		for (var index = 0; index < jsonObject.items.length; index ++) {
	    	var page = jsonObject.items[index];
	    	var rate = 0;
	    	html = html + '<li><a href="';
	    	for (var i in page) {
	    		if (i == 'pageurl') {
	    			html = html + page[i] + '">';
	    		} else if (i == 'pagetitle') {
	    			html = html + page[i];
	    		} 
	    	}
	    	html = html + '</a></p></li>';
	 	}

		html = html + '</ul>';
		divdisplay.innerHTML = html;
	}
}

function toggleLayer(layer) {
  var elem, vis;
  if(document.getElementById) // this is the way the standards work
    elem = document.getElementById(layer);
  else if(document.all) // this is the way old msie versions work
      elem = document.all[layer];
  else if(document.layers) // this is the way nn4 works
    elem = document.layers[layer];
  
  vis = elem.style;

  if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
    vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
  
  vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}

function getPreviousPages() {
	var html = '<ul class="links">';
	var amountOfCurrentResults = 1;
	var httpLocation = window.location.href;
	var recentlyViewedTitle = '';
	
	var metaCollection = document.getElementsByTagName('meta'); 
	for (i=0;i<metaCollection.length;i++) { 
		nameAttribute = metaCollection[i].name;
		if (nameAttribute == 'topratedlink')
			recentlyViewedTitle  = metaCollection[i].content;
	}
		
	if (recentlyViewedTitle.length < 1)
		recentlyViewedTitle = document.title;
	
	var locationCookie = 'lg-location-';
	var pageTitleCookie = 'lg-pagetitle-';
	
	var data = new Array (amountPreviousResults);
	for (var i=0; i<amountPreviousResults; i++)
		data[i] = new Array (2);

	for (var i=0; i<amountPreviousResults; i++) {
		var location = readCookie (locationCookie + i);
		var pageTitle = readCookie (pageTitleCookie + i);
		data[i][0] = location;
		data[i][1] = pageTitle;
		html += '<li><a href="' + location + '">' + pageTitle + '</a></li>';
		if (location != '')
			amountOfCurrentResults++;
	}
	
	if (!urlAlreadyStored (data, httpLocation)) {
		storeCookie(locationCookie+'0', httpLocation);
		storeCookie(pageTitleCookie+'0', recentlyViewedTitle);
		for (var row=0; row<amountPreviousResults; row++) {
			if (data[row][0] != '') {
				if ((row+1) != amountPreviousResults) {
					storeCookie(locationCookie+(row+1), data[row][0]);
					storeCookie(pageTitleCookie+(row+1), data[row][1]);
				}
			}
		}
	}
	
	if (amountOfCurrentResults > 0) {
		html += '</ul>';
		var recentlyviewed = document.getElementById('recentlyviewed');
		if (recentlyviewed != null) {
			recentlyviewed.innerHTML = html;
		}
	} 
}

function urlAlreadyStored (data, httpLocation) {
	for (var i=0; i<data.length; i++)
		if (data[i][0] == httpLocation)
			return true;
	
	return false;
}

function updateCookie (name, page, rank) {
	var cookieData = readCookie(name);
	
	if (cookieData != '') 
		cookieData += ',' + page + ' ' + rank;
	else 
		cookieData = page + ' ' + rank;
	
	storeCookie(name, cookieData);
}

function readCookie (name) {
	var re = new RegExp(name+"=[^;]+", "i"); 
	if (document.cookie.match(re))
		return unescape((document.cookie.match(re)[0].split("=")[1]));	
	return '';
}

function storeCookie (name, value) {
	var ex = new Date ();
	ex.setSeconds((expires.getDate() + cookieExpireTime), 0);
	
	var cookieString = name + '=' + escape(value) + "; ";
	cookieString += "expires=" + ex.toUTCString() + "; ";
	cookieString += "path=" + path + "; ";
	document.cookie = cookieString;
}

function getHttpRequest () {
	var httpRequest = null;
	
	try {
		httpRequest = new XMLHttpRequest();
	} catch(e) {
		try {
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
		    	httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
		    } catch (e) {
		    	httpRequest = false;
		    }
		}
	}
	
	return httpRequest;
}

function addLoadEvent(func) { 
	var oldonload = window.onload; 
	if (typeof window.onload != 'function') { 
		window.onload = func; 
	} else { 
		window.onload = function() { 
			if (oldonload) { 
				oldonload(); 
			} 
			func(); 
		} 
	} 
} 

addLoadEvent(function(){getPreviousPages()});
addLoadEvent(function(){isRanked()});
