/*
 * 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;
/*
 * 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. 
 */
www.getServerTime = function(callback) {
	if (!www.serverTime.fetched) {
		$.get("/timer.xml?rand="+ord, 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.amPm = 'AM';
				if (www.serverTime.hours == 0){
					www.serverTime.hoursAmPm = 12;
				} else {
					www.serverTime.hoursAmPm = www.serverTime.hours;
				}
			}
			www.serverTime.fetched = true;
			
			if (typeof(callback) == "function") {
				callback();
			}
		});
	} else {
		if (typeof(callback) == "function") {
			callback();
		}
	}
}


/*
 * 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;
}


/*
 * 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('http://twitter.com/home?status=' + title + ' - '+ shortURL,'twitter');
		};
		BitlyClient.call('shorten', {'longUrl': productionUrl + '?ref=twitter'}, 'BitlyCB.alertResponse');
	});
}