/********************************************************************************************
TVNZ Ondemand Javascript Library functions list:
********************************************************************************************/

var jsTVNZondemand = window.jsTVNZondemand || {};

//UTILS --------------------------------------------------------------
function SetExternalLinks(){
	/*
	Purpose: checks all <a>'s in the doc, if it has a rel attribute of 'external', sets to open in new window
	usage: <a href="http://www.google.com" rel="external">Google</a>
	*/
	$('a[rel=external]').click(function(){ window.open(this.href); return false; });
}



function lightOff(){
	if ($.browser.msie && $.browser.version >= 7 && $.browser.version < 9) {
		$("#container").css("position", "static");
	}
	
	if ($.browser.msie) {
		$("#adSkin").css("top", "240px");
	}
	
	$(".jBoxOverlay").fadeTo("slow",0.95);
	$(".jBoxOverlay").css("z-index",500);
	$("#video-container .video-overlay").fadeTo("slow",0.95);
	$('.popout:visible').animate({height: "hide"}, { duration: 250, easing: 'swing', queue: true });
}

function lightOn(){
	$(".jBoxOverlay").fadeTo("slow",0.0 , function(){
		$(this).css("z-index",10000); 
		$(this).css({display: "none"});
	});
	
	$("#video-container .video-overlay").fadeTo("slow",0.0,function(){
		$(this).css({display: "none"});
	});
	$("#player").css({'z-index':'auto'});
	
}


jQuery.fn.eqByRow = function(){
	/*
	Purpose: equalise the heights of li's in a list by row
	usage: $('#eq-this-list').eqByRow();
	*/
	var inRow 	= Math.floor( $(this).width() / $(this).children("li:first").width() );
	var items 	= $(this).children('li');
	for (var i = 0; i < ($(items).length / inRow); i++){
		var max 	= 0;
		var start 	= (i * inRow);
		for (var j = start; j < start + inRow; j++){
			if(items[j]){
				if( $($(items)[j]).height() > max ) max = $($(items)[j]).height();
			}
		};
		for (var k = start; k < start + inRow; k++){
			if(items[k]){
				$($(items)[k]).height(max);
			}
		};
	};
}

jQuery.fn.biggerClick = function(){
	/*
	Purpose: makes a container 'hot', and binds it click event to go to the location of the first <a>'s href it finds within it
	usage: $('#make-these-hot ul li').biggerClick();
	*/
	$(this).hover(
		function(){
			$(this).addClass("hover");
		},function(){
			$(this).removeClass("hover");
		}
	)
	$(this).click(function(){
		window.location = $(this).find("a:first").attr("href");
	})
}

jQuery.fn.resetDefaults = function(){
	var defaultForm = $(this).data('defaultForm');
	if (defaultForm) {
		$(this).html(defaultForm);
	}
	else {
		defaultForm = $(this).html();
		$(this).data('defaultForm',defaultForm);
	}
	$(this).find("input").each(function(i) {
		$(this).addClass('default-value');
		$(this).focus(function(){
			if ( $(this).attr('value') == $('[name='+$(this).attr('name')+']',defaultForm).val()){
				$(this).attr('value', '');
				$(this).removeClass('default-value');
			}
		});
		$(this).blur(function(){
			var defaultValue = $('[name='+$(this).attr('name')+']',defaultForm).val();
			if( $(this).attr('value') == '' || $(this).attr('value') == defaultValue ){
				$(this).attr('value', defaultValue );
				$(this).addClass('default-value');
			}
		});
	});
};

// Makes the init run at Document ready // Playstation doesn't like the on load
$(window).load(function() {
	jsTVNZondemand.initialize();
	$(".jBoxOverlay , #video-container .video-overlay").click(function(){
		SendMessageToFlash();
	});

});

/*JS call back to flash*/
function SendMessageToFlash() {
	getVideoObject("player").lightOnJS();
}

function getVideoObject(appName) {
	if (navigator.appName.indexOf ("Microsoft") !=-1) {
		return window[appName];
	} else {
		return document[appName];
	}
}

