/********************************************************************************************
TVNZ Javascript Library functions list:

jsTVNZ.initialize();
	jsTVNZ.Common().initSetHomepage();
	jsTVNZ.Common().initWeatherLocation();
	jsTVNZ.Common().getServerTime(function()
		jsTVNZ.Common().setCurrentDate();
	jsTVNZ.Common().initPageTools();
	jsTVNZ.Common().initHighlightAlt();
	jsTVNZ.Common().initSuperClick();
	jsTVNZ.Common().fixUpMyIE6();

********************************************************************************************/

var jsTVNZ = window.jsTVNZ || {};
var globalObj = new Object();

var xmlMinutes;
var xmlHours;
var xmlTextDay;
var xmlDay;
var xmlTextMonth;
var xmlMonth;
var xmlYeah;
var xmlDate;

var intMouseDown;

var dc_tile = 0;
var channelEPGRows = 0;
var tvnzEPGRows = 0;

//var rootURL = "/stylesheets/tvnz/entertainment/";
var rootURL = "http://images.tvnz.co.nz/tvnz_site_images/entertainment/";

// Figure out what browser is being used
 $(function(){
 	

 
	/* var userAgent = navigator.userAgent.toLowerCase();
	var userBrowserName  = navigator.appName.toLowerCase();

	$.browser = {
		version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
		safari: /webkit/.test( userAgent ),
		opera: /opera/.test( userAgent ),
		msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
		mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent ),
		name:userBrowserName
	};
	alert($.browser.name + $.browser.version); */
	/* if ($.browser.name != 'playstation 3') {
		$("head").append("<script type='text/javascript' src='/stylesheets/tvnz/entertainment/flash/SIFR_Headings/js/sifr.js'></script>");
		$("head").append("<script type='text/javascript' src='/stylesheets/tvnz/entertainment/flash/SIFR_Headings/js/sifr-config.js'></script>");
	} */
}); 

// Makes the init run at page load
$(window).load(function() {
	jsTVNZ.initialize();
});

// the Initialize function, which runs on load, all sub-functions are called in here.
jsTVNZ.initialize = function() {
	
	// sets up the "set my homepage" button as per browser
	jsTVNZ.Common().initSetHomepage();

	// sets the current location showed in the top nav
	jsTVNZ.Common().initWeatherLocation();
	
	// finds ou the current time (needs timer.xml to work)
	jsTVNZ.Common().getServerTime(function() {
		jsTVNZ.Common().setCurrentDate();
	});

	// tools on article/story page
	if ($("#featureBackground.fullShow").is(":visible")) {
		jsTVNZ.Common().initPageTools();
	}

	jsTVNZ.Common().initCheckFlash();

	// Channel page alternative highlighting if now/next epg
	if ($("#channelSchedule").is(":visible")) {
		jsTVNZ.Common().initHighlightAlt();
	}

	// Make the enitre div clickable
	jsTVNZ.Common().initSuperClick();
	
	// Below rips out all the PNG images in IE6, and uses the filter in an IE6 only stylesheet
	if ($.browser.msie && $.browser.version <= 6) {
		jsTVNZ.Common().fixUpMyIE6();
	}	
}

