﻿//you can configure the following

//the path to get recommendation from the recommendation engine
var recEnginePath = "http://re.discoverhongkong.com/recommend.do";

//flag to control showing the RE area
var showRE = false;

//flag to control whether enable data collection
var collectData = true;

//the path to get backup recommendation
//[table_suffix] will be replaced by the country name automatically in the code
var backupPath = "/[table_suffix]/rec-engine/backup.js";

//the path to handle the click count in the recommedation engine
var clickCountPath = "http://re.discoverhongkong.com/logClickCount.do";

//the path to handle the click count in the recommedation engine
var durationCountPath = "http://re.discoverhongkong.com/logDuration.do";

//the recommend area div id
var recommendAreaId = "recommendation";

//the timeout interval. When time out, get the backup recommendation
var recTimeoutInterval = 5000;

//the sleep time in milli second to ensure data is sent out
var sleepTime = 200;

//configuration
//please encode the non-english characters to html entities encoding, please do the encoding at: http://re.hktb.com/admin/html_entities.php
var config = {
	eng: 		{alsoSee: "Also see:", characterLimit: 30},
	china: 		{alsoSee: "Also see:", characterLimit: 30},
	tc: 		{alsoSee: "Also see:", characterLimit: 30},
	usa: 		{alsoSee: "Also see:", characterLimit: 30},
	uk: 		{alsoSee: "Also see:", characterLimit: 30},
	australia: 	{alsoSee: "Also see:", characterLimit: 30},
	german: 	{alsoSee: "Also see:", characterLimit: 30},
	canada: 	{alsoSee: "Also see:", characterLimit: 30},
	jpn: 		{alsoSee: "Also see:", characterLimit: 30},
	newzealand: {alsoSee: "Also see:", characterLimit: 30},
	seasia: 	{alsoSee: "Also see:", characterLimit: 30},
	kor: 		{alsoSee: "Also see:", characterLimit: 30},
	france: 	{alsoSee: "Also see:", characterLimit: 30},
	spanish: 	{alsoSee: "Also see:", characterLimit: 30},
	dutch: 		{alsoSee: "Also see:", characterLimit: 30},
	italy: 		{alsoSee: "Also see:", characterLimit: 30},
	thai: 		{alsoSee: "Also see:", characterLimit: 30},
	malaysia: 	{alsoSee: "Also see:", characterLimit: 30},
	russia: 	{alsoSee: "Also see:", characterLimit: 30}
};

//the function to generate the layout in the recommendation area
function buildRecommendArea(results) {

	var url;
	var title;
	var itemId;
	var isPopup;
	var type
	var typeStr = "";
	
	var innerHtml = "<div class=\"recommendation\" style=\"font-weight: bold; padding-bottom: 10px;\">" + config[tableSuffix].alsoSee + "</div>";
	//alert("see" + results.length);
	for (var i=0;i<results.length;i++) {	
		if (results[i].itemId != null) {
			itemId = results[i].itemId;
		}
		
		url = results[i].url;
		title = trimTitle(results[i].title);
		isPopup = results[i].isPopup;
		type = results[i].type;
		
		//*** for debug use, will remove when production ***//
		/*
		switch (type) {
			case 1:
				typeStr = "( promotion )";
				break;
			case 2:
				typeStr = "( weighted )";
				break;
			default:
				typeStr = "( recommendation )";
				break;
		}
		*/
		//***//
		
		var onClickStr = "";
		if (isRecEngine) {
			onClickStr = "onClick=handleClickCount('" + tableSuffix + "'," + itemId + "," + type + ");";
		}
		
		var popupStr = "";
		if (isPopup == 1) {
			popupStr = "target=\"_blank\"";
		}
		
		innerHtml += "<div class=\"recommendationTxt\">";
		innerHtml += 	"<a href=\"" + url + "\" " + popupStr + " " + onClickStr + ">" + title + "</a> " + typeStr;
		innerHtml += "</div>";
	}
	
	innerHtml += "</div>";
	document.getElementById(recommendAreaId).innerHTML = innerHtml;
	
}

//**********************************************************************************//
//please do not update the lines below

var recTimeoutId;
var startTime;
var isRecEngine = true;

var tableSuffix;
var url;
var userId;
var currentItemId;
var currentLocation;

//the variable need to prevent calling the timer function again when click the 'back' button
var gotResult = false;

function initRecEngine() {

	//request recommendation
	var data = extractParams();
	tableSuffix = data.tableSuffix;
	url = data.url;
	
	addScript(recEnginePath + "?tableSuffix=" + data.tableSuffix + "&url=" + data.url + "&title=" + escape(document.title) + "&collectData=" + (collectData ? "1" : "0"));
	
	recTimeoutId = setTimeout("getBackupResults();",recTimeoutInterval);
	
	var currentTime = new Date();
	startTime = currentTime.getTime();
}

