jQuery(function($) {
	var deviceAgent = navigator.userAgent.toLowerCase();
	is_iOS = deviceAgent.match(/(iphone|ipod|ipad)/);
	is_android = deviceAgent.match(/android/);
	//is_iOS = true; // testing
	if(is_iOS || is_android) { addScrollButtonsToThumbnailContainer(); }

	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
	
	$(".thumb a").click(function(e) {
		e.preventDefault();
		$("#videoThumbs .activeThumb").removeClass('activeThumb');
		$("#textInVideo").hide();
		$(this).addClass('activeThumb');
		var p = $(this).parents(".thumb");
		var vid = p.attr('id').split('_')[1];
		var currentDescription = "<p>" + p.find('.videoDescription').text().split("#").join("</p><p>") + "</p>";
		var currentTitle = $('img', this).attr('title');
		$("#videoTitle").text(currentTitle);
		$("#description").css('visibility', 'visible').find(".description").html(currentDescription);
		$("#description .fullResLink").attr('href', '/videos/sv3470/?v=' + vid).css('visibility', 'visible');
		playVideo(vid);
	});
	var loaded_videoID = getURLParamValue('videoID');
	if(loaded_videoID) {
		var thumb = $("#videoThumbs_inner #v_" + loaded_videoID + " a");
		$.scrollTo("#playContainer");
		$("#videoThumbs").scrollTo("#v_" + loaded_videoID)
		thumb.click();
	}
	/*$(".trim a").click(function(e) {
		//not yet in use, please Jack come up with some sweet trims we can photograph!
		e.preventDefault();
		$(".selectedTrim").removeClass("selectedTrim");
		$(this).addClass("selectedTrim");
		var bgi = $('img', this).attr('src').split('th_s').join('s').replace('.jpg', '.gif');
		console.log(bgi);
		$("#video_overlay").css('backgroundImage', "url("+bgi+")");
	});*/
	$("#overlay").click(function(e) {
		overlay(false);
	});
});