// the Initialize function all sub-functions are called in here.
jsTVNZondemand.initialize = function() {
	jsTVNZondemand.Common().initAccordian();
	jsTVNZondemand.Common().ondemandTools();
}

// TVNZ Common functions, that can be re-called at any point.
jsTVNZondemand.Common = function() {
	// Accordian effect on the watch episodes page - menu for selecting content
	var initAccordian = function() {
		$("dl.findAccordian dt").each(function () {
			$(this).click(function() {
				if (!$(this).hasClass("selected")) {
					$("dl.findAccordian dt.selected").stop().next("dd").children("div").filter(":first").animate({height: 'hide'}, 'fast');
					$("dl.findAccordian dt.selected").removeClass("selected");
					$(this).next("dd").children("div").filter(":first").animate({height: 'show'}, 'fast');
					$(this).addClass("selected");
				}
				return false;
			});
		});
		
		$("dl.recommendedAccordian dt").each(function () {
			$(this).click(function() {
				if (!$(this).hasClass("selected")) {
					$("dl.recommendedAccordian dt.selected").stop().next("dd").children("div").filter(":first").animate({height: 'hide'}, 'fast');
					$("dl.recommendedAccordian dt.selected").removeClass("selected");
					$(this).next("dd").children("div").filter(":first").animate({height: 'show'}, 'fast');
					$(this).addClass("selected");
				}
				return false;
			});
			$("a",this).click(function() {
				$(this).parents("dt").click();
			});
		});
		
		// initialize
		$("dl.findAccordian dt#"+findAShow.getLastSearchId()).click();
		
		// initialize
		$("dl.recommendedAccordian dt:first").click();
	}

	// Ondemand Player
	var ondemandTools = function() {

		var $this = $(this);

		// call other Init functions
		SetExternalLinks();

		
		// Toggle a popup (if given) and ensure all others are hidden
		var togglePopup = function(id) {
			$('.popout:visible').animate({height: "hide"}, { duration: 250, easing: 'swing', queue: true });
			if ( $(id).is(':hidden') ) $(id).animate({height: "show"}, { duration: 500, easing: 'swing', queue: true });
			return false;
		};
		
		togglePopup();
		$("#share-email a").click(function() {
			$('#popout-email').resetDefaults(); 
			$("#close-btn").click(function(){return togglePopup();});
			$("#email-submit a").click(function() {
				//console.log("#btnSubmit clicked");
				var hint = function(form,field,msg) {
					if ( msg && field ) {
						$("#popout-email #message").html(msg);
						$("[name="+field+"]").addClass('form-error');
					}
				};
				$("#popout-email input").removeClass('form-error');
				if (  jsTVNZValidate.validate({ 	
							to: 			{ re: jsTVNZValidateRE.EMAIL,	hint:'Please enter a valid e-mail address to send to'	},
							from: 			{ re: jsTVNZValidateRE.EMAIL,	hint:'Please enter a valid e-mail address for yourself'	},
							sender: 		{ re: jsTVNZValidateRE.NO_PUNC,	hint:'Please enter a name without special characters' }
						},document.forms['email-form'],hint )) {
					$.getJSON("http://runes.tvnz.co.nz/tvnz_email_ondemand_mail.php?callback=?", $("#email-form").serialize(),
						function(data){
							//console.log("getJSON got; " + data.email);
							if(data.email == 'success') {
								$("#popout-email #message").html("Thank you. Your email has been sent.");
							} else {
								$("#popout-email #message").html("We're having some problems reaching that email address. Please check it and try again.");
								$("#popout-email #to").addClass('form-error');
							}
						});
				}
				return false;
			});
			return togglePopup('#popout-email');
		});
		
		$("#share-more a").click(function(){return togglePopup('#popout-more');});

		$('#video-container a[href*=#]').click(function() {
			var $target = $(this.hash);
			if ( $target && $target.offset() ) {
				var targetOffset = $target.offset().top;
				$('html,body').animate({scrollTop: targetOffset}, { duration: 1000, easing: 'swing' });
			}
			return false;
		});

	}
	
	return {
		initAccordian : initAccordian,
		ondemandTools : ondemandTools
	}
}


