/* BEGIN: library-type functions */
if (!window.console || !console.firebug) {
	var names = ["log", "debug", "info", "warn", "error", "assert", "dir", "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace", "profile", "profileEnd"];
	window.console = {};
	for (var i = 0; i < names.length; ++i) {
		window.console[names[i]] = function() {}
	}
}
function go(where) {
	window.location.href = where;
}
/* END: library-type functions */
/* BEGIN: Page specific functions */
function getVideoID(url) {
	var videoIDparts = url.split('/');
	var videoID = videoIDparts[videoIDparts.length - 2]
	return videoID; // eg es002
}
function bottomAlignRightTopContent() {
	ltch = $("#leftTopContent").height();
	rtch = $("#rightTopContent").height();
	rtc_ptop = ltch - rtch;
	if(rtc_ptop < 0) { rtc_ptop = 0; }
	$("#rightTopContent").css({'paddingTop': rtc_ptop + 'px'});
	//rtc = $("#rightTopContent")[0];
	//rtc.style.paddingTop = rtc_ptop + 'px';
}
function setupNextPrevButtons() {
	curThumb = $("#thumbs_vertical a.selected");
	if(!!curThumb.parent().prev().size()) { 
		$("a.prev").css('visibility', 'visible'); 
		var t = $("#thumbs_vertical a.selected").parent().prev().find('img').attr('title');
		$("a.prev").attr('title',t); 
	}
	else {
		$("#prevButton").css('visibility', 'hidden'); 
	}
	if(!!curThumb.parent().next().size()) { 
		$("a.next").css('visibility', 'visible');
		var t = $("#thumbs_vertical a.selected").parent().next().find('img').attr('title');
		$("a.next").attr('title',t); 
	}
	else {
		$("a.next").css('visibility', 'hidden');
	}
	$("a.prev").unbind('click').click(function(e) {
		e.preventDefault();
		//go($("#thumbs_vertical a.selected").parent().prev().find('a').attr('href'));
		var theurl = $("#thumbs_vertical a.selected").parent().prev().find('a').attr('href');
		$.history.load(getVideoID(theurl));
	});
	$("a.next").unbind('click').click(function(e) {
		e.preventDefault();
		//go($("#thumbs_vertical a.selected").parent().next().find('a').attr('href'));
		var theurl = $("#thumbs_vertical a.selected").parent().next().find('a').attr('href');
		$.history.load(getVideoID(theurl));
	});
}
function playVideo(vID) {
	window.currentVideoID = theVideo;
	//console.log('in playVideo, vID: ' + vID);
	var hqVideo = "/videos/es/" + vID + ".mov"; // this variable is unused because the .mov files are not constrained by bitrate. using .mp4 instead
	var lowVideo = "/videos/es/" + vID + ".mp4";
	var webmVideo = "/videos/es/" + vID + ".webm";
	var ogvVideo = "/videos/es/" + vID + ".ogv";
	var theVideo = lowVideo; // .mov files are pretty well unconstraint re: bitrate - approaching 1MB/s
	if(supportsFlash) {
		if(!player || typeof(player) == "undefined" || typeof(player.sendEvent) == "undefined") {
			createPlayer(theVideo);
			if(typeof _gaq !== "undefined") {
				_gaq.push(['_trackEvent', 'eScape-videos', 'play', vID]);
			}
		}
		else {
			player.sendEvent('STOP');
			player.sendEvent('LOAD',theVideo);
			if(typeof _gaq !== "undefined") {
				_gaq.push(['_trackEvent', 'eScape-videos', 'replay', vID]);
			}
		}
	} else {
		//html5 video element is appended instead of swfobject
		//mp4, webm, and ogv videos appended.  Browser's choice.
		html5Video = '<video height="470" width="264" controls="" autoplay="autoplay" class="'+vID+'"><source src="'+lowVideo+'" type="video/mp4"><source src="'+webmVideo+'" type="video/webm"><source src="'+ogvVideo+'" type="video/ogg"></video>';
		//console.log(html5Video);
		if(typeof _gaq !== "undefined") {
			_gaq.push(['_trackEvent', 'eScape-videos', 'html5play', vID]);
		}
		$("#video").html(html5Video);
		// chrome autoplay bug: http://www.google.com/support/forum/p/Chrome/thread?tid=6636ce31ccd9b4e7&hl=en
		h5VidEl = document.getElementsByTagName('video')[0];
		if(h5VidEl) {
			$(h5VidEl)
				.bind('ended', playEnd)
				.bind('canplay', function() {
					this.play();
					playBegin();
				});
		}
	}
}
function createPlayer(theVideo) {
	var stageW = 264;
	var stageH = 470;
	var flashvars = {
		stageW: stageW,
		stageH: stageH,
		file: theVideo,
		autostart: "true",
		controlbar: "none",
		smoothing: "false",
		displayclick: "none",
		icons: "false",
		stretching: "none",
		bufferlength: 3
	};
	//flashvars.repeat = "single";
	//flashvars.loop = "true";
	var params = {
		bgcolor: "#000000",
		allowfullscreen: "false",
		wmode: "transparent"
	};
	//params.wmode = "opaque";
	attribs = {
		id: "eScape_player",
		name: "eScape_player"
	};
	swfobject.embedSWF("/products/eScape/player-licensed.swf", "video", stageW, stageH, "9.0.0", "/common/swfobject/expressInstall.swf", flashvars, params, attribs);
}