function playVideo(vID) {
	theVideo = "/videos/sv/sv";
	theVideo += vID + ".mov";
	var hqVideo = "/videos/sv/sv" + vID + ".mov";
	var lowVideo = "/videos/sv/sv" + vID + ".mp4";
	var webmVideo = "/videos/sv/sv" + vID + ".webm";
	var ogvVideo = "/videos/sv/sv" + vID + ".ogv";
	/* the iOS class causes the video to have relative positioning and a higher z-index than the overlaying frame, which sadly is a total hack. */
	var videoClass = (is_iOS) ? "iOS " + vID : vID; 
	h5video = '<video height="280" width="528" autobuffer controls="" autoplay="autoplay" class="'+videoClass+'"><source src="'+lowVideo+'" type="video/mp4"><source src="'+webmVideo+'" type="video/webm"><source src="'+ogvVideo+'" type="video/ogg"></video>';
	if(!supportsFlash) {
		if(typeof _gaq !== "undefined") {
			_gaq.push(['_trackEvent', 'skyv-videos', 'html5play', vID]);
		}
		$("#video")
			.html(h5video)
			.find('video')
			.bind('ended', deletePlayer);
		
	} else {
		if(typeof player == "undefined" || typeof player.sendEvent == "undefined") {
			createPlayer(theVideo, typeof player !== "undefined");
			if(typeof _gaq !== "undefined") {
				_gaq.push(['_trackEvent', 'skyv-videos', 'play', vID]);
			}
		}
		else {
			player.sendEvent('STOP');
			player.sendEvent('LOAD',theVideo);
			if(typeof _gaq !== "undefined") {
			_gaq.push(['_trackEvent', 'skyv-videos', 'replay', vID]);
		}
		}
	}
}
function createPlayer(theVideo, switchVideo) {
	var stageW = 528;
	var stageH = 280;
	var flashvars = {};
	var params = {};
	params.bgcolor = "#000000";
	params.allowfullscreen = "false";
	window.bugTheVideo = theVideo;
	window.bugSwitchVideo = switchVideo;
	flashvars.autostart = (!!switchVideo)?"false":"true";
	flashvars.controlbar = "none"; // "over", "none", "bottom", "top"
	flashvars.smoothing = "false";
	flashvars.icons = "false";
	flashvars.stretching = "none";
	flashvars.bufferlength = 3;
	flashvars.displayclick = "none";
	params.wmode = "transparent";
	flashvars.stageW = stageW;
	flashvars.stageH = stageH;
	flashvars.file = theVideo;
	attribs = {};
	attribs.id = "video";
	attribs.name = "video";
	swfobject.embedSWF("/products/eScape/player-licensed.swf", "video", stageW, stageH, "9.0.0", "/common/swfobject/expressInstall.swf", flashvars, params, attribs);
}
function playerReady(obj) {
	//console.info('the videoplayer '+obj['id']+' has been instantiated');
	player = document.getElementById(obj['id']);
	player.addModelListener("STATE","playState");
	if(bugSwitchVideo) {
		//console.log('bugfix in effect');
		player.sendEvent('STOP');
		player.sendEvent('LOAD',bugTheVideo);
	}
}
function deletePlayer() {
	if(typeof _gaq !== "undefined") {
		_gaq.push(['_trackEvent', 'skyv-videos', 'html5play-end', bugTheVideo]);
	}
	delete player;
	$("#video").replaceWith('<div id="video"></div>'); 
	$("#textInVideo").show();	
}
function playState(o) {
	if(o.newstate === "COMPLETED") {
		if(typeof _gaq !== "undefined") {
			_gaq.push(['_trackEvent', 'skyv-videos', 'play-end', bugTheVideo]);
		}
		deletePlayer();
		overlay(false);
		$("#duration span, #vid span, #np span").text("");
	}
	if(o.newstate === "PLAYING" && o.oldstate === "BUFFERING") {
		if(typeof _gaq !== "undefined") {
			_gaq.push(['_trackEvent', 'skyv-videos', 'play-begin']);
		}
		overlay(true);
		//$("#duration, #vid, #np").css({ visibility: 'visible', opacity: 1}).show();
	}
}
function overlay(turnOn) {
	if(!overlaySupported) return;
	if(turnOn) {
		turnedOn = true;
		$("body").addClass('overlayOn');
		$("#overlay").fadeIn();
		$("#videoThumbs").css('opacity',.4).hoverIntent(thumbs_over, thumbs_out);
	} else {
		turnedOn = false;
		$("body").removeClass('overlayOn');
		$("#overlay").fadeOut();
		$("#videoThumbs").css('opacity',1);
	}
}
function thumbs_over() {
	if(turnedOn) {
		//console.log('over event occurred');
		$(this).fadeTo('fast',1);
		//$(this).removeClass('o_60');;
	}
}
function thumbs_out() {
	if(turnedOn) {
		//console.log('out event occurred');
		$(this).fadeTo('slow',.6);
		//$(this).addClass('o_60');
	}
}
function addScrollButtonsToThumbnailContainer() {
	// for devices which do not support internally-scrolling elements
	$("#videoThumbs").addClass('withScroller');
	$("#videoThumbs_outer").prepend("<div class='scroller left'><img src='/images/left_arrow.gif' style='width: 6px; height: 11px;' /></div>").append("<div class='scroller right'><img src='/images/right_arrow.gif' style='width: 6px; height: 11px;' /></div><div style='clear: both;'></div>");
	$("#videoThumbs_outer .scroller").click(function(e) {
		var vTi_sL = $("#videoThumbs")[0].scrollLeft;
		var vTi_sW = $("#videoThumbs")[0].scrollWidth;
		if($(this).hasClass('left')) {
			//console.log('before ' + $("#videoThumbs")[0].scrollLeft);
			$("#videoThumbs").scrollTo("-=381px", 800, {axis: "x"});
			//$("#videoThumbs").scrollTo("-=381px", 800, {onAfter: removeScrolling});
			//$("#videoThumbs")[0].scrollLeft = Math.min(0, vTi_sL - 381);
			//console.log('after ' + $("#thumbs_inner_wrap")[0].scrollTop);
		} else {
			//console.log('before ' + $("#videoThumbs")[0].scrollLeft + " vTi_sW: " + vTi_sW + " vti_sL: " + vTi_sL);
			$("#videoThumbs").scrollTo("+=381px", 800, {axis: "x"});
			//$("#videoThumbs").scrollTo("+=381px", 800, {onAfter: removeScrolling});			//$("#videoThumbs")[0].scrollLeft = Math.max(vTi_sW, vTi_sL + 381);
			//console.log('after ' + $("#thumbs_inner_wrap")[0].scrollTop);
		}
	});
}

