/*
 * 16/12/2006 CR23837 Steve Hillman - Initial version:
 *									  refactored as a discrete object
 *									  new XML format
 *									  added dated entries
 *									  added display order
 *
 * 15/01/2007 CR23838 Steve Hillman - Added Hitbox Campaign and Audience Impression Tracking.
 *
 * 07/03/2007 CR24705 Steve Hillman - Amend Hitbox Audience Impression Tracking so that hbx images are not logged on each rotation.
 *                                    Moved the img url generation to it's own function and put the urls in the array, rather than 
 *									  generating them on the fly.
 *
 * 13/03/2007 CR24746 J Cutbush     - Commented out audience impression image
 *
 * 20/03/2007 CR24765 Steve Hillman - Feature Focus tracking tidy up
 *									  Added code to track each feature focus impression ONCE per page
 *
 * 21/05/2007 CR24967 Steve Hillman - Remove Hitbox Audience Impression Tracking - leave Campaign Response (click thrus) intact    
 */

/*************************
 * Object: RandomSlideShow
 *************************/

function RandomSlideShow(imageId, nodeId) {

	var rs = this;
	
	this.mArr = new Array();
	//this.requestedImages = new Array();
	this.curFrame = 0;
	this.delay = 3000;
	this.timeoutId = null;
	this.running = true;
	this.lastFrame = 0;
	this.targetImg = imageId;
	this.targetNode = nodeId;
	
	/*
	 * HitBox tracking vars
	 */
	
	this.trackingPage = "/core/trackhbx.jhtml";
	this.campaignString = "";
	this.trackingName = "";
	this.hitboxAccount = "tel"; //default to telegraph account
	
	//this.slideShowTracked = false;
	
	this.hbxtel = "DM550808OANC78EN3"; //telegraph
	this.hbxexp = "DM551108DEAD78EN3"; //expat
	this.hbxjob = "DM55091966ZN78EN3"; //jobs
	this.hbxtst = "DM560123P1SC71EN3"; //test
	
	this.hbxurl = "http://ai.hitbox.com/ai"
	this.hbxacc = this.hbxtel; //default to telegraph account


	/*
	 * HitBox tracking functions
	 */

	this.setCampaignString = function(campaignString) {
		this.campaignString = campaignString;
	}
	
	this.setTrackingName = function(trackingName) {
		this.trackingName = trackingName;
	}
	
	this.setHitboxAccount = function(hitboxAccount) {
		this.hitboxAccount = hitboxAccount;
		
		if(hitboxAccount.toLowerCase() == "tel") {
			this.hbxacc = this.hbxtel;
		}
		
		if(hitboxAccount.toLowerCase() == "exp") {
			this.hbxacc = this.hbxexp;
		}
		
		if(hitboxAccount.toLowerCase() == "job") {
			this.hbxacc = this.hbxjob;
		}
		
		if(hitboxAccount.toLowerCase() == "tst") {
			this.hbxacc = this.hbxtst;
		}
	}

	/*
	 * manually set the refresh rate
	 */
	 
	this.setDelay = function(delay) {
		this.delay = delay;
	}
	
	/*
	 * Stop rotation if running and show previous image
	 */

	this.goBack = function() {
		
		if(rs.timeoutId !== null) {	
			clearInterval(rs.timeoutId);
			rs.timeoutId = null;
		}

		if(rs.running) {
			rs.running = false;
			rs.curFrame = rs.curFrame - 2;
		} else {
			rs.curFrame--;
		}

		if(rs.curFrame < 0) {
			rs.curFrame = (rs.mArr.length - 1);
		}

		goToFrame(rs.curFrame);
	};

	/*
	 * Stop rotation if running and show next image
	 */

	this.goForward = function() {

		if(rs.timeoutId !== null) {
			clearInterval(rs.timeoutId);
			rs.timeoutId = null;
		}

		if(rs.running) {
			rs.running = false;
		}

		rs.curFrame++;

		if(rs.curFrame == rs.mArr.length) {
			rs.curFrame = 0;
		}

		goToFrame(rs.curFrame);
	};

	/*
	 * show the specified frame
	 */

	function goToFrame(target) {

		var nxtImg = rs.mArr[target].src;
		
		document.getElementById(rs.targetImg).src = nxtImg;
		document.getElementById(rs.targetImg).alt = rs.mArr[target].alt;
		
		// Set hbx tracking image...
		// Checks to see if the next image has already been requested. 
		// If not add it to the requestedImages array and set the audience Impressions tracking image.
		// This should only happen once per image per page
		
		/*
		CR24967 - remove audience impression tracking
		
		if(rs.slideShowTracked === false) {
		
			document.getElementById(rs.targetImg + "hbx").src = getTrackingImage();
			
			// set slideShowTracked to true to prevent subsequent tracking
			rs.slideShowTracked = true;
		
		}
		*/
			
		document.getElementById(rs.targetNode).href = rs.mArr[target].href;

	};

	/*
	 * get random number
	 */
	 
	function getRandomNumber() {
	
		// set limit random number
		var max = rs.mArr.length;
		
		// random number between 1 and mArr.length + 1
		var rand = Math.floor(Math.random() * max);
		
		return rand;
	};

	/*
	 * Randomise the frames
	 */

	function randomFrames() {
		
		var rand = getRandomNumber();

		// prevent showing the same frame twice in a row
		if(rs.lastFrame == rand) {

			randomFrames();

		} else {

			goToFrame(rand);
			rs.lastFrame = rand;
			rs.curFrame = rand;			
		}
	};

	/*
	 * load XML file via droplet
	 */

	this.loadXMLFile = function(file) {
	
		var myurl = "/portal/featurefocus/loadxmlfile.jhtml?file=" + file;
		var ajax = new AJAXInteraction(myurl,null,loadCallback);
		ajax.doGet();
	};

	/*
	 * call back function to handle load response
	 */ 

	function loadCallback(xmlDoc) {

		if(xmlDoc.firstChild.nodeName == 'featurefocuslinks') {

			docLinks = new Array();

			var linkNodes = xmlDoc.getElementsByTagName('link');

			for(var i = 0; i < linkNodes.length; i++) {

				tempObj = new Object();

				var linkNode = xmlDoc.getElementsByTagName("link")[i];								
				
				var startDate = null;
				var expiryDate = null;
				
				var linkText = null;
				var linkHref = null;
				
				try {
					var dateStr = linkNode.getElementsByTagName('start-date')[0].firstChild.nodeValue
					if(dateStr.length > 0) {
						startDate = new Date(dateStr);
					}
				} catch(exception) {
					startDate = null;
				}
				
				try {
					var dateStr = linkNode.getElementsByTagName('expiry-date')[0].firstChild.nodeValue;
					if(dateStr.length > 0) {
						expiryDate = new Date(dateStr);
					}
				} catch(exception) {
					expiryDate = null;
				}
				
				if(startDate == null || expiryDate == null) {
				
					// add link as default option
					
					try {
						tempObj.src = linkNode.getElementsByTagName('link-image')[0].firstChild.nodeValue;
					} catch(exception) {
						tempObj.src = "";
					}
					
					try {
						linkText = linkNode.getElementsByTagName('link-text')[0].firstChild.nodeValue;
					} catch(exception) {
						linkText = "";
					}
					
					try {
						linkHref = linkNode.getElementsByTagName('link-href')[0].firstChild.nodeValue;
					} catch(exception) { 
						linkHref = "";
					}
					
					try {
						tempObj.order = parseInt(linkNode.getElementsByTagName('display-order')[0].firstChild.nodeValue);
					} catch(exception) { 
						tempObj.order = parseInt("0");
					}
					
					try {
						tempObj.alt = linkText;
						//tempObj.hbximg = buildHbxImg(linkText);
					} catch(exception) {
						tempObj.alt = "";
						tempObj.hbximg = "";
					}
					
					// build the url to include all tracking parameters
					
					try {
						tempObj.href = buildUrl(linkText, linkHref);
					} catch(exception) {
						tempObj.href = "";
					}
				    
				    docLinks.push(tempObj);
				    			    
				} else {
					
					// do date check and add if applicable.
					
					if(dateInRange(startDate, expiryDate)) {
						
						try {
							tempObj.src = linkNode.getElementsByTagName('link-image')[0].firstChild.nodeValue;
						} catch(exception) {
							tempObj.src = "";
						}

						try {
							linkText = linkNode.getElementsByTagName('link-text')[0].firstChild.nodeValue;
						} catch(exception) {
							linkText = "";
						}

						try {
							linkHref = linkNode.getElementsByTagName('link-href')[0].firstChild.nodeValue;
						} catch(exception) { 
							linkHref = "";
						}

						try {
							tempObj.order = parseInt(linkNode.getElementsByTagName('display-order')[0].firstChild.nodeValue);
						} catch(exception) { 
							tempObj.order = parseInt("0");
						}

						try {
							tempObj.alt = linkText;
							//tempObj.hbximg = buildHbxImg(linkText);
						} catch(exception) {
							tempObj.alt = "";
							tempObj.hbximg = "";
						}
					
						// build the url to include all tracking parameters
						
						try {
							tempObj.href = buildUrl(linkText, linkHref);
						} catch(exception) {
							tempObj.href = "";
					}
						
						docLinks.push(tempObj);
					}
				}			
			}

			docLinks.sort(sortByDisplayOrder);
			
			rs.mArr = docLinks;			
			
			goToFrame(getRandomNumber());
			
			var rf = randomFrames;
			rs.timeoutId = setInterval(rf, rs.delay);
		}
	};
	
	/*
	 * Sort array by contained object's display order field
	 */
	
	function sortByDisplayOrder(a,b) {
	
		  if (a.order < b.order) return -1;
		  if (a.order > b.order) return 1;
		  return 0;
		  
	};
	
	/*
	 * Replace spaces with underscores
	 * Remove apostrophies
	 * encode all other illegal characters
	 */
	 
	function makeUrlSafe(str) {
		str = str.replace(/ /g, "_");
		str = str.replace(/'/g, "");
		return encodeURIComponent(str);
	};
	
	/*
	 * emTy param must be 28 characters or less (including the dcmp type i.e. 'OTC-') so trim down if necessary
	 */
	 
	function trimToSize(str) {
		
		if(str.length > 24) {
			return str.substring(0,24);
		} 
		 	
		return str;
	};
	
	/*
	 * Return Date (at time of execution) as milliseconds.
	 * Used to make the HitBox tracking image name unique for cache busting
	 */
	 
	function getDateAsMilliseconds() {
		return Date.parse(new Date());
	};
	
	/*
	 * Construct the URL to contain the tracking page, the tracking params and the target link 
	 */
	 
	function buildUrl(linkText, linkHref) {
		
		var link = rs.trackingPage + 				// /core/trackhbx.jhtml
		"?dcmp=" + rs.campaignString + 				// ?dcmp=OTC-
		"&name=" + rs.trackingName + 				// &name=FeatureFocus
		"&hb=" + rs.hitboxAccount + 				// &hb=tel
		"&emTy=" + trimToSize(rs.trackingName + "-" + makeUrlSafe(linkText)) + 	// ?FeatureFocus-Laptop_Guide
		"&nxt=" + linkHref;
		
		return link;
	};
	
	/*
	 * Construct the hbx img url
	 */
	 
	/*
	function buildHbxImg(campaignName) {
	
		return rs.hbxurl + "?hb=" + rs.hbxacc + "&dai=" + rs.campaignString + trimToSize(rs.trackingName + "-" + makeUrlSafe(campaignName));
	
	};
	*/
	
	/*
	 * track slideshow usage once per page
	 */
	 
	/*
	CR24967 - remove audience impression tracking
	
	function getTrackingImage() {
	
		return rs.hbxurl + "?random=" + getDateAsMilliseconds() + "&hb=" + rs.hbxacc + "&dai=" + rs.trackingName;
		
	};
	*/
	
	/*
	 * Does the requestedImages array contain the specified object
	 */
	 
	/*
	CR24967 - remove audience impression tracking
	
	function arrayContains(obj) {	
		for(var i = 0; i < rs.requestedImages.length; i++) {			
			if(rs.requestedImages[i] === obj) {
				return true;
			}
		}
		return false;
	};
	*/
	
	/*
	 * is todays date between startDate and endDate
	 */
	 
	function dateInRange(startDate, endDate) {
	
		var now = new Date();
		
		// Disregard the time elements for the comparison
		
		var today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
		
		if((today >= startDate) && (today <= endDate)) {
		
			// use link - date is in range
			return true;
		
		} else {
		
			// dont use link - date is out of range
			return false;
		}
	
	};
	
}


/****************************
 * Object: AJAX functionality
 ****************************/

function AJAXInteraction(url,parameters,callback) {

	var req = initXHR();

	/* Firefox fix */
	if (req.overrideMimeType) {
		req.overrideMimeType('text/xml');
	}

	req.onreadystatechange = processRequest;

	function initXHR() {
		if (window.XMLHttpRequest) {
			return new XMLHttpRequest();
		} else if (window.ActiveXObject) {
			return new ActiveXObject("Microsoft.XMLHTTP");
		}
	}

	function processRequest () {
		if (req.readyState == 4) {
			if (req.status == 200) {
				if (callback) {
					callback(req.responseXML);
				}
			}
		}
	}

	this.doGet = function() {
		req.open("GET", url, true);
		req.send(null);
	};

	this.doPost = function() {
		req.open('POST', url, true);

		/* fixes Firefox's no req params problem */
		req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
		req.send(parameters);
	};
}