var videos_per_row = 4;
var video_offset_left = 200; // left of video icon positions, updated after page load
var video_offset_top = 140; // top of video icon positions, updated after page load
var video_basewidth = 150; // updated after page load
var video_basemargin = 5; // updated after page load
var video_ratio = 3/4; // height to width ratio
var video_hover_enlarge = 1.8; // enlargement multiplier
var video_fillpercent = 60; // percent of screen to fill when viewing video
var video_count = 0; // number of videos, updated after page load
var currentposition = -1;
var currentlyplaying = false;

$(document).ready(function() {
	// fill the positioning variables
	video_count = $('.video').length;
	video_offset_left = $('.videos').offset().left;
	video_offset_top = $('.videos').offset().top; //contentoffset.top + parseInt($('#content').css('margin-top')) + $('#content .headingimage').height();
	video_basewidth = $('.video:first').innerWidth();
	video_basemargin = parseInt($('.video:first').css('margin-left'));
	DisableTextSelection($('body'));
	
	// do the positioning
	$('.video').each(function(index) {
		var pos = CalculateVideoPosition(this);
		$(this).css({left : pos.left, top : pos.top});
	});
		
	$('.videos').css({
		height:	parseInt($('.video:last').css('top'))+$('.video:last').height()
	});
	
	// wire the mouse events
	$('.video').mouseenter(function() {
		BlurVideo($(".video[position='"+currentposition+"']"));
		FocusVideo(this);
		
		currentposition = $(this).attr('position');
	});
	
	$('.video').mouseleave(function() {
		BlurVideo(this);
	});
	
	
	$('.video').click(function() {
		PlayVideo(this);
	});
	
	$('.videowindow').live('click', function() {
		StopVideo();
	});
	
	$(window).resize(function() {
		var video_height = 0;
		var video_width = 0;
		
		if($(window).height() < $(window).width()) {
			video_height =($(window).height() * video_fillpercent) / 100;
			video_width = video_height / video_ratio;
		}
		else {
			video_width = ($(window).width() * video_fillpercent) / 100;
			video_height = video_width * video_ratio;  
		}
		
		$('.videowindow .window').css({
			width: video_width,
			height: video_height,
			left: ($(window).width() - video_width) / 2,
			top: ($(window).height() - video_height) / 2
		});
		
		$('.videowindow .window embed').css({
			width: video_width,
			height: video_height});
		
		$('.videowindow .closebutton').css({
			left: parseInt($('.videowindow .window').css('left')) + $('.videowindow .window').width() - $('.videowindow .closebutton').width(),
			top: parseInt($('.videowindow .window').css('top')) - $('.videowindow .closebutton').width()
		});
	});
	
	
	// keyboard navigation
	$(document).keydown(function(e) {
		if(currentlyplaying) {
			StopVideo();
			return;
		}
		
		var newposition = currentposition;
		switch(e.keyCode) {
		case 37:
			// left
			newposition--;
			if(newposition < 0)
				newposition = video_count -1;
			break;
		case 38:
			// up
			newposition-= videos_per_row;
			if(newposition < 0) { 
				newposition = (video_count - (video_count % videos_per_row)) + currentposition % videos_per_row;
				if(newposition >= video_count)
					newposition -=videos_per_row;
			}
			break;
		case 39:
			// right
			newposition++;
			if(newposition >= video_count)
				newposition = 0;
			break;
		case 40:
			// down
			newposition+= videos_per_row;
			if(newposition >= video_count)
				newposition = (newposition % videos_per_row);
			break;
		case 13:
			// enter
			PlayVideo($(".video[position='"+currentposition+"']"));
			break;
		}
		
		// position debugging: $('.headingimage').attr('src',"/includes/headingimage.php?text=Cur:"+currentposition+" New:"+newposition);
		if(newposition != currentposition) {
			BlurVideo($(".video[position='"+currentposition+"']"));
			FocusVideo($(".video[position='"+newposition+"']"));
			
			currentposition = newposition;
		}
	})
});

function FocusVideo(element) {
	$(element).stop().animate({
		width : video_basewidth * video_hover_enlarge,
		height : (video_basewidth * video_ratio) * video_hover_enlarge,
		'margin-top': (-(((video_basewidth * video_ratio) * video_hover_enlarge)-(video_basewidth * video_ratio))/2)+'px',
		'margin-right': (-(((video_basewidth * video_hover_enlarge) - video_basewidth)/2))+'px',
		'margin-bottom': (-(((video_basewidth * video_ratio) * video_hover_enlarge) - (video_basewidth * video_ratio))/2)+'px',
		'margin-left': (-(((video_basewidth * video_hover_enlarge) - video_basewidth))/2)+'px'				
		},
		300);
	
	$(element).children('.videoinfoshade, .videoinfo').css({
		top: ((video_basewidth * video_ratio) * video_hover_enlarge - $('.videoinfoshade').height())+'px',
		display: 'block',
		'z-index': 15
		});
	
	$(element).css({'z-index': 10});
	
	$(element).children('.videoinfo').css({'z-index': 20}).fadeIn(500);
}

