/*Author Prashant Harbola
* prashant.harbola@infomentum.co.uk
*
* Javascript for tracking 'most popular' content.
* Requires cookies to be enabled.
*
*/

//to allow for degrading of firebug in non-firefox browsers	
try { console.assert(1); } catch(e) { console = { log: function() {}, assert: function() {} } }

//onload handled on template page so IDOC vars can be passed to the logTrial function.
jQuery().unload(pageClosed);

var Cookie = { 
    create: function(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else var expires = "";
        document.cookie = name + "=" + value + expires + "; path=/";
    },

    read: function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') {
                c = c.substring(1, c.length);
            }
            if (c.indexOf(nameEQ) == 0) {
                return c.substring(nameEQ.length, c.length);
            }
        }
        return null;
    },

    erase: function(name) {
        this.create(name, "", -1);
    }
}

function logTrial(webroot,contentId,trialRelURL){
	contentId = contentId.replace(/^\s+|\s+$/g,"");
	trialRelURL = trialRelURL.replace(/^\s+|\s+$/g,"");

	if(contentId == '' || contentId == null ){
		return;	
	}

	if(trialRelURL.indexOf("trials-search/") > -1){
		trialRelURL = trialRelURL.replace("trials-search/", "")
	}
	var timestampString = Cookie.read('CRUKTrialDate');
    if (timestampString) {
        var timestamp = new Date(timestampString);
        var temp = new Date();
        temp.setMinutes(temp.getMinutes(), temp.getSeconds() - 30);
				console.log("timestamp:%s, temp:%s",timestamp,temp);
				var cookieId = Cookie.read('CRUKTrialId');
        // If this is true, the load is after a set time period from the last reload
        if (timestamp < temp || contentId != cookieId) {
	        console.log("time difference sufficient, in main.");
					Cookie.create('CRUKTrialDate', setNowDate());
					Cookie.create('CRUKTrialId',contentId);
					logTrialAjax(webroot,contentId,trialRelURL);
        }else{
        	console.log("time difference not sufficient, no action taken");
        	console.log("cookie timestamp:%s, temp current:%s",timestamp,temp);
        }
    }
    else{
	    Cookie.create('CRUKTrialDate', setNowDate());
	    var checkCookiesEnabled = Cookie.read('CRUKTrialDate');
	    if (checkCookiesEnabled)
	    	logTrialAjax(webroot,contentId,trialRelURL);
  	}
}

function logTrialAjax(webroot, contentId, trialRelURL){
	jQuery.ajax({
    url: webroot + 'idcplg?IdcService=CRUK_TRIALS_LOG&contentId='+ contentId + '&trialRelURL=' + trialRelURL +'&IsJava=1',
    type: 'GET',
    dataType: 'html',
    timeout: 1000,
    error: function(){
			console.log("unable to add Trial");
    },
    success: function(xml){
			console.log("Trial successfully logged : [%s], [%s], [%s]", contentId);
    }
	});
}

function setNowDate(){
 var temp = new Date();
 temp.setMinutes(temp.getMinutes(), temp.getSeconds());
 return temp;
}

function pageClosed() {
		console.log("page closed");
    Cookie.create('CRUKTrialDate', new Date());
}

function preventLogGeneration(classname){
 $('ul.' + classname + ' li a')
 .each(function()
   { 
      var temp = this.href;
      temp += '&log=0';
      this.href = temp;
   });	
}
