// start position of the carousel (this must be set before the initialization of the carousel!)
var start_position = 0;
// current 4 video combination active inside the carousel
var current_carousel = null;
// active (viewed) au pair number
var aupair_number = "";
// boolean to tell logic whether or not to show unavaliable message
var video_is_available = true;
var leaving_site = false;

function playStarted() {
	$("#post-roll").hide();
}
function playEnded() {
	$("#post-roll").show();
}
function check_hash() {
    //if browser back button was clicked and we're at the index page, return to the prior page
	if (window.location.hash < 2 && leaving_site == false){	
		leaving_site = true;
		history.back();
	}	
	//if browser back/forward button was clicked, load the appropriate video
	else if (location.hash.substring(1) != aupair_number) {		
		aupair_number = location.hash.substring(1);
		beginLoad(true, true);
    }
}
// initialize the carousel with custom values
function initializeCarousel(){
	/*-  Start the carousel -*/
	$(".carousel").jCarouselLite({
		btnNext: ".next",
		btnPrev: ".prev",
		visible: 4,
		scroll: 4,
		circular: true,
		start: start_position,
		init: function(carousel){
			current_carousel = carousel;    
		},
		afterEnd: function(carousel){
			current_carousel = carousel;
		}
	});
	$("#items li").bind("click", function(){loadVideo(this, true); return false;});
}
$(document).ready(function() {
	aupair_number = location.hash.substring(1);
	// changing country logic	
	$("#countries").change(function(e) {
		var country = $(this).val();
		$.post("index.php", {set_country:country}, function(data){
			$(".items-holder").remove();
			if(data.ResultNumber > 4 ){
				$("#prev").show();
				$("#next").show();
				$("#carousel-holder").append("<div class='items-holder carousel'><ul id='items'>" + data.Results + "</ul></div>");				
			}
			else{
				$("#next").hide();
				$("#prev").hide();
				$("#carousel-holder").append("<div class='items-holder static'><ul id='items'>" + data.Results + "</ul></div>");
			}
			beginLoad(e.loadRandomVideo, e.autoPlay);
		}, "json");
	});
	
	//allowing access by query string (for google analytics reports)
	if(location.search.substring(1) != "")
		location.hash = location.search.substring(1).toUpperCase().replace("=","");
	
	beginLoad(true, true);	
	$(".next-video").bind("click", function(){nextVideo(); return false;});
	
	//if flash 6.0.65 or higher isn't present the express install isn't going to work
	if (!(swfobject.hasFlashPlayerVersion("6.0.65"))) {
		$("#info").before('<div class="flashnotice">Please <strong><a href="http://get.adobe.com/flashplayer/">install Flash Player</a></strong> to view au pair videos.</div>');
		$("#video-holder").hide(); }
	
	//back button support
	if (window.XMLHttpRequest){ //not updating hashes for IE6, so not polling either
		hashCheck = setInterval("check_hash()", 100);
	}
});

/*- Determine if video is valid, and load if so
	@loadActiveVideo - tells code whether or not to load the active au pair or force the first video in the list.
	@autoPlay - passes directly to the loadVideo function to determine whether or not to play the video on loading.
-*/
function beginLoad(loadActiveVideo, autoPlay){	
	// forces the first item of the list to be loaded
	if(!loadActiveVideo){
		start_position = 0;
		loadVideo($("#items li:eq(0)"), autoPlay);
		initializeCarousel();
		return;
	}	
	if(aupair_number != ""){		
		var exit_function = false;
		// loop through carousel and see if there is a matching video
		$("#items li").each(function(j){
			if($(this).attr("class") == aupair_number){
				$("#unavailable").hide();
				start_position = j;
				loadVideo(this, autoPlay);
				exit_function = true;
			}
		});
		// video is not valid
		if(!exit_function){
			// if code reaches this point, video was not found 
			if($("#countries").val() != "All Videos"){
				// switch country combobox to all videos and re-get all videos
				$("#countries").val("All Videos");
				var event = jQuery.Event("change");
				event.loadRandomVideo = true;
				event.autoPlay = true;
				$("#countries").trigger(event);
			}
			// if code reaches here, "all videos" is selected,
			// but video is still not found, show unavaliable message
			// and load first video in list
			else{
				video_is_available = false;
				start_position = 0;
				loadVideo($("#items li:eq(0)"), autoPlay);
			}
		}
	}
	else{
		autoPlay = false;	
		start_position = 0;
		loadVideo($("#items li:eq(0)"), autoPlay);
	}
	// initialize the carousel with the above settings
	initializeCarousel();
}