function BlurVideo(element) {
	$(element).animate({
		width : video_basewidth,
		height : (video_basewidth * video_ratio),
		'margin-top': video_basemargin+'px',
		'margin-right': video_basemargin+'px',
		'margin-bottom': video_basemargin+'px',
		'margin-left': video_basemargin+'px'
		},
		300);
	// IE can't take the heat, so stop fading animations on all but the latest
	if($.browser.msie)
		$('.video').not(element).stop().css({
			width : video_basewidth,
			height : (video_basewidth * video_ratio),
			'margin-top': video_basemargin+'px',
			'margin-right': video_basemargin+'px',
			'margin-bottom': video_basemargin+'px',
			'margin-left': video_basemargin+'px'
		});
	
	$(element).children('.videoinfoshade').css({
		display: 'none',
		'z-index': 2
		});
	
	$(element).css({'z-index': 1});
	
	$(element).children('.videoinfo').css({'z-index': 3}).fadeOut(500);
}

function PlayVideo(element) {
	// play the video
	
	// if it's a link, simply redirect to the location
	if($(element).attr('external') == 'link') {
		window.location.href = $(element).attr('videopath');
		return;
	}
	
	currentlyplaying = true;
	
	var video_height = 0;
	var video_width = 0;
	
	if($(window).height() < $(window).width()) {
		video_height =($(window).height() * video_fillpercent) / 100;
		video_width = video_height / video_ratio;
	}
	else {
		video_width = ($(window).width() * video_fillpercent) / 100;
		video_height = video_width * video_ratio;  
	}
	
	var video_path = $(element).attr('videopath');
	var video_trackername = video_path.substring(video_path.lastIndexOf('/')+1,video_path.length);
	var video_controlshidden = ($(element).attr('hidecontrols').toLowerCase()) == 'true';
	
	// append the element
	$('body').append(
			"<div class='videowindow'>"
			+"<img class='closebutton' alt='close' src='/applications/videos/data/icon_redx.png' style='display: none;' />"
			+"<div class='shading'></div>"
			+"<div class='window' style='width: 1px; height: 1px;'>"
				+"<img class='previewimage' src='#' />"
					+"<embed id='movie' name='movie' type='application/x-shockwave-flash' src='"+video_path+"' width='"+video_width+"' height='"+video_height+"' quality='high' quality='high' loop='false' wmode='window' menu='true' allowScriptAccess='always'></embed>"
				+"</object>"
			+"</div>"
			+"</div>");
	$('.videowindow .window img').attr('src', $(element).children('img').attr('src'));
	$('.videowindow embed').hide(); // this will slide all around if displayed before it's ready, and can't start hidden because jquery has problems with adjusting it while hidden, and flash doesn't load in chrome on hidden elements
	
	// if the size of the shading is obviously wrong (IE6?), fix it
	if($('.videowindow .shading').height() != $(window).height())
		$('.videowindow .shading').height($(window).height());
	
	// position the (tiny 1x1) window in the very center so it grows from the right place
	$('.videowindow .window').css({
		left: $(window).width() / 2,
		top: $(window).height() / 2
	});
	
	// animate the window growing
	$('.videowindow .window').animate({
			width: video_width,
			height: video_height,
			left: ($(window).width() - video_width) / 2,
			top: ($(window).height() - video_height) / 2
		},
		1000, function() {
			$('.videowindow .previewimage').fadeOut(100, function() {
				$('.videowindow embed').show();
			});
	});	
	
	// display the flash controls
	// this must happen after the embed element has arrived at it's final position or
	// the flash control will be positioned incorrectly.
	setTimeout(function() {
		$('.videowindow embed').each(function() {
			var readyfunction = function () { $('.videowindow embed').flashcontrol({ hidden : video_controlshidden })};
			FlashReadyWait(this, readyfunction, 100, 5000);
		});
	}, 3000);
	
	// close button
	setTimeout(function() {
		$('.videowindow .closebutton').css({
			left: parseInt($('.videowindow .window').css('left')) + $('.videowindow .window').width() - $('.videowindow .closebutton').width(),
			top: parseInt($('.videowindow .window').css('top')) - $('.videowindow .closebutton').width()
		});
	}, 2000);
	$('.videowindow .closebutton').delay(2000).fadeIn(1000);
	
	// track video view on GA
	TrackView(video_trackername);
}

function FlashReadyWait(flashobject, onreadyfunction, waitdelay, maxwaitms, waitedms) {
	if(typeof waitedms == 'undefined')
		waitedms = 0;
	
	if(typeof flashobject.TGetProperty == 'function' || typeof flashobject.TGetProperty == 'unknown') {
		onreadyfunction();
	}
	else if(waitedms < maxwaitms) {
		setTimeout(function() { waitedms += waitdelay; FlashReadyWait(flashobject, onreadyfunction, waitdelay, maxwaitms, waitedms); }, waitdelay);
	}
	else {
		// failed to load.
	}
}

function StopVideo() {
	currentlyplaying = false;
	$('.videowindow embed').each(function() {
		if(typeof this.destroyflash == 'function')
			this.destroyflash();
	});
	$('.videowindow').empty().remove();
}

function CalculateVideoPosition(element) {
	return {
		'left' : (video_offset_left + ($(element).attr('position')%videos_per_row) * (video_basewidth+video_basemargin*2))+'px',
		'top' : (video_offset_top + Math.floor($(element).attr('position')/videos_per_row) * ((video_basewidth*video_ratio)+video_basemargin*2))+'px'
	}
}

function DisableTextSelection(elements) {
	elements.each(function(){
		if($.browser.mozilla){
			$(this).css('MozUserSelect','none');
		}
		else if($.browser.msie){
			$(this).bind('selectstart', function() { return false; });
		}
		else{
			$(this).mousedown(function() { return false; });
		}
	});	
}

function TrackView(video_title) {
	var category = 'Application Video View';
	pageTracker._trackEvent(category, video_title);
	return false;
}
