//site.js
var bottomNav 	= { yOver:62, yOut:57, yOpenPadding:16, opened:false, over:false, animating:false };
var currentPage	= null;
var subPage		= null;
var pages 		= {};
var changing	= false;

if (!Array.indexOf) {
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) {
      if (this[i] == obj) {
        return i;
      }
    }
  }
}

// Gets a specific flash embedd by its name/id
function getFlashMovie(movieName){
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : document[movieName];
}

function replaceShowPageContent(imageList, json){
	if(window.console){console.log("replacing page contents to page: " + json.title);}
	var title = json.title;
	var copy = json.copy;
	var link = json.link;
	var imageCount= 0;
	var img = $("#supersize .activeslide");
	img.fadeOut(750, function(){
		img.attr("src", imageList[0]);
		img.fadeIn(750);
		
		// change the sIFR title
		replaceSifrText(title);
		
		// change the visit link
		if(link == null || link == undefined || link == ""){
			$(".visit-website").hide();
		}
		else {
			$(".visit-website").attr("href", link);
			$(".visit-website").show();
		}
		
		// change the copy
		$("#pageCopy").html(copy);
		document.title = json["title"] + json["longtitle"];
		
		$('#left').fadeTo("fast", 1);
		$('#right').fadeTo("fast", 1);
		$('#supersize').fadeTo("fast", 1);
		setTimeout(function(){changing = false;}, 750);
		
	});
}

function setupPage(page, hasSlideshow, pageURLs) {
	if(jQuery.browser.flash==true && page != "home"){
		$("#left h1 em").css("width", "300px");
		checkForSIFR();
	}
	
	try{
	if(!console) console = {info:{}, log:{}, error:{}, warn:{}};
	}
	catch(e){}
	
	currentPage = page;
	subPage		= getSubpage();

	
	var pageURLsSplit = pageURLs.split(",");
	var pageNameValuePair;
	for(var i = 0; i < pageURLsSplit.length; i++){
		pageNameValuePair = pageURLsSplit[i].split(":");
		pages[pageNameValuePair[0]] = pageNameValuePair[1];
	}
	
	try{
	console.log("setupPage:: currentPage="+currentPage);
	console.log("setupPage:: subPage="+subPage);
	}
	catch(e){}

	//
	// setup hook to catch internal nav destinations
	$('a[rel="internal"]').click(function(e) {
		var h = $(this).attr("href");
		if(h.indexOf("/" + currentPage) == 0){ // same top-level page ?
			e.preventDefault();
			if(h.indexOf("/shows") == 0){
				window.location.href = "/shows/#/" + h.substring(7, h.length - 4);
				loadSubpageContent();
			};
		} else if(h.indexOf("/shows/") == 0){
				e.preventDefault();
				window.location.href = "/shows/#/" + h.substring(7, h.length - 4);
			};
		}
	);
	
	//setup top nav
	setupTopNav();
	
	// setup bottom nav
	setupBottomNav();
	
	//
	// handle resizes
	$(window).resize(function(){
		$("#programmes").offset({top: $(window).height() - bottomNav.yOffset, left: 0});
	});
	
	//
	// a page with video lightbox?
	if($.fn.fancybox && currentPage) setupVideoLightbox();
	
	//
	// if there's a sub-page, load it
	loadSubpageContent(subPage);
	
	if(currentPage == "shows"){
		if(window.console)console.log(page + " :: " + subPage + " :: " + pages[subPage]);
		
		getPageContentData(pages[subPage]);
		
	}
	else if(currentPage == "home"){
		
		var count = $("#supersize img").length - 1;
		if(count > 1){
			$.ajax({
			  url: "index.php",
			  data: "dataonly=true",
			  dataType: "json",
			  success: function(json){
					var links = json["bg_links"].split(",");
					$("#doVideo").attr("href", links[0]);
					$("#doVideo").unbind();
					setTimeout(function(){cycleHomePageImages(count, 0, "next", links, true)}, 10000);
			  }
			});
		}
		$('#left').fadeTo("fast", 1);
		$('#right').fadeTo("fast", 1);
		$('#supersize').fadeTo("fast", 1);
		
	}
	
		//
	// setup supersize background
	if($.fn.supersized) setupBackgroundSlideshow();

}

function checkForSIFR() {
	var fl = getFlashMovie("sIFR_replacement_0");
	if(fl != undefined){

		setTimeout(function(){replaceSifrText($("#sIFR_replacement_0_alternate").text());}, 1000);
		//replaceSifrText($("#sIFR_replacement_0_alternate").text());
	}
	else {
		setTimeout(checkForSIFR, 50);
	}
}


