/*
 * Top level library for javascript common across tvnz.co.nz
 */
var www = new Object();


www.serverTime = new Object();
/*
 * Variables for getServerTime. All the global variables will be populated by a call to getServerTime and are for compositing various date formats.
 */
www.serverTime.DAY_ARRAY = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
www.serverTime.MONTH_ARRAY = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
www.serverTime.fetched = false;
/*
 * 'Global' variables that will be populated by a call to getServerTime and are for compositing date formats.
 * date is a JavaScript date object, all others are strings.
 */
www.serverTime.date;      
www.serverTime.minutes;
www.serverTime.hours;     // 0-23
www.serverTime.hoursAmPm; // 1-12
www.serverTime.dayText;
www.serverTime.day;
www.serverTime.monthText;
www.serverTime.month;
www.serverTime.year;
www.serverTime.amPm;

www.news_rootURL = "/stylesheets/tvnz/news/";
/*
 * Get the current time by requesting timer.xml, then populate some easily accessible global variables with the various fields of the current time for easy consumption.
 * Can be invoked multiple times without worrying about multiple requests to timer.xml.
 * If a callback function is supplied, the function returns null immediately and calls the callback function with the server time object when the result is available (perhaps before returning)
 * If callback not supplied, function completes synchronously (waits for result from server before returning it).  Returns null if failed to fetch.
 */
www.getServerTime = function(callback) {
	var isAsynchronous = typeof(callback) == "function";
	if (!www.serverTime.fetched) {
		$.ajax(
			{
			async: isAsynchronous,
			url: "/timer.xml?rand="+ord, 
			success: function(xml) {
			var splitSpace = $(xml).find("timer").attr("current_time").split(" ");
			var splitDate = splitSpace[0].split("-");
			var splitTime = splitSpace[1].split("-");
		
			// populates the global variables
			www.serverTime.date = new Date(splitDate[0], splitDate[1]-1, splitDate[2], splitTime[0], splitTime[1], splitTime[2]);
			www.serverTime.hours = splitTime[0];
			www.serverTime.minutes = splitTime[1];
			www.serverTime.dayText = www.serverTime.DAY_ARRAY[www.serverTime.date.getDay()];
			www.serverTime.day = splitDate[2];
			www.serverTime.monthText = www.serverTime.MONTH_ARRAY[splitDate[1]-1];
			www.serverTime.month = splitDate[1];
			www.serverTime.year = splitDate[0];
			
			if (www.serverTime.hours >= 12) {
				www.serverTime.amPm = 'PM';
				if (www.serverTime.hours > 12){
					www.serverTime.hoursAmPm = www.serverTime.hours - 12;
				} else {
					www.serverTime.hoursAmPm = www.serverTime.hours;
				}
			} else {
				www.serverTime.amPm = 'AM';
				if (www.serverTime.hours == 0){
					www.serverTime.hoursAmPm = 12;
				} else {
					www.serverTime.hoursAmPm = www.serverTime.hours;
				}
			}
			www.serverTime.fetched = true;
			
			if (isAsynchronous) {
				callback(www.serverTime);
			}
		}
			
		});
	} else {
		// already fetched once
		if (isAsynchronous) {
			callback(www.serverTime);
		}
	}
	return !isAsynchronous && www.serverTime.fetched ? www.serverTime : null; /* synchronous return - return server time or null if not fetched due to error */
}


/*
 * Returns true if the third parameter is after the first parameter and before the second parameter.
 * All three parameters need to be either dates or strings parseable as dates by Date.parse()
 */
www.dateWithin = function(beginDate, endDate, checkDate) {
	var b = (typeof beginDate == 'Date') ? beginDate : Date.parse(beginDate);
	var e = (typeof endDate == 'Date') ? endDate : Date.parse(endDate);
	var c = (typeof checkDate == 'Date') ? checkDate : Date.parse(checkDate);
	return c <= e && c >= b;
}

