// JavaScript Document

var images=[];
var imageWidths=[];
var imageHeights=[];
var curImage=-1;
var numImages=0;
var img = new Image();
var curImageURL="";
var clickAction=0; // -1 = left, +1 = right, 0 = nowt
var bShowingVideo=false;
var ytplayer=null;
var LBFailTimer=-1;

var imgW=-1, imgH=-1;

var bShowButtons=true;

$(document).ready(function(){
	
	$("div#lightBox").mousemove(function(evt){
		MouseMovedInBox(evt);
		}).click(LightBoxClick);
	
	$("img#lightBoxPic").click(LightBoxClick);
	
	$("div#lightBoxImage").click(LightBoxClick);
	
	// get youtube thumbnail if required
	if ($("img#videoThumbOverlay").size()>0)
	{
		var str = GetYTThumb(images[numImages-1], "");
		$("img#videoThumb").attr("src",str);
		$("img#videoThumbOverlay").css("opacity", "0.25").mouseenter(function(){
			$(this).css("opacity", "0.5")
		}).
		mouseleave(function(){
			$(this).css("opacity", "0.25")
		}).click(function(){
			OpenLightBox(images[numImages-1], bShowButtons);
		});
		//$("div#videoBox div#screensBoxMid").css("height", "240px");
	}
	
	// esc key closing of light box
	$(document).keypress(function(evt){
			if (evt.keyCode==27 && $("div#lightBox").is(":visible"))//esc key
			{
				evt.preventDefault();
				CloseLightBox();
				return false;
			}
		});
	});

function OpenLightBox(url, bShowNextPrev)
{	
	imgW=-1;
	imgH=-1;
	curImageURL=url;
	
	bShowButtons = bShowNextPrev;

	$("object#videoPlayer").remove(); // remove any video players hanging around
	if (curImage==-1)
	{
		$("div#lightBox div#lightBoxText").show();
		$("div#lightBox div#lightBoxImage").hide();
		var tpos = $(window).scrollTop() + ($(window).height()/2) - 50;
		tpos = Math.max(tpos, 8);
		var lpos = ($(window).width()/2) - 75;
		$("div#lightBox").css({top: ($(window).height()/2)+'px', left: ($(window).width()/2)+'px', width:'0px', height:'0px'})
					.animate({width: '150px', height: '100px', top: tpos, left: lpos}, 500);
	}
	else
	{
		$("div#lightBox div#lightBoxText").show();
		$("div#lightBox div#lightBoxImage").hide();
	}
	
	// hide the buttons
	$("div#lightBoxTabLeft").hide();
	$("img#lightTabEndL").hide();
	$("div#lightBoxTabRight").hide();
	$("img#lightTabEndR").hide();
	$("img#closeLB").hide();
	
	curImage=-1;
	for (var i=0; i!=numImages; i++)
	{
		if (images[i] == url)
		{
			curImage = i;
			break;
		}
	}
	if (curImage==-1)
	{
		curImage=99;
		images[99] = url;
		bShowButtons=false;
	}
	
	if (!bShowButtons)
	{
		$("div#lightBoxTabLeft").hide();
		$("img#lightTabEndL").hide();
		$("div#lightBoxTabRight").hide();
		$("img#lightTabEndR").hide();
	}
	
	if (url.indexOf('www.youtube.com')!=-1)
	{
		bShowingVideo=true;
		
		if ($("img#videoThumb").attr("src")=="images/layout/videoBlank.gif")
		{
			GoatMessage("Sorry, YouTube is not currently responding.  Check back soon and hopefully the gremlins will have left YouTube towers");
		}
		else
		{
			images[99]=url;
			curImage=99;
			var p = url.indexOf('v=');
			var str = images[curImage].substr(p+2);
			
			$("div#lightBoxVideo").append("<div id='vpReplace'></div>");
				
			var params = { allowScriptAccess: "always" };
			var atts = { id: "videoPlayer" };
			swfobject.embedSWF("http://www.youtube.com/v/"+str+"?enablejsapi=1&playerapiid=ytplayer", 
						 "vpReplace", "835", "505", "8", null, null, params, atts);
			imgW=835; imgH = 505;
			setTimeout(TestFlash, 1000);
			ImageLoaded();
		}
	}
	else
	{
		FetchImageSize(url);
		bShowingVideo=false;
		$(img).unbind('load').load(ImageLoaded);
		img.src = url;
		clearTimeout(LBFailTimer);
		LBFailTimer = setTimeout(LBFail, 7000);
	}
	
	//$("html").animate({scrollTop:"0"}, 250);
}

function LBFail()
{
	GoatMessage("Sorry, the server is not responding.  Please try again soon");
	CloseLightBox();
}

function ImageLoaded()
{
	if (imgW<0 || imgH<0)
	{
		setTimeout(ImageLoaded, 250);
		return; // waiting for image data
	}
	imageWidths[curImage] = imgW;
	imageHeights[curImage] = imgH;
		
	clearTimeout(LBFailTimer);	
	LBFailTimer=null;
	
	if ($("div#lightBox").is(":animated"))
	{
		setTimeout(ImageLoaded, 500);
	}
	else
	{
		DisplayImage();
	}
}