function setupTopNav(){
	if(currentPage != "/home"){
	// highlight the selected topnav item
		var navElements = $("#nav ul li a");
		var i = navElements.length;
		while(--i>-1) {
			if(window.location.href.indexOf(navElements[i].href) == 0){
				$(navElements[i]).css('text-decoration', 'none');
				$(navElements[i]).css('background-color', '#fff');
				$(navElements[i]).css('color', '#000');
				return;
			};
		}
	}
}


//
//
function getSubpage(){
	if(currentPage != "shows") return null;
	var i = window.location.href.indexOf("/#/");
	if(i >-1) {
		var r = window.location.href.substring(i + 3);
		if(r.length > 1) return r;
	}
	if(window.location.href.indexOf("shows") != -1)return null;
	// no show? default to baby-jake
	window.location.href = "/shows/#/baby-jake";
	return "baby-jake";
	
}
//
function loadSubpageContent(){
	try{
	console.log("loadSubpageContent:" + getSubpage());
	}
	catch(e){}
}


//
//
function setupBackgroundSlideshow(){
	$.fn.supersized.options = {startwidth: 1200,startheight: 800,minsize: .5,slideshow: 0,transition: 1};
	$('#supersize').supersized();
}


//
//


//
//
function setupVideoLightbox(){

	$("a.watch-video-coming").unbind();
	
	// handle clicks to the a.watch-video elements
	$("a.watch-video").fancybox({
		hideOnContentClick:false,
		type:"iframe",
		width:640,
		height:360,
		padding:0,
		margin:0,
		overlayOpacity:0.75,
		overlayColor:"#000000"
	});
	
	$("a#view-all").fancybox({
		hideOnContentClick:false,
		showNavArrows:false,
		showCloseButton:false,
		width:950,
		height:456,
		padding:0,
		margin:0,
		overlayOpacity:0.75,
		overlayColor:"#000000"
	});
}



//
// bottom nav
function onNavAnimateCompete() { bottomNav.animating = false; };
function handleBottomNav(isClick) {
	if(bottomNav.animating) return;
	if(isClick) {
		bottomNav.animating	= true;
		$("#programmes").animate( {"top": $(window).height() - bottomNav.yOffset}, {duration:"slow", queue:false, complete:onNavAnimateCompete});
	} else if(!bottomNav.opened) {
		$("#programmes").animate({"top": $(window).height() - bottomNav.yOffset}, {duration:"fast", queue:false});
	}
}
//
function setupBottomNav(){
	
	// setup bottom nav
	$('#roll-up').mouseover(function(){
		if(!bottomNav.opened) bottomNav.yOffset = bottomNav.yOver;
		handleBottomNav();
	});
	$('#roll-up').mouseout(function(){
		if(!bottomNav.opened) bottomNav.yOffset = bottomNav.yOut;
		handleBottomNav();
	});
	$('#roll-up').click(function(e){
		if(bottomNav.timeout) clearTimeout(bottomNav.timeout);
		bottomNav.timeout = null;
		e.preventDefault();
		
		bottomNav.opened  = !bottomNav.opened;
		bottomNav.yOffset = bottomNav.opened ? ($("#programmesContent").height() + bottomNav.yOpenPadding) : bottomNav.yOut;
		
		// swap the arrow direction
		$(this).css('background-image', bottomNav.opened ? 'url(/assets/images/buttons/rolldown.gif)' : 'url(/assets/images/buttons/rollup.gif)');
		
		handleBottomNav(true);
	});
	
	
	// now, show the nav (opened) at the bottom of the page
	bottomNav.opened  = true;
	bottomNav.yOffset = bottomNav.yOut;
	$('#roll-up').css('background-image', 'url(/assets/images/buttons/rolldown.gif)');
	$("#programmes").css("top", $(window).height() - ($("#programmesContent").height() + bottomNav.yOpenPadding));
	
	// after a 4 sec delay, tween it down
	bottomNav.timeout = setTimeout("$('#roll-up').click()", 4000);
	
	$("#programmesContent span a").click(function(e){
		e.preventDefault();
		if($(this).attr("href") != "#viewall-shows"){
			getPageContentData($(this).attr("href"));
		}
	});
}