/** 
 * (derived from from lib.js) Extension Function: truncate
 * Truncates text at the last word boundry before <code>length</code> 
 * characters and appends an ellipsis entity suffix.
 * Parameters:
 * - string : String : the text to truncate
 * - length : Number : the length of string to truncate to.
 * Returns:
 * - String
 */
www.truncate = function(string,length) {
	if (!length) length = 80;
	var text = String(string);
	if (length < text.length) {
		return text.substr(0, text.lastIndexOf(' ',length) ) + '\u2026';
	} else {
		return text;
	}
}

/*
 * Global default params variable for calls to swfobject.embedSWF
 */

www.params = {
	wmode: "transparent",
	allowScriptAccess: "always",
	quality: "high"
}


/*
 * Returns the flash version currently supported by the browser as a string in Flash version format e.g. 10,0,45
 */
www.getFlashVersion = function() {
	// Internet Explorer 
	if (typeof ActiveXObject != "undefined") {
		try { 
			var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); 
			try {
				axo.AllowScriptAccess = 'always';
				return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; 
			} catch(e) {
				return '6,0,0';
			} 
		} catch(e) {} 
	// other browsers 
	} else {
		try {
			if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) { 
				return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]; 
			} 
		} catch(e) {} 
	}
	return '0,0,0';
}


/*
 * This function is called when a twitter icon is clicked. 
 * Once it's clicked, it loads the bit.ly api at runtime and passes the short url to twitter.
 * productionUrl - the url of the page to be shared, It should always point to a production URL so that the feature can be tested (as digg et al can't resolve no-production URLs)
 * urlEncodedArticleTitle - The title of the page to be shared, encoded for inclusion in a URL 
 */
www.tweet = function(productionUrl, urlEncodedArticleTitle) {
	$.getScript('http://bit.ly/javascript-api.js?version=latest&amp;login=tvnz&amp;apiKey=R_9d26195f2db6a848f089f635dbcd66a9', function() {
		BitlyCB.alertResponse = function(data) {
            var s = '';
            var shortURL = '';
            var firstResult;
            for(var r in data.results) {
            	firstResult = data.results[r]; break;
            }
            for (var key in firstResult) {
                 s += key + ":" + firstResult[key].toString() + "\n";
                 if (key == 'shortUrl'){
                 	shortURL = firstResult[key].toString();
                 }
            }
            var title = urlEncodedArticleTitle.replace(escape(String.fromCharCode(133)), "...");
            window.open('https://twitter.com/intent/tweet?text=' + title + '&url='+ productionUrl,'twitter');
		};
		var charSeparator = productionUrl.indexOf('?') == -1 ? '?' : '&';
		BitlyClient.call('shorten', {'longUrl': productionUrl + charSeparator + 'ref=twitter'}, 'BitlyCB.alertResponse');
	});
}


/* This function is used to inject ad for top banner*/
www.injectAd = function(){
	 if($("#hiddenLeaderboard #top-banner .ad #FLASH_AD").attr("id") != undefined){
	 	$("#header #top-banner .ad").append($("#hiddenLeaderboard #top-banner .ad #FLASH_AD"));
	 }else{
	 	$("#header #top-banner .ad").append($("#hiddenLeaderboard #top-banner .ad a"));
	 }
}
www.globalObj = new Object();
www.setGlobal = function(_variable, _value) {
	www.globalObj[_variable] = _value;
}

www.getGlobal = function(_variable) {
	return www.globalObj[_variable];
}

www.createCookie = 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=/";
}

www.readCookie = 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;
}

www.eraseCookie = function(name) {
	jsTVNZ.Common().createCookie(name,"",-1);
}

function combine() {
	var query_1 = document.recipeSearchForm.q1.value;
	var query_2 = document.recipeSearchForm.q2.value;
	var q = query_1 + " " + query_2;
	document.recipeSearchForm.q.value = q;
}