var player = null;
function playerReady(obj) {
	player = document.getElementById(obj['id']);
	//player.addModelListener("BUFFER","playBuffering");
	player.addModelListener("STATE","playState");
	if (overlaySupported) { 
		$("#thumbs_vertical").css('opacity',.6).hoverIntent(thumbs_over, thumbs_out);
	}
}
function playBuffering(obj) { // eg: obj == { percentage: 44 }
	//console.log('buffering... ' + obj.percentage + "%");
	myObj = obj;
}
function playState(obj) { //IDLE, BUFFERING, PLAYING, PAUSED, COMPLETED
	currentState = obj.newstate; 
	previousState = obj.oldstate;
	//console.log('playState changed, new state: ' + currentState);	
	//console.log('playState changed, previous state: ' + previousState);	
	if(currentState == "BUFFERING") {
		//$("<img src='/images/ajax-loader.gif' id='bufferingIcon' />").appendTo("#video_wrap");
		$("#bufferingIcon").show();
		//console.log('showing buffering icon');	
	} else {
		setTimeout('$("#bufferingIcon").hide()', 180);
	}
	if(currentState == "COMPLETED") { // completed in v4, idle in v5 http://developer.longtailvideo.com/trac/wiki/Player5Events
		playEnd();
	}
	if(currentState == "PLAYING") {
		setTimeout('$("#bufferingIcon").hide()', 180);
		playBegin();
	}
}
function playBegin() {
	if(typeof _gaq !== "undefined") {
		if(supportsFlash) {
			_gaq.push(['_trackEvent', 'eScape-videos', 'play-begin', currentVideoID]);
		} else {
			_gaq.push(['_trackEvent', 'eScape-videos', 'html5play-begin', currentVideoID]);
		}
	}
	setTimeout('$("#bufferingIcon").hide()', 180);
	if(overlaySupported) {
		$("#overlay").css('height',$('body').height())
		showOverlay();
	}
}
function playEnd() {
	if(typeof _gaq !== "undefined") {
		if(supportsFlash) {
			_gaq.push(['_trackEvent', 'eScape-videos', 'play-end', currentVideoID]);
		} else {
			_gaq.push(['_trackEvent', 'eScape-videos', 'html5play-end', currentVideoID]);
		}
	}
	if(overlaySupported) {
		hideOverlay();
	}
}
function showOverlay() {
	overlayOn = true;
	$('body').addClass('overlayOn');
	//$("#thumbs_vertical").addClass('o_60');
	$("#thumbs_vertical").css('opacity',.6);
	$("#overlay").fadeIn('fast');
}
function hideOverlay() {
	$("#overlay").fadeOut('slow');
	$("#thumbs_vertical").css('opacity',1);
	//$("#thumbs_vertical").removeClass('o_60');
	$('body').removeClass('overlayOn');
	overlayOn = false;
}
function thumbs_over() {
	if(overlayOn) {
		//console.log('over event occurred');
		$(this).fadeTo('fast',1);
		//$(this).removeClass('o_60');;
	}
}
function thumbs_out() {
	if(overlayOn) {
		//console.log('out event occurred');
		$(this).fadeTo('slow',.6);
		//$(this).addClass('o_60');
	}
}
function pageload(hash) {
	//console.log('in pageload, hash: '+hash);
	if(!hash) { return } // no history state
	$("#thumbs_vertical a").each(function() {
		if($(this).hasClass(hash)) { 
			updateActiveVideo($(this), hash);
			//$("#bufferingIcon").show();
			/*$("#video_loading_indicator").html("<img src='" + $("img", this).attr('src') + "' height='470' width='265' style='opacity: 0.5' /><span>BUFFERING...</span>");*/
			return false;
		}
	});
}
function updateActiveVideo(vidObj, hash) {
	if(vidObj.hasClass('selected')) { 
		// clicked on a video that was already selected
		if(supportsFlash) {
			if(!player || typeof(player) == "undefined" || typeof(player.sendEvent) == "undefined") {
				theVideo = "/videos/es/" + hash + ".mp4";
				createPlayer(theVideo);
			}
			else {
				player.sendEvent('SEEK',0);
				setTimeout('$("#bufferingIcon").hide()', 180);
				playBegin();
			}
		}
		else if(typeof(h5VidEl) !== "undefined") {
			if(h5VidEl.currentTime == 0 || h5VidEl.currentTime >= h5VidEl.duration) {
				//console.log('not playing, just hit play()');
				h5VidEl.play();
			} else if(h5VidEl.currentTime > 0 && !h5VidEl.ended && !h5VidEl.paused) {
				//console.log('currently playing, reset currentTime to 0');
				h5VidEl.currentTime = 0;
			}
			return false;
			//playVideo(hash);
		}
		return false; 
	}
	$("#thumbs_vertical a.selected").removeClass('selected');
	$("body").removeClass('noVideo'); //some items are hidden by this class
	vidObj.addClass('selected');
	tdata = vidObj.parents('div.thumb').find('div.thumbdata');
	$("#crumbs span.videoID").text(hash);
	$('#midTopContent td.sceneHead').text(tdata.find('div.videoTitle').text());
	$('#midTopContent p.duration span.minutes').text(tdata.find('div.videoLength').text());
	$('#midTopContent p.duration span.theScene').text(hash);
	$("#leftMidContent a.fullResLink").attr('href', '/videos/1080/?v='+hash).css('visibility', 'visible');
	thtml = tdata.find('div.videoDescription').html();
	$('#leftMidContent .description').html(thtml);
	if(!!$('#leftMidContent .description').text()) {
		$('#description').css('visibility', 'visible');
	} else {
		$('#description').css('visibility', 'hidden');
	}
	$('#leftMidContent span.keywords').text(tdata.find('div.keywords').text());
	if(!!$('#leftMidContent span.keywords').text()) {
		$('#tags_wrap').css('visibility', 'visible');
	} else {
		$('#tags_wrap').css('visibility', 'hidden');
	}
	$('#leftMidContent p.location').css('visibility', 'visible').find('span.location').text(tdata.find('div.location').text());
	// edit notes are disabled in css with p.editnotes { display: none; } so the below is unnecessary
	/*
	
	var editNotes = tdata.find('div.editnotes').text();
	$('#leftMidContent span.editnotes').text(editNotes);
	if(!!editNotes && editNotes !== "none") {
		$('p.editnotes').css('visibility', 'visible');
	} else {
		$('p.editnotes').css('visibility', 'hidden');
	}
	
	*/
	playVideo(hash);
	setupNextPrevButtons();
	bottomAlignRightTopContent();
}
function ajaxThumbs() {
	$("#overlay").click(function(e) {
		hideOverlay();
	});
	
	// THIS IS THE SOURCE OF THE PLAY FUNCTIONALITY!
	$("#thumbs_inner_wrap a").click(function(e) {
		e.preventDefault();
		$.history.load(getVideoID(this.href)); // fires the pageload function for each click (yes this is a bit confusing)
	});
}
function addScrollButtonsToThumbnailContainer() {
	// for devices which do not support internally-scrolling elements
	$("#thumbs_vertical").addClass('withScroller').prepend("<div class='scroller up'><img src='/images/up_arrow.gif' style='width: 11px; height: 6px;' /></div>").append("<div class='scroller down'><img src='/images/downArrow.gif' style='width: 11px; height: 6px;' /></div>");
	$("#thumbs_vertical .scroller").click(function(e) {
		$t = $(this);
		//$t.addClass('scrolling');
		var tiw_sT = $("#thumbs_inner_wrap")[0].scrollTop;
		var tiw_sH = $("#thumbs_inner_wrap")[0].scrollHeight;
		if($t.hasClass('up')) {
			$("#thumbs_inner_wrap").scrollTo("-=390px", 800, {axis: "y", onAfter: removeScrolling});
			//$("#thumbs_inner_wrap")[0].scrollTop = Math.max(0, tiw_sT - 390);
		} else {
			$("#thumbs_inner_wrap").scrollTo("+=390px", 800, {axis: "y", onAfter: removeScrolling});
			//$("#thumbs_inner_wrap")[0].scrollTop = Math.min(tiw_sH, tiw_sT + 390);
		}
	});
}
function removeScrolling() {
	$("#thumbs_vertical .scrolling").removeClass('scrolling');
}
jQuery(function($){
	var deviceAgent = navigator.userAgent.toLowerCase();
	is_iOS = deviceAgent.match(/(iphone|ipod|ipad)/);
	is_android = deviceAgent.match(/(android)/);
	//is_iOS = true; // testing
	supportsFlash = 
		(swfobject.getFlashPlayerVersion().major) 
			? true : 
		(typeof navigator.plugins !== "undefined" 
			&& typeof navigator.plugins["Shockwave Flash"] !== "undefined") 
				? true :
		(typeof navigator.mimeTypes !== "undefined" 
			&& typeof navigator.mimeTypes["application/x-shockwave-flash"] !== "undefined"
			&& typeof navigator.mimeTypes["application/x-shockwave-flash"].description !== "undefined") 
				? true : 
		false;
	//supportsFlash = false; // testing
	
	$.history.init(pageload); 
	setupNextPrevButtons(); 
	bottomAlignRightTopContent(); 
	ajaxThumbs();
	if(is_iOS || !supportsFlash) {
		overlaySupported = false;
		addScrollButtonsToThumbnailContainer();
	}
	if(supportsFlash) {
		// preload buffering icon
		var img = new Image();
		img.src = "/images/ajax-loader.gif";
	}
	/* BEGIN: check height of left nav and move description down if it is outside of nominal range */
	var nsh = $("#nav_side_wrap").height(); //171, 178 below is a fudge factor
	if((nsh - 178) > 0) {
		$("#description").css('top', 180 + (nsh - 171));
	}
	$("#videoQualityContainer .qualitySwitcher").click(function(e) {
		e.preventDefault();
		if(!$(this).hasClass('selectedQuality')) {
			$("#videoQualityContainer .selectedQuality").removeClass('selectedQuality');
			$(this).addClass('selectedQuality');
		}
	});
	$(".clicker").click(function(e) {
		$.history.load(getVideoID($("#thumbs_inner_wrap a.selected").attr('href')));
	});
});


/*
function playerListen() {
	if (player) { 
		//player.addModelListener("STATE","playComplete")
		player.addModelListener("BUFFER","playBuffering");
	} else {
		setTimeout("addListeners()",100);
	}
}*/


