/*
page_log.js
Purpose: makes AJAX call to page_logger.php to log and retrieve page hits. Also sets and reads page hit cookie.
Dependencies: html/stats/page_logger.php
Version history
1.0 - Initial release - NS - Jan 29, 2008
*/

function logPageView(type, id, page, viewStats, ipCloaked){
	/*alert('type: '+type+', id: '+id+', page: '+page+', viewStats: '+viewStats+', ipAllowed: '+ipAllowed);*/
	var ipBlocked = ipCloaked;//IP permanently blocked
	var showAllStats = 1;//default setting to show all page stats
 
	//read prefs cookie
	var prefsCookieExists = readCookie('firstpost_prefs');
	if (prefsCookieExists == 0) { //no prefs cookie. first time.
		if (viewStats == 1) { //set prefs cookie only if you are allowed to view stats.
			ipCloaked = 1; //set IP cloaked default
			setPrefCookie('firstpost_prefs', ipCloaked, showAllStats);
		}
	} else {
		//always view stats if prefs cookie set. No need to log into intranet.
		viewStats = 1;
		//prefs cookie exists. set ipCloaked and showstats from cookie
		prefs = prefsCookieExists.split(':');
		//prefs - [0]:cloaked / [1]:show all stats
		//only set ipcloaked from cookie if its not cloaked from first test
		ipCloaked = (ipCloaked == 1) ? ipCloaked : prefs[0]; 
		//ipCloaked = prefs[0];
		showAllStats = prefs[1];
	}

	//set history cookie if IP is not cloaked
	if (ipCloaked == 0) { 
		var newPage = setHistoryCookie('pageLog', id, type, page);
	}
	
	newPage = (newPage == -1) ? 1 : 0;
	var url = "stats/page_logger.php?timestamp=" + new Date().getTime();   
	var queryString = "type=" + type + "&id=" + id + "&page=" + page + "&viewStats=" + viewStats + "&ipCloaked=" + ipCloaked + "&newPage=" + newPage;
	/*alert(queryString);*/
	var xhr = getXHR();
	
	if (xhr) {
		xhr.onreadystatechange = function() {
			serverResponse(xhr, viewStats, showAllStats, ipBlocked);
		};	   
		xhr.open("POST", url, true);	  
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");	
		xhr.send(queryString);
	
	 } 		
}
 
function serverResponse(xhr, viewStats, showAllStats, ipBlocked) {
	if (xhr.readyState == 4) {
		if (xhr.status == 200 || xhr.status == 304) {
			if (viewStats == 1) {
				if (showAllStats == 1) {
					var statsHook = document.getElementById('statsHook');
					var statsContainer = document.createElement('div');
					var cloakLink = document.createElement('a');
					cloakLink.href = '#';
					addEvent('click', cloakLink, toggleCloak);	
					
					var response = xhr.responseText.split(':');
					if (ipBlocked == 0) {
						if (response[1] == 0) {
							var cloakText = 'You are logging hits';
							cloakLink.innerHTML = 'STOP';
						} else {
							var cloakText = 'You are NOT logging hits';
							cloakLink.innerHTML = 'START';
						}
					} else {
						var cloakText = 'You are NOT logging hits';
					}
					statsContainer.appendChild(document.createTextNode('Page Views: ' + response[0]));
					statsContainer.appendChild(document.createElement('br'));
					statsContainer.appendChild(document.createElement('hr'));
					statsContainer.appendChild(document.createTextNode(cloakText));
					if (ipBlocked == 0) {
						statsContainer.appendChild(document.createElement('br'));
						statsContainer.appendChild(cloakLink);
						statsContainer.appendChild(document.createElement('br'));
					}
					statsContainer.appendChild(document.createElement('hr'));
					var displayStatsLink = document.createElement('a');
					displayStatsLink.href = '#';
					displayStatsLink.innerHTML = 'Hide Page Stats';
					addEvent('click', displayStatsLink, toggleDisplayStats);
					statsContainer.appendChild(displayStatsLink);
					
					statsContainer.className = 'displayStats';
					statsHook.appendChild(statsContainer);

				} else {
					var statsHook = document.getElementById('statsHook');
					var statsContainer = document.createElement('div');
					var displayStatsLink = document.createElement('a');
					displayStatsLink.href = '#';
					displayStatsLink.innerHTML = 'View Page Stats';
					addEvent('click', displayStatsLink, toggleDisplayStats);
					statsContainer.appendChild(displayStatsLink);
					statsContainer.className = 'showPageHits';
					statsHook.appendChild(statsContainer);
				}
				
			}
		}
	}
}

function toggleCloak() {
	var cookieContent = readCookie('firstpost_prefs').split(':');
	var cloak = (cookieContent[0] == 0) ? 1 : 0;
	setPrefCookie('firstpost_prefs', cloak, cookieContent[1]);
	window.location.reload();
}
function toggleDisplayStats() {
	var cookieContent = readCookie('firstpost_prefs').split(':');
	var showAllStats = (cookieContent[1] == 0) ? 1 : 0;
	setPrefCookie('firstpost_prefs', cookieContent[0], showAllStats);
	window.location.reload();	
}

function setPrefCookie(name, cloak, showAllStats)
{
	 //cookie format - (cloaked 1-yes or 0-no) : (show all stats 1-yes or 0-no)
	 var the_cookie = cloak + ':' + showAllStats + ':';
 	 //expiry date for cookie
	 var years = 1;
	 var date = new Date();
	 date.setTime(date.getTime()+(years*365*24*60*60*1000));
	 var expires = "; expires="+date.toGMTString();
	 //add name and closing colon
	 the_cookie = name + '=' + the_cookie + expires + ';path=';
 	 document.cookie = the_cookie;
	 /* get previous cookie content*/
	 var cookieContent = readCookie(name);

	 if (cookieContent) { 
	  //alert('cookieContent: '+cookieContent);
	 }	 
}
 
function setHistoryCookie(name, id, type, page)
{
	 /* get previous cookie content*/
	 var cookieContent = readCookie(name);
	 /*
	  cookie code - id,type,page
	  id - story,film OR item ID
	  type - s:storyID, f:filmID, i:itemID
	  page - page number
	 */ 
	 var the_cookie = id + type.charAt(0)+ type.charAt(1) + page;
	 var pageViewed = -1;
	 //cookie exists. Get content and append new page data
	 if (cookieContent) { 
	  /*alert('cookieContent: '+cookieContent);*/
	  pageViewed = cookieContent.indexOf(the_cookie);
	  the_cookie = the_cookie + cookieContent;
	 }
	 expires = ''; //session cookie
	 //add name and closing colon
	 the_cookie = name + '=/' + the_cookie + expires + ';path=';
	 if (pageViewed == -1) { //its a new page, log it	 
	  document.cookie = the_cookie;
	 }
	 return pageViewed;
}
 
function readCookie(name) {
    var startIndex = document.cookie.indexOf(name);
    if (startIndex != -1) { //cookie exists get content
  		var endIndex = startIndex;
  		startIndex =  startIndex + name.length + 1;
		//find the end of the cookie content 	
		while (document.cookie.charAt(endIndex)!=";" && endIndex <= document.cookie.length) {
            endIndex++;   
        }
        var cookieContent = unescape(document.cookie.substring(startIndex,endIndex));
 		//alert(cookieContent);
		return cookieContent;
    } else {
  		return 0; 
 	}
} 