function getPageContentData(url){
	if(changing == false){
		if(window.console)console.log("getting page data for: " + url);
		changing = true;
		$.ajax({
		  url: url,
		  data: "dataonly=true",
		  dataType: "json",
		  success: function(json){
			changePageContents(json);
		  }
		});
	}
	else {
		if(window.console)console.log("data request for: " + url + " cancelled because previous data request has not finished");
	}
}

function changePageContents(json){
	if(window.console)console.log("page data loaded for: " + json.title);
	$videoURL = json.videoURL;
	$videoPoster = json.videoPoster;
	
	if($videoURL == "noVideo"){
		$videoURL = null;
		$videoPoster = null;
		$("#doVideo").addClass("watch-video-coming");
		$("#doVideo").removeClass("watch-video");
		$("#doVideo").attr("href", "#");
		$("a.watch-video-coming").unbind();
	} else {
		$("#doVideo").removeClass("watch-video-coming");
		$("#doVideo").addClass("watch-video");
		$("#doVideo").attr("href", "/includes/videoLightbox.html");
		setupVideoLightbox();
	}
	
	// Preload any new images
	var imageList = json.bg.split(",");
	if(window.console)console.log("the page " + json.title + " contains " + imageList.length + " background image(s)");
	for(var i = 0; i < imageList.length; i++){
		if(i == 0){
			if(window.console)console.log("preload image: " + imageList[i] + " before continuing...");
			preloadImage(imageList[i], backgroundImageReady, imageList, json);
		}
		else {
			preloadImage(imageList[i], null);
		}
	}
	
}

function backgroundImageReady(imageList, json){
	
	setTimeout(function(){replaceShowPageContent(imageList, json);}, 500);
	
}

function preloadImage(url, callback, imageList, json){
	$.ajax({
	  url: url,
	  error: function(xmlHttpRequest, textStatus, errorThrown){
		  // ie cannot parse the image so throws an error
		  if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){
			  if(textStatus == "parsererror"){
				if(callback){
					if(window.console){
						console.log("IE preloaded background image: " + url);
					}
				  callback(imageList, json);
				}
			  }
		  }
	  },
	  success: function(){
		if(callback){
			if(window.console){
				console.log("preloaded background image: " + url);
			}
		  callback(imageList, json);
		}
	  }
	});
}

function replaceSifrText(text){
	var fl = getFlashMovie("sIFR_replacement_0");
	if(jQuery.browser.flash == false){
		$("#left h1 em").text(text);
	}
	else {
		if(fl == undefined || fl.replaceText == undefined){
			setTimeout(function(){replaceSifrText(text);}, 100);
		}
		else{
			if($("div #left h1 em").length > 0){
				$("div #left h1 em").css("width", "auto");
				var fontSize = Math.ceil(parseFloat($("div #left h1 em").css("font-size").replace("px", ""))*0.5);
				var textLength = text.length;
				var textWidth = Math.max((textLength * fontSize), 120);
				$("div #left h1 em object").css("background", "none").css("width", textWidth+"px");
				fl.replaceText(text);
			}
		}
	}
}

function cycleHomePageImages(imageCount, currentIndex, currentDirection, links, repeat){
	var direction = currentDirection;
	var index = currentIndex;
	if(direction == "next"){
		if(currentIndex == imageCount - 1){
			direction = "loop";
		}
	}
	else {
		if(currentIndex == 0){
			direction = "next";
		}
	}
	//if(index != imageCount - 1);
	$("#supersize .activeslide").fadeOut(750, function(){
		if(direction == "next"){
			
			$("#supersize img").removeClass("activeslide prevslide");
			index = currentIndex + 1;
			$("#supersize img").eq(index).hide().addClass("activeslide").fadeIn(750);
		}
		else {
			$("#supersize img").removeClass("activeslide prevslide");
			$("#supersize img").eq(0).hide().addClass("activeslide").fadeIn(750);
			index = 0;
		}
		$("#doVideo").attr("href", links[index]);
	});
	if(repeat == true){
		setTimeout(function(){cycleHomePageImages(imageCount, index, direction, links, repeat)}, 10000);
	}

}

$(document).ready(function(){
	//textfields placeholder copy
	var $textfields = $('input[type=text][title], textarea[title]');
	
	$textfields.each(function(){
		var placeholder = $(this).attr('title');
		
		//if it's blank put the title in
		if($(this).val() == '') {
			$(this).val(placeholder);
		}
		
		$(this).focus(function(){
			if($(this).val() == placeholder) {
				$(this).val('');
			}
		});
		
		$(this).blur(function(){
			if($(this).val() == '') {
				$(this).val(placeholder);
			}
		});
		
	});
			
});