function onPageUnload() {
	if (isRecEngine) {
		if (collectData) {
			var currentTime = new Date();
			var duration = Math.round((currentTime.getTime() - startTime) / 1000);
			
			if (duration > 0) {
				//to handle backward and forward case, we need a random number to prevent caching
				var random = Math.floor(Math.random() * 1000000);
				
				addScript(durationCountPath + "?tableSuffix=" + tableSuffix + "&itemId=" + currentItemId + "&duration=" + duration + "&random=" + random);
				
				//ensure the request is send out before page is leaving
				sleep(sleepTime);
			}
		}
	}
}

//function included in the json format file
function getRecResults(obj) {
	if (showRE) {
		buildRecommendArea(obj.results);
	}
	
	if (obj.currentItemId != null) {
		currentItemId = obj.currentItemId;
	}
	
	if (obj.currentLocation != null) {
		currentLocation = obj.currentLocation;
	}
	
	if (obj.userId != null) {
		userId = obj.userId;
	}
	
	gotResult = true;
	clearTimeout(recTimeoutId);
}

function getBackupResults() {
	if (!gotResult) {
		isRecEngine = false;
		
		//request the back up data
		addScript(backupPath.replace(/\[table_suffix\]/,tableSuffix));
		
		recTimeoutId = setTimeout("getDefaultResults();",recTimeoutInterval);
	}
}
function getDefaultResults() {
	addScript(backupPath.replace(/\[table_suffix\]/,"eng"));
}

function handleClickCount(tableSuffix,itemId,type) {
	if (isRecEngine) {
		if (collectData) {
			addScript(clickCountPath + "?tableSuffix=" + tableSuffix + "&appliedFirstLocationId=" + currentLocation[0] + "&appliedSecondLocationId=" + currentLocation[1] + "&appliedThirdLocationId=" + currentLocation[2] + "&itemId=" + itemId + "&type=" + type);
			
			//ensure the request is send out before page is leaving
			sleep(sleepTime);
		}
	}
}

function addScript(url) {
    var script = document.createElement('script');

    script.src = url;
    document.body.appendChild(script);
}

function extractParams() {
	var url = location.href;
	var matches = url.match(/^http\:\/\/[a-zA-Z0-9-:\.]+\/iw-mount\/default\/main\/dhk\/\w+\/WORKAREA\/\w+(.+)/);
	var path;
	
	//production
	if (matches == null) {
		var temp = url.match(/^http:\/\/[^\/]+(.+)/);
		path = temp[1];
	}
	//staging
	else {
		path = matches[1];
	}
	
	//extract table suffix
	var temp = path.match(/\/(\w+)\//);
	var ts = temp[1];
	
	var data = {
		"tableSuffix" : ts,
		"url" : path
	};
	
	return data;
}

function trimTitle(title) {
	var characterLimit = config[tableSuffix].characterLimit;
	
	if (htmlEntityStrLen(title) > characterLimit) {
		title = htmlEntitySubStr(title,0,characterLimit) + "...";
	}
	
	return title;
}

function htmlEntityStrLen(str) {
	var strBuffer = str;
	var len = 0;
	
	var temp;
	while (strBuffer.length > 0) {
		temp = strBuffer.match(/^(&#[0-9]+;)/);
		
		if (temp != null) {
			strBuffer = strBuffer.substr(temp[1].length);
		}
		else {
			strBuffer = strBuffer.substr(1);
		}
		
		len++;
	}
	
	return len;
}
	
function htmlEntitySubStr(str,from,len) {
	var strBuffer = str;
	var counter = (len != null) ? from + len : str.length;
	var counter2 = from;
	var resultStr = "";
	
	var temp;
	while ((strBuffer.length > 0) && (counter > 0)) {
		temp = strBuffer.match(/^(&#[0-9]+;)/);
		
		if (temp != null) {
			if (counter2 <= 0) {
				resultStr += temp[1];
			}
			strBuffer = strBuffer.substr(temp[1].length);
		}
		else {
			if (counter2 <= 0) {
				resultStr += strBuffer.charAt(0);
			}
			strBuffer = strBuffer.substr(1);
		}
		
		counter--;
		counter2--;
	}
	
	return resultStr;
}

function sleep(millis) {
	var date = new Date();
	var curDate = null;

	do { 
		curDate = new Date(); 
	} while (curDate - date < millis);
} 

//**********************************************************************************//