function DisplayImage()
{
	if (curImage==null || curImage=='undefined' || images[curImage]=='undefined')
	{
		return;
	}
	var tpos = $(window).scrollTop() + ($(window).height()/2) - (imageHeights[curImage]/2);
	if (imageHeights[curImage]>500)
		tpos += 75;
	tpos = Math.max(tpos, 30);
	var lpos = ($(window).width()/2) - (imageWidths[curImage]/2);
	lpos = Math.max(lpos, 12);
	$("div#lightBox").animate({width: imageWidths[curImage]+'px', height: imageHeights[curImage]+'px', top: tpos+'px', left: lpos+'px'}, 500);
	//setTimeout(ShowImage, 500);
	ShowImage();
}

function ShowImage()
{
	if (images[curImage].indexOf('www.youtube.com')!=-1)
	{
		$("div#lightBox div#lightBoxText").hide();
		$("div#lightBoxVideo").show();
	}
	else
	{
		$("div#lightBox div#lightBoxText").hide();
		$("div#lightBox div#lightBoxImage img#lightBoxPic").attr("src", images[curImage]).fadeIn(500);
		$("div#lightBox div#lightBoxImage").show();
	}
	$("img#closeLB").show();
}

function MouseMovedInBox(evt)
{
	clickAction=0;
	if (bShowingVideo || !bShowButtons)
		return;
	var top = $("div#lightBox").offset().top;
	if (evt.pageY < top + 20)
	{
		$("div#lightBoxTabLeft").hide();
		$("img#lightTabEndL").hide();
		$("div#lightBoxTabRight").hide();
		$("img#lightTabEndR").hide();
		return;
	}
	else
	{
		if (evt.pageX < $(window).width()/2)
		{
			clickAction=-1;
			$("div#lightBoxTabLeft").show();
			$("img#lightTabEndL").show();
			$("div#lightBoxTabRight").hide();
			$("img#lightTabEndR").hide();
		}
		else
		{
			clickAction=1;
			$("div#lightBoxTabLeft").hide();
			$("img#lightTabEndL").hide();
			$("div#lightBoxTabRight").show();
			$("img#lightTabEndR").show();
		}
	}
}

function LightBoxClick()
{
	if (bShowingVideo==true)
		return true; // true to propgate click into flash object
	if (!bShowButtons)
	{
		CloseLightBox();
		return false;
	}

	if (clickAction==-1)
	{
		// go left
		curImage--;
		if (curImage<0)
		{
			curImage = numImages;
			do
			{
				curImage--;
				
			} while (images[curImage].indexOf('www.youtube.com')!=-1);	
		}
		OpenLightBox(images[curImage], bShowButtons);
	}
	else if (clickAction==1)
	{
		// go right
		curImage++;
		if (curImage>=numImages || images[curImage].indexOf('www.youtube.com')!=-1)
		{
			curImage = 0;
		}
		OpenLightBox(images[curImage], bShowButtons);
	}
	return false;
}

function CloseLightBox()
{
	curImage=-1;
	if (bShowingVideo)
	{
		if (ytplayer==null || ytplayer=='undefined')
			return false;
		ytplayer.pauseVideo();
		ytplayer=null;
	}
	else
	{
		$("div#lightBox div#lightBoxImage img#lightBoxPic").fadeOut(500);
	}
	$("div#lightBox div#lightBoxText").hide();
	var tpos = $("div#lightBox").offset().top +  ($("div#lightBox").height()/2) - 100;
	$("div#lightBox").animate({width: '0px', height: '0px', top:tpos+'px', left: ($(window).width()/2)+'px'}, 505,
							function(){$(this).hide();});
	return false;
}

function onYouTubePlayerReady(playerid)
{
	ytplayer = document.getElementById("videoPlayer");
	if (ytplayer==null || ytplayer=='undefined')
		return;
	ytplayer.seekTo(0, false);
	ytplayer.playVideo();
}

function TestFlash()
{
	if (ytplayer==null || ytplayer=='undefined')
	{
		$("div#vpReplace").append("<br><br><br><b>Sorry, but you need the latest flash player to view video content</b><br><br>"+
							  "To get the latest player for your browser, <A href='http://www.adobe.com/go/gntray_dl_getflashplayer'>"+
							  "Click Here</a><br><br><br>");
	}
}

// pass in the youtube url
function GetYTThumb( url, size )
{
  if(url === null || url=='undefined'){ return ""; }

  size = (size === null) ? "big" : size;
  var vid;
  var results;

  results = url.match("[\\?&]v=([^&#]*)");

  vid = ( results === null ) ? url : results[1];

  if(size == "small")
  {
  	return "http://img.youtube.com/vi/"+vid+"/2.jpg";
  }
  else
  {
  	return "http://img.youtube.com/vi/"+vid+"/0.jpg";
  }
}

function FetchImageSize(url)
{
	$.post("bin/common.php", {action:"getSize", address:url}, function(data){
		var pos = data.indexOf("x");
		if (pos!=-1)
		{
			imgW = parseInt(data.substr(0,pos));
			imgH = parseInt(data.substr(pos+1));
		}
	}, function(){
		// failure from server
		alert("bugger"); // tbd remove
	});
}
