/********************************************************************************************
TVNZ Javascript Library functions list:

jsTVNZ.initialize();
	jsTVNZ.Common().initPageTools();
	jsTVNZ.Common().initHighlightAlt();
	jsTVNZ.Common().initSuperClick();

********************************************************************************************/

var jsTVNZ = window.jsTVNZ || {};
var globalObj = new Object();

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/";

//random number used in requests for DoubleClick ads. Should be different for each page view, but the same within the page.
//var ord=Math.ceil(Math.random()*10000000000000000);

// 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() {
	
	// finds out the current time (needs timer.xml to work)
	www.getServerTime(function() {
		jsTVNZ.Common().setCurrentDate();
	});

	// tools on article/story page
	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();
	
}

// TVNZ Common functions, that can be re-called at any point.
jsTVNZ.Common = function() {

	var setCurrentDate = function() {
		$(".currentTime").html(www.serverTime.dayText + ", " + www.serverTime.monthText + " " + www.serverTime.day + ", " + www.serverTime.hoursAmPm + "." + www.serverTime.minutes + " " + www.serverTime.amPm.toLowerCase());
	}

	var disableTools = function() {
		$(".print").css("display","none");
	}
	

	var initCheckFlash = function() {
		var version = www.getFlashVersion().split(",")[0];
		if (version < 9) {
			$(".noFlashTag").show();
		}
	}

	// 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, urlEncodedArticleTitle, productionUrl, 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
		

		// 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+"; domain=tvnz.co.nz; 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(" ");
	}
	
	return {
		setCurrentDate : setCurrentDate,
		disableTools : disableTools,
		initCheckFlash : initCheckFlash,
		initSuperClick : initSuperClick,
		initPageTools : initPageTools,
		setGlobal : setGlobal,
		getGlobal : getGlobal,
		createCookie : createCookie,
		readCookie : readCookie,
		eraseCookie : eraseCookie,
		initHighlightAlt : initHighlightAlt
	}
}

function JumpToPage(sel) {
	var url = sel.options[sel.selectedIndex].value;
	if ( url != '' ) top.location = url;
}

function CarouselPanel(loadXml){
	
	$.get(loadXml, function(xml) {
		var allItems = $(xml).find("item");
		if(allItems.length > 0){
			var content = "";
			var summary = "";
			var icon = "";
			var singlepanel = "";
			var seconds = 0;
			var watchepisodeuri = "";
			var mainimageuri = "";
			var miniimageuri = "";
			var showpageuri = "";
			
			$.each( allItems, function(i, l){
				content = $(l).find("content").text();
				summary = $(l).find("summary").text();
				icon = $(l).find("icon").attr("uri");
				singlepanel = isSinglePanel($(l).attr("single-panel"));
				seconds = parseInt($(l).attr("seconds"));
				//alert(seconds);
				if(!singlepanel){
					
				}else{
					
				}

			});
		}
	});
	
	function isSinglePanel(s){
		if(s == "false"){
			return false;
		}
		return true;
	}
}

jsTVNZ.initVideoSlider = function (slider, itemCount){
	var currentPage = 1;
	var numPages = (itemCount / 5);

	$(".shows", slider).css("width",(numPages*945));
	$('.showPagination a.nav-button:first', slider).addClass('selected');
	
	//bind clicks for next
	$('.next', slider).click(function() {
		if (currentPage < numPages) {
			showPage(parseInt(currentPage + 1), slider);
			currentPage++;
		}
		return false;
	});
	
	//bind clicks for prev
	$('.previous', slider).click(function() {
		if (currentPage > 1) {
			showPage(parseInt(currentPage - 1), slider);
			currentPage--;
		}
		return false;
	});
	
	//bind clicks for pageButtons
	$('.nav-button', slider).each(function() {
		$(this).click(function() {
			if(currentPage == $(this).text()){
				return false;
			}
			showPage($(this).text(), slider);
			currentPage = parseInt($(this).text());
			return false;
		});
	});
	
	function showPage(page, slider) {
		$(".shows", slider).animate({ left: ((page - 1) * 945 * -1) +"px"}, 500);
		
		$('.showPagination a.nav-button', slider).each(function() {
			if ($(this).text() == page) {
				$(this).addClass('selected');
			}
			else {
				$(this).removeClass('selected');
			}
		});
	}	
}