/*- Skip to the next video in the carousel -*/
function nextVideo(){
	var activeLi = $("#items li:has(img[class='currentItem'])");
	var carousel_div = $(".carousel").length;
	if(carousel_div){
		for(i = 0;i < current_carousel.length; i++){ 
			//if the current video is in the carousel
			if($(current_carousel[i]).attr("class") == $(activeLi).attr("class")){ 
				// if we are on the last item in the carousel, then rotate the carousel
				if(i == current_carousel.length-1)
					$(".next").trigger("click");
				break;
			}
		}
	}
	//load the next video
	var nextLi = $(activeLi).next();
	if($(nextLi).attr("class"))
		loadVideo(nextLi, true);
	else
		loadVideo($(".items-holder ul li:first"), true);
}

/*-
	Load a video
	@li - list item to load video from
	@autoPlayVideo - auto play the video upon loading
-*/
function loadVideo(li, autoPlayVideo) {
	swfobject.removeSWF("video"); //trying to prevent IE errors
	try {
		// set the current item class
		$("#video-holder").append('<div id="video"></div>');
		$("li img").removeAttr("class");
		$("img", li).attr("class", "currentItem");
		if(video_is_available){
			$("#unavailable").hide();
		}
		else{
			$("#unavailable").show();
			video_is_available = true;
		}		
		$("#post-roll").hide();
		aupair_number = $(li).attr("class");
		if (window.XMLHttpRequest){ //not updating hashes for IE6 as it causes JS errors
			location.hash = aupair_number;
		}
		
		// get aupair information
		$.get("index.php", {get_video : aupair_number}, function(data){
			var flashvars = { enablecallbacks : "t" };
			
			// enable autoplay based on parameter
			if (autoPlayVideo) {
				flashvars = { autoplay : "t", enablecallbacks : "t" };
			}
			
			swfobject.embedSWF(data.ViddlerLink, "video", "565", "492", "9.0.0", "http://aupairvideos.com/_share/js/expressInstall.swf", flashvars, 
				// params
				{ wmode : "transparent", allowScriptAccess : "always", allowFullScreen : "true" });
			
			// set au pair information to various fields			
			$("#info").html(data.AupairFirstName + ", " + data.AupairAge + " from " + data.AupairResidence);
			
			var wufooLink = "https://culturalcare.wufoo.com/forms/available-au-pair-interest-alert/def/field330=" + aupair_number;
			if(data.IsSecondYear == "1"){
				$("#info").append(" &nbsp; <span class='badge'>Second Year</span>");				
			}
			if(data.IsAvailableNow == "1"){
				$("#info").append(" &nbsp; <span class='badge badge2'>Available Now</span>");
				wufooLink += "&field345=transition.true";
			}
			$(".interest span, #post-roll a.interest").html("I'm interested in " + data.AupairFirstName);
			$(".interest").attr("href", wufooLink);	
			$("#mail").attr("href", "https://culturalcare.wufoo.com/forms/send-this-video-to-a-friend/def/field12=" + aupair_number);
			$('.badge').corners();		
			try {pageTracker._trackPageview('/?'+aupair_number)} catch(e){} //google analytics tracking
		}, "json");	
		if ((autoPlayVideo)) {$('html, body').animate({scrollTop:100}, 'slow');}
	}
	catch (e) {}
}