// TVNZ Common functions, that can be re-called at any point.
jsTVNZ.Common = function() {
	var initSetHomepage = function() {
		$("#metaNav .topNav .setHomePage").click(function() {
			if ($.browser.msie) {
				// add's Behaviour to the body tag, then sets the homepage, IE Only
				$("body").css({behavior: 'url(#default#homepage)'});
				document.body.setHomePage('http://tvnz.co.nz');
				return false;
			} else if ($.browser.mozilla) {
				if (($("#makeThisMyHP").is(":hidden") == false) && ($("#makeThisMyHP").is(":visible") == false)) {
					// calls the HTML for Mozilla out of the jsHTML
					jsHTML.makeHomeMozilla(this);
					$("#makeThisMyHP .close").click(function() {
						$("#makeThisMyHP").animate({height: "hide"}, 250);
					}).css({cursor: "pointer"});
				}
				$("#makeThisMyHP").animate({height: "show"}, 250);
				return false;
			}
		});
	}
	
	var initWeatherLocation = function() {
		// an alt text map to show the correct alt text on the icons
		var altTextMap = {
			'FEWSHOWERS': 'Few Showers',
			'SHOWERS': 'Showers',
			'CLOUD': 'Cloudy',
			'DRIZZLE': 'Drizzle',
			'FEWSNOWSHOWERS': 'Few Snow Showers',
			'FINE': 'Fine',
			'FOG': 'Foggy',
			'HAIL': 'Hail',
			'HEAVYRAIN': 'Heavy Rain',
			'PARTCLOUDY': 'Partially Cloudy',
			'RAIN': 'Rain',
			'SNOW': 'Snow',
			'SUNNY': 'Sunny',
			'THUNDER': 'Thunder',
			'WIND': 'Windy'
		}
		// grabs the weather cookie
		var myCookie = jsTVNZ.Common().readCookie("weatherTVNZ");
		// changes the visibility to visible, and display none (as some browsers will not alow you to edit an element thats invisible)
		$("#metaNav .weather").css({visibility: "visible", display: "none"});
		// checks to see if the cookie exsists
		if (myCookie != null) {
			// if it exsists, use the cookie to write the current weather
			if (typeof(towns) == "object") {
				$("#metaNav .weather strong.location").html(myCookie.replace("_", " ") + ": ");
				$("#metaNav .weather img.icon").attr("src", "http://images.tvnz.co.nz/tvnz_site_images/images/weather/icon" + town_data[myCookie.toUpperCase()].icon + ".jpg").attr("alt", altTextMap[town_data[myCookie.toUpperCase()].icon]).attr("title", altTextMap[town_data[myCookie.toUpperCase()].icon]);
				$("#metaNav .weather .high strong").html(town_data[myCookie.toUpperCase()].max);
				$("#metaNav .weather .low strong").html(town_data[myCookie.toUpperCase()].min);
				$("#metaNav .weather").css({display: "block"});
			}
		} else {
			// else it will pick a random number and use that.
			if (typeof(towns) == "object") {
				var randomNo = Math.floor(Math.random() * towns.length);
				$("#metaNav .weather strong.location").html(towns[randomNo].toLowerCase().replace("_", " ") + ": ");
				$("#metaNav .weather img.icon").attr("src", "http://images.tvnz.co.nz/tvnz_site_images/images/weather/icon" + town_data[towns[randomNo]].icon + ".jpg").attr("alt", altTextMap[town_data[towns[randomNo]].icon]).attr("title", altTextMap[town_data[towns[randomNo]].icon]);
				$("#metaNav .weather .high strong").html(town_data[towns[randomNo]].max);
				$("#metaNav .weather .low strong").html(town_data[towns[randomNo]].min);
				$("#metaNav .weather").css({display: "block"});
			}
		}
		// add's the click function to the "change location" button
		$("#metaNav .topNav .weather .changeLocation").click(function() {
			if (($("#changeMyLocation").is(":hidden") == false) && ($("#changeMyLocation").is(":visible") == false)) {
				// call the jsHTML function to write the HTML to the page.
				jsHTML.weatherLocation(this);
				$("#changeMyLocation .close").click(function() {
					$("#changeMyLocation").animate({height: "hide"}, 250);
					return false;
				}).css({cursor: "pointer"});
				// binds the A-Z button
				$("#changeMyLocation .btnAZ").click(function() {
					$("#changeMyLocation .btnHolder a.selected").removeClass("selected");
					$(this).addClass("selected");
					$("#changeMyLocation .group").animate({height: "hide"}, 250, function() {
						$(this).removeClass("selected");
						$("#changeMyLocation .groupAll").addClass("selected").animate({height: "show"}, 250);
					});
					return false;
				}).css({cursor: "pointer"});
				// Bind's the North - South button
				$("#changeMyLocation .btnIslands").click(function() {
					$("#changeMyLocation .btnHolder a.selected").removeClass("selected");
					$(this).addClass("selected");
					$("#changeMyLocation .groupAll").animate({height: "hide"}, 250, function() {
						$(this).removeClass("selected");
						$("#changeMyLocation .group").addClass("selected").animate({height: "show"}, 250);
					});
					return false;
				}).css({cursor: "pointer"});
				// makes the checkbox selected even if you click the text
				$("#changeMyLocation .rowRadio").each(function() {
					$(this).click(function() {
						$("#changeMyLocation .rowRadio.selected").removeClass("selected");
						$(this).find("input").click();
						$(this).addClass("selected");
					}).css({cursor: "pointer"});
				});
				// below ensure's both a_ check box and b_ checkbox with the same id's are both checked
				$("#changeMyLocation .rowRadio input").each(function() {
					$(this).click(function() {
						if ($(this).attr("id").substring(0,1) == "a") {
							$("#b_" + $(this).attr("id").substring(2, $(this).attr("id").length)).attr("checked", "true").parent().addClass("selected");
						} else {
							$("#a_" + $(this).attr("id").substring(2, $(this).attr("id").length)).attr("checked", "true").parent().addClass("selected");
						}
					});
				});
				// if the save button is clicked, change to the new weather and save a cookie!
				$("#changeWeather").click(function() {
					$("#metaNav .weather strong.location").html($("#changeMyLocation .groupAll .rowRadio.selected input").val().replace("_", " ") + ": ");
					$("#metaNav .weather img.icon").attr("src", "http://images.tvnz.co.nz/tvnz_site_images/images/weather/icon" + town_data[$("#changeMyLocation .groupAll .rowRadio.selected input").val().toUpperCase()].icon + ".jpg").attr("alt", altTextMap[town_data[$("#changeMyLocation .groupAll .rowRadio.selected input").val().toUpperCase()].icon]).attr("title", altTextMap[town_data[$("#changeMyLocation .groupAll .rowRadio.selected input").val().toUpperCase()].icon]);
					$("#metaNav .weather .high strong").html(town_data[$("#changeMyLocation .groupAll .rowRadio.selected input").val().toUpperCase()].max);
					$("#metaNav .weather .low strong").html(town_data[$("#changeMyLocation .groupAll .rowRadio.selected input").val().toUpperCase()].min);
					jsTVNZ.Common().createCookie("weatherTVNZ", $("#changeMyLocation .groupAll .rowRadio.selected input").val(), 365);
					$("#changeMyLocation").animate({height: "hide"}, 250);
					return false;
				});
			}
			// stops all page animation so we can show out pop-over
			$("#changeMyLocation").animate({height: "show"}, 250);
			return false;
		});
	}

	var getServerTime = function(_callback) {
		$.get("/timer.xml?rand="+ord, function(xml) {
			var dayArray = new Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
			var monthArray = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
			var splitSpace = $(xml).find("timer").attr("current_time").split(" ");
			var splitTime = splitSpace[1].split("-");
			var splitDate = splitSpace[0].split("-");
			
			// populates the global variables
				xmlDate = new Date(splitDate[0], splitDate[1]-1, splitDate[2], splitTime[0], splitTime[1], splitTime[2]);
				xmlHours = splitTime[0];
				xmlMinutes = splitTime[1];
				xmlTextDay = dayArray[xmlDate.getDay()];
				xmlDay = splitDate[2];
				xmlTextMonth = monthArray[splitDate[1]-1];
				xmlMonth = splitDate[1];
				xmlYeah = splitDate[0];

			if (typeof(_callback) == "function") {
				_callback();
			}
		});
	}

	/*
	var setCurrentDate = function() {
		$(".currentTime").html(xmlTextDay + ", " + xmlTextMonth + " " + xmlDay + ", " + xmlYeah + " " + xmlHours + ":" + xmlMinutes).css({visibility: "visible"});
	}*/

	// the Current time
	var setCurrentDate = function() {
		var Time;
		var timeHours = xmlHours;
		if (timeHours >= 12){
			if (timeHours == 12){
				timeHours = 12;
			} else {
				timeHours = timeHours - 12;
			}
			Time = timeHours + ":" + xmlMinutes + " pm";
		}else if(timeHours < 12){
			if (timeHours == 0){
			timeHours = 12;
			}
			Time = timeHours + ":" + xmlMinutes + " am";
		}
	   $(".currentTime").html(xmlTextDay + ", " + xmlTextMonth + " " + xmlDay + ", " + Time);
	}

	var disableTools = function() {
		$(".print").css("display","none");
	}
	
	// Work arounds for IE6
	var fixUpMyIE6 = function() {
		// IE6 PNG remover
		$("img").each(function(){
			if ($(this).attr("src").match(/\.png$/) != null) {
				if ($(this).hasClass("iePNG")) {
					$(this).css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + $(this).attr("src") + "', sizingMethod='crop')");
				}
				$(this).attr("src", "http://images.tvnz.co.nz/tvnz_site_images/images/spacer.gif");
			}
		});
		// IE6 Style sheet, to add filtered PNG's	
		$("head").append("<link rel='stylesheet' href='" + rootURL + "css/ie6.css' type='text/css' media='screen' />");
	}

	var initCheckFlash = function() {
		var varsion = getFlashVersion().split(",")[0]
		var error = $("noscript").html().replace(/&lt;/g, "<").replace(/&gt;/g, ">");
		if (varsion < 9) {
		//if (varsion > 9) {
			$("body").prepend(error);
			$(".buttonHelpEnablingJS").css({visibility: 'hidden'});
		}
	}

	var getFlashVersion = function() {
		// ie 
		try {
			try { 
				var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); 
				try {
					axo.AllowScriptAccess = 'always';
				} catch(e) {
					return '6,0,0';
				} 
			} catch(e) {} 
			return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; 
		// other browsers 
		} catch(e) { 
			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';
	}

	// Standard Story page tools
	var initPageTools = function() {
		// Increase Font Size
		$(".textSize .plus").each(function() {
			$(this).click(function(){
				var currentFontSize = $('#featureStory').css('font-size');
				var newFontSize = parseInt(currentFontSize.substring(0,2))+2;
				if (newFontSize < 19) {
					$('#featureStory').css('font-size', newFontSize + "px");
					jsTVNZ.Common().createCookie("TVNZ-Fontsize", newFontSize, 365);
				}
				return false;
			});
		});
		 
		// Decrease Font Size
		$(".textSize .minus").each(function() {
			$(this).click(function(){
				var currentFontSize = $('#featureStory').css('font-size');
				var newFontSize = parseInt(currentFontSize.substring(0,2))-2;
				if (newFontSize >= 11) {
					$('#featureStory').css('font-size', newFontSize + "px");
					jsTVNZ.Common().createCookie("TVNZ-Fontsize", newFontSize, 365);
				}
				return false;
			});
		});
		
		// Print function
		$(".tools .print a").each(function() {
			$(this).click(function() {
				window.print();
				return false;
			});
		});

		// Share Box
		$(".tools .share a, #topButtons a.share, #topicTable .shareMe a.share").each(function() {
			var $this = $(this);
			$(this).click(function() {
				if (($("#shareMore").is(":hidden") == false) && ($("#shareMore").is(":visible") == false)) {
					// calls the HTML from jsHTML
					jsHTML.shareMore(this, jsTVNZ.Common().getGlobal('articleTitle'), jsTVNZ.Common().getGlobal('articleURL'), 295);
					$("#shareMore .close").click(function() {
						$("#shareMore").animate({height: "hide"}, 250);
						return false;
					}).css({cursor: "pointer"});
					if ($("#emailBox").is(":visible")) {
						$("#emailBox").animate({height: "hide"}, 125, function() {
							$("#shareMore").animate({height: "show"}, 250);
						});
					} else {
						$("#shareMore").animate({height: "show"}, 250);
					}
				} else if ($("#shareMore").is(":visible")) {
					$("#shareMore").animate({height: "hide"}, 125, function() {
						var leftCalc = $this.offset().left - ($(this).width() / 2) + (($this.width() + parseInt($this.css("padding-left")) + parseInt($this.css("padding-right"))) / 2);
						$(this).css({left: leftCalc + 'px', top: ($this.offset().top + 15) + 'px'}).animate({height: "show"}, 125);
					});
				} else {
					var leftCalc = $(this).offset().left - ($("#shareMore").width() / 2) + (($(this).width() + parseInt($(this).css("padding-left")) + parseInt($(this).css("padding-right"))) / 2);
					$("#shareMore").css({left: leftCalc + 'px', top: ($(this).offset().top + 15) + 'px'});
					if ($("#emailBox").is(":visible")) {
						$("#emailBox").animate({height: "hide"}, 125, function() {
							$("#shareMore").animate({height: "show"}, 250);
						});
					} else {
						$("#shareMore").animate({height: "show"}, 250);
					}
				}
				return false;
			}).css({cursor: "pointer"});
		});

		// Send email. Uses a php script to send email. Query string shows if it succeded or not. Uses jsHTML.js
		var emailSend = jsTVNZ.Common().getQuestionMark("email");
		if (emailSend == "fail" || emailSend == "success") {
			jsHTML.email(".tools .email a", jsTVNZ.Common().getGlobal('articleId'), $("#featureStory h3").text(), jsTVNZ.Common().getGlobal('keyword'), document.location, 395);
			if (emailSend == "fail") {
				$("#emailBox .title span").html("We're having some problems reaching that email address. Please check it and try again.");
			} else {
				$("#emailBox .title span").html("Thank you. Your email has been sent.");
			}
			$("#emailBox .close").click(function() {
				$("#emailBox").animate({height: "hide"}, 250);
				return false;
			}).css({cursor: "pointer"});
			// remove appended query string
			q = top.location.href.replace('?email=' + emailSend,'');
			$("#emailBox input[name=articleUrl]").attr({value: q});
			$("#emailBox .button").click(function() {
				$("#emailForm").submit();
				return false;
			});
			$("#emailBox").css({display: "block"});
		}

		// email Box
		$(".tools .email a").each(function() {
			var $this = $(this);
			$(this).click(function() {
				if (($("#emailBox").is(":hidden") == false) && ($("#emailBox").is(":visible") == false)) {
					// calls the HTML from jsHTML
					jsHTML.email(this, jsTVNZ.Common().getGlobal('articleId'), $("#featureStory h3").text(), jsTVNZ.Common().getGlobal('keyword'), document.location, 395);
					$("#emailBox .close").click(function() {
						$("#emailBox").animate({height: "hide"}, 250);
						return false;
					}).css({cursor: "pointer"});
					$("#emailBox .button").click(function() {
						$("#emailForm").submit();
						return false;
					});
					if ($("#shareMore").is(":visible")) {
						$("#shareMore").animate({height: "hide"}, 125, function() {
							$("#emailBox").animate({height: "show"}, 250);
						});
					} else {
						$("#emailBox").animate({height: "show"}, 250);
					}
				} else if ($("#emailBox").is(":visible")) {
					$("#emailBox").animate({height: "hide"}, 125, function() {
						var leftCalc = $this.offset().left - ($(this).width() / 2) + (($this.width() + parseInt($this.css("padding-left")) + parseInt($this.css("padding-right"))) / 2);
						$(this).css({left: leftCalc + 'px', top: ($this.offset().top + 15) + 'px'}).animate({height: "show"}, 125);
					});
				} else {
					var leftCalc = $(this).offset().left - ($("#emailBox").width() / 2) + (($(this).width() + parseInt($(this).css("padding-left")) + parseInt($(this).css("padding-right"))) / 2);
					$("#emailBox").css({left: leftCalc + 'px', top: ($(this).offset().top + 15) + 'px'});
					if ($("#shareMore").is(":visible")) {
						$("#shareMore").animate({height: "hide"}, 125, function() {
							$("#emailBox").animate({height: "show"}, 250);
						});
					} else {
						$("#emailBox").animate({height: "show"}, 250);
					}
				}
				return false;
			}).css({cursor: "pointer"});
		});
		
		// read the font-size cookie, and if its not null, set the font-size
		var tvnzFontSize = jsTVNZ.Common().readCookie("TVNZ-Fontsize");
		if (tvnzFontSize != null && $('#featureStory').is(":visible")) {
			$('#featureStory').css('font-size', tvnzFontSize + "px");
		}
	}

	var setGlobal = function(_variable, _value) {
		globalObj[_variable] = _value;
	}

	var getGlobal = function(_variable) {
		return globalObj[_variable];
	}

	// Creates a Cookie
	var 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=/";
	}
	// Reades a Cookie
	var 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;
	}
	
	// Deletes a Cookie
	var eraseCookie = function(name) {
		jsTVNZ.Common().createCookie(name,"",-1);
	}

	// Finds the first a tag in a element and makes the entire element clickable
	var initSuperClick = function() {
		$(".superClick").click(function() {
			if ($(this).children("a").length>0) {
				document.location = $(this).children("a:first").attr("href");
			}
		});
	}
	
	// Highlights alternating words
	var initHighlightAlt = function() {
		$("#channelSchedule h6 .highlight").each(function() {
			$(this).html(spanAlternate($(this).html()));
		});
	}
	
	var spanAlternate = function(str) {
		var arr = new Array();
		for (var i = 0; i < str.split(" ").length; i++) {
			if (i % 2) {
				arr.push("<span>" + str.split(" ")[i] + "</span>");
			} else {
				arr.push(str.split(" ")[i]);
			}
		}
		return arr.join(" ");
	}

	// get a Query String value.
	var getQuestionMark = function(name) {
		var getPath = "?" + top.location.href.split("?")[1];
		var start=getPath.indexOf("?"+name+"=");
		if (start<0) start=getPath.indexOf("&"+name+"=");  
		if (start<0) return '';
		start += name.length+2;
		var end=getPath.indexOf("&",start)-1;
		var endHash=getPath.indexOf("#",start)-1;
		if (endHash<0) endHash=getPath.length;
		if (end<0) end=getPath.length;
		if (endHash < end) {
			var result=getPath.substring(start,endHash);
			var result='';
			for(var i=start;i<=endHash;i++) {
				var c=getPath.charAt(i);
				result=result+(c==' + '?' ':c);
			}
		} else {
			var result=getPath.substring(start,end);
			var result='';
			for(var i=start;i<=end;i++) {
				var c=getPath.charAt(i);
				result=result+(c==' + '?' ':c);
			}
		}
		return unescape(result);
	}
	
	return {
		initSetHomepage : initSetHomepage,
		initWeatherLocation : initWeatherLocation,
		getServerTime : getServerTime,
		setCurrentDate : setCurrentDate,
		disableTools : disableTools,
		fixUpMyIE6 : fixUpMyIE6,
		initCheckFlash : initCheckFlash,
		initSuperClick : initSuperClick,
		initPageTools : initPageTools,
		setGlobal : setGlobal,
		getGlobal : getGlobal,
		createCookie : createCookie,
		readCookie : readCookie,
		eraseCookie : eraseCookie,
		initHighlightAlt : initHighlightAlt,
		getQuestionMark : getQuestionMark
	}
}

function jump(sel) {
	var url = sel.options[sel.selectedIndex].value;
	if ( url != '' ) top.location = url;
}
