//var uid = new Date().getTime();
//var flashProxy = new FlashProxy(uid, 'img/JavaScriptFlashGateway.swf');

var isgal = true;

var flapdist = 10;
var flapspeed = 300;
var flapeffect = "easeOutQuad";
var flapeffect = "easeOutBack";

var player_idx = 1;



$(document).ready(function () {
	if($(".gal").length == 0)
		isgal = false;
	init();
});

// For testing only.
var showClickArea = false; //location.href.search("clickarea=1") > -1 ? true : false;
var noFlashForImages = true; //location.href.search("noflash=1") > -1 ? true : false;
var scrollActionsDisabled = false;

var pli = new Array();

function log(msg) {
	if(typeof console == 'undefined') return;
	if(typeof console.log == 'undefined') return;
	
	console.log(msg);
}


function openGallery()
	{
		removeHaptic();
		var gal = $(this).closest(".gal");
		var item = $(this).closest(".item");
		
		if(gal.hasClass("current") && item.hasClass("current"))
		{
			gal.find(".item").removeClass("current");
			var n = $(this).closest(".item").next();
			if(n.length == 0)
				n = $(this).closest(".gal").find(".item").eq(0);
			n.addClass("current");
			if(n.get(0) != $(this).closest(".item").get(0))
				$("#balken").hide();
		}
		else
		{
			$("#balken").hide();
			$(".gal").removeClass("current");
			gal.addClass("current");
			gal.find(".item").removeClass("current");
			item.addClass("current");
		}
		updateView();
		// Load all thumbs in the gallery.
		$(".gal.current .thumb").each(function() {
			var $this = $(this)
			if($this.find("img").size()) return;
			
			$this.append($("<img>").attr("src", $this.attr("rel")).click(openGallery))
		})
	}

function init()
{

	$("#contentOuter").scroll(function() {
		//console.log("Scroll: " + scrollActionsDisabled);
		if(scrollActionsDisabled)
			return;
		//console.log("Scrolling...");
		
		var $currentGal = $(".gal.current");
		$("#contentInner > .current").removeClass("current");
		
		removeHaptic();
		
		$currentGal.find("item:not(.current)").hide();
		$currentGal.find("item:not(.current)").find(".thumb").hide();
		$currentGal.find(".current").show();
		$currentGal.find(".current .thumb").show();
		$currentGal.css("height", $(this).find(".current .thumb img").height());
		$currentGal.css("width", $("#contentInner").width());
		$currentGal.find(".flash").hide();
		$currentGal.find(".v-navigation").hide()
	})
	
	/*
$(".gal, .flash").each(function()
	{
		var cacheImage = document.createElement("img");
		cacheImage.src = $(this).attr("rel");
		pli.push(cacheImage)
		log("Preloading IMG: " + $(this).attr("rel"))
	});
*/
	$("#footer img").each(function()
	{
	/*
	var cacheImage = document.createElement("img");
		cacheImage.src = $(this).attr("hoverimg");
		pli.push(cacheImage)
	
*/	
		$(this).hover(function(){
			var savedsource = $(this).attr("src");
			$(this).attr("src", $(this).attr("hoverimg"));
			$(this).attr("hoverimg", savedsource);
		},function(){
			var savedsource = $(this).attr("src");
			$(this).attr("src", $(this).attr("hoverimg"));
			$(this).attr("hoverimg", savedsource);
		});
	});
	
	$("#footer a").attr("onfocus", "this.blur();");
	$("#header a").attr("onfocus", "this.blur();");
	
	updateView();
	
	/*
	$("#balkeninner").flash({
		src: 'img/text.swf',
		height: '100%',
		width: '100%',
		swliveconnect: 'true',
		name: 'balkenflash',
		id: 'balkenflash',
		allowscriptaccess: 'sameDomain',
		wmode: 'transparent'
	});
	*/
	
	//var tag = new FlashTag('img/text.swf', "100%", "100%");
	//tag.setFlashvars('lcId='+uid);
	//$("#balkeninner").html(tag.toString());
	
	$(window).resize(function()
	{
		updateView();
	});
	
	$(".thumb img, #balken").click(openGallery);
	
	$(".flash, .flashover").unbind("click", clickFlash).click(clickFlash);
	
	$("#header, #footer, .gal, #contentInner").mouseover(function(ev) {
		if(ev.target.tagName != "IMG" && $(ev.target).closest("#balken").length == 0 && $(ev.target).closest(".flashover").length == 0)
			$("#balken").hide();
	});
	
	$("#closer a").click(function(ev) {
		ev.preventDefault();
		$("#contentInner > .current").removeClass("current");
		$("#balken").hide();
		updateView();
	});
	
/*
	$("#header, #footer").click(function(ev) {
		$(".thumb").each(function() {
			if((ev.target.id == "header" && ev.pageY > 60) || (ev.target.id == "footer" && ev.pageY < ($("#footer").offset().top + 40)))
			{
				if($(this).offset().left < ev.pageX && $(this).offset().left + $(this).width() > ev.pageX && $(this).offset().top < ev.pageY && $(this).offset().top + $(this).height() > ev.pageY)
				{
					$(".gal").removeClass("current");
					var gal = $(this).closest(".gal");
					gal.addClass("current");
					var item = gal.find(".item").eq(0);
					gal.find(".item").removeClass("current");
					item.addClass("current");
					ev.stopPropagation();
					ev.preventDefault();
					updateView();
				}
			}
		});
		
	});
*/	
	$(".thumb img").live("mouseover", function(){
		$(this).closest(".item").prepend($("#balken"));
		$("#balkeninner").html('<img src="' + $(this).closest(".gal").attr("rel") + '">');
		//changeText($(this).closest(".gal").attr("rel"));
		$("#balken").css("top", ($(this).height() - $("#balken").height()) / 2);
		window.status = window.status + ".";
		if($(this).closest(".gal").attr("rel") != "")
			$("#balken").show();
		else
			$("#balken").hide();
	});
}

function clickFlash() {
		removeHaptic();
		var n;
		if(!$(this).closest(".item").hasClass("current"))
		{
			$("#balken").hide();
			$(this).closest(".gal").find(".item").removeClass("current");
			$(this).closest(".item").addClass("current");
		}
		else
		{
			$(this).closest(".gal").find(".item").removeClass("current");
			n = $(this).closest(".item").next();
			if(n.length == 0)
				n = $(this).closest(".gal").find(".item").eq(0);
			n.addClass("current");
			if(n.get(0) != $(this).closest(".item").get(0))
				$("#balken").hide();
		}
		updateView();
		// Find all videos and yeah, well, stop them.
		$(".gal.current").find(".item").each(function() {
			var $this = $(this)
			
			if(!$this.find(".video").size()) return;
			if(!$this.find(".flash table").size()) return;
			
			try {
				var api = $this.find(".flash td:first").data("flashembed").getApi()
				api.sendEvent('STOP');
			}
			catch(e) {
				//log(e)
			}
		})
		// Start the shown video.
		try {
			var n = $(".gal.current .item.current")
			var api = n.find(".flash td:first").data("flashembed").getApi()
			api.sendEvent('PLAY');
		}
		catch(e) {
			//log(e)
		}
}

var imgindex = 0;
var oldindex = -1;

/*
$(document).mousewheel(function(ev, delta) {
	if(delta == 0)
		return;
	var absdelta = delta / Math.abs(delta);
	
	var incontent = false;
	$(ev.target).parents("div").each(function() {
		if($(this).attr("id") == "content" || $(this).attr("id") == "balken")
			incontent = true;
	});
	if($(ev.target).attr("id") == "content" || $(ev.target).attr("id") == "balken")
		incontent = true;
	if(incontent)
	{
		//imgindex -= absdelta;
		$("#contentInner > .current").removeClass("current");
		removeHaptic();
		updateView();
		scrollToGal($("#content .gal").eq(imgindex - absdelta));
	}
	ev.preventDefault();
});
*/

$(document).click(function(ev)
{
	if(($(ev.target).closest(".flash,.thumb,#balken,object,embed,.v-navigation").length == 0) || ($(ev.target).closest("table").length > 0 && $(ev.target).closest("object,embed").length == 0))
	{
		$("#contentInner > .current").removeClass("current");
		removeHaptic();
		updateView();
	}
});

function scrollToGal(gal)
{
	var gals = $("#content .gal");	
	var newindex = 0;
	
	gals.each(function() {
		if($(this).get(0) == gal.get(0))
		{
			imgindex = newindex;
		}
		newindex++;
	});
	
	
	var befindex = imgindex;
	if(imgindex < 0)
		imgindex = 0;
	if(imgindex > gals.length - 1)
		imgindex = gals.length - 1;
	
	if(oldindex != imgindex)
	{
		$("#balken").hide();
		//$("#balken").css("top", "-10000px");
		var newtop = (gals.eq(imgindex).offset().top - gals.eq(0).offset().top) - 40;
		
		/*
		$("#contentInner").stop();
		$("#contentInner").animate({
			top: newtop
		}, 500, "easeOutQuad");
		*/
		$("#contentOuter").stop();
		scrollActionsDisabled = true;
		$("#contentOuter").animate({
			scrollTop: newtop
		}, 500, "easeOutQuad", function() {
			setTimeout(function() {
				scrollActionsDisabled = false;
			}, 100)
			
		});
		oldindex = imgindex;
	}
}

function addFlash(item)
{
	var imgsrc = item.find(".img span").attr("rel");
	var flash = item.find(".flash");

	if(imgsrc)
	{
		if(flash.length > 0 && !flash.html())
		{
			
			/*
flash.flash({
				src: 'img/img.swf',
				scale: 'exactfit',
				height: '100%',
				width: '100%',
				wmode: 'transparent',
				flashvars:{
					img: imgsrc
				}
			});
*/
			if(noFlashForImages) {
				flash.css("background", "url(/img/loading.gif) no-repeat center center");
				flash.append($("<img>").attr("src", imgsrc).addClass("flash-image").hide().load(
					function() { flash.css("background", "none"); $(this).show(); }));
			}
				
			else {
				flash.flashembed({
					src: 'img/img.swf',
					scale: 'exactfit',
					height: '100%',
					width: '100%',
					wmode: 'transparent'
				}, {
					img: imgsrc
				});
			}
			
			flash.prepend('<div class="flashover"></div>');
		}
	}
	else
	{
		//if(flash.length > 0 && $("#video").attr("rel") != item.find(".video").attr("rel"))
		if(flash.length > 0 && !flash.html())
		{
			var vals = item.find(".video").attr("rel").split(",");
			item.find(".flash").html('<table border="0" cellspacing="0" cellpadding="0" height="100%"><tr valign="middle"><td></td></tr></table>');
			if(vals[3] == "1"){ 
				var repeatit = "always";
			} else {
				var repeatit = "none";
			}
			// Find the thumbnail to the flash movie.
			var thumb = "";
			try {
				var img = item.find(".thumb").attr("rel") || item.find(".thumb img").get(0).src
				var thumb = img.replace("150h", vals[1] + 'h')
			}
			catch(e) {
				log(e)
			}
			// Only autostart if the video is the first on the list, otherwise
			// all videos start in parallel.
			var autostart = flash.parent(".item").hasClass("current") ? true : false;
			var api = item.find(".flash td").flashembed({
				src: './player/player5.swf',
				height: vals[1],
				width: vals[0],
				repeat: repeatit,
				wmode: 'transparent',
				menu: 'false',
			}, {
				file: 'http://www.markglassner.com/files/'+vals[2],
				skin: 'http://www.markglassner.com/player/simple.swf',
				controlbar: 'over',
				repeat: repeatit,
				menu: 'false',
				autostart: autostart,
				image: thumb
			});
		}
	}
}

function updateView()
{

	$(".flashover").unbind("mouseenter");
	var somecurrent = false;
	var curisvideo = false;
	
	var maxheight = $("#footer").offset().top - $("#header").height() - 80;
	
	$(".gal").each(function() {
		if($(this).hasClass("current"))
		{
			somecurrent = true;
			if($(this).get(0) == $(".gal").get(0) || $(this).get(0) == $(".gal:last").get(0))
				maxheight += 40;
			var gal = $(this);
			var curitem = gal.find(".current");
			var previtem = curitem.prev(".item");
			var nextitem = curitem.next(".item");
			var prevgal = gal.prev(".gal");
			var nextgal = gal.next(".gal");
			
			gal.find("img").unbind("mouseenter");
			gal.find("img").unbind("mouseleave");
			
			prevgal.find("img").unbind("mouseenter");
			prevgal.find("img").unbind("mouseleave");
			prevgal.find("img").hover(function(){
				$(this).stop();
				$(this).animate({
					top: flapdist
				}, flapspeed, flapeffect);
			},function() {
				$(this).stop();
				$(this).animate({
					top: 0
				}, flapspeed, flapeffect);
			});
			
			nextgal.find("img").unbind("mouseenter");
			nextgal.find("img").unbind("mouseleave");
			nextgal.find("img").hover(function(){
				$(this).stop();
				$(this).animate({
					top: 0 - flapdist
				}, flapspeed, flapeffect);
			},function() {
				$(this).stop();
				$(this).animate({
					top: 0
				}, flapspeed, flapeffect);
			});
			
			curitem.unbind("mouseenter");
			curitem.unbind("mouseleave");
			
			nextitem.unbind("mouseenter");
			nextitem.unbind("mouseleave");
			nextitem.hover(function(){
				$(this).stop();
				$(this).animate({
					marginLeft: 0-flapdist
				}, flapspeed, flapeffect);
			},function() {
				$(this).stop();
				$(this).animate({
					marginLeft: 0
				}, flapspeed, flapeffect);
			});
			
			previtem.unbind("mouseenter");
			previtem.unbind("mouseleave");
			previtem.hover(function(){
				$(this).stop();
				$(this).animate({
					marginLeft: flapdist
				}, flapspeed, flapeffect);
			},function() {
				$(this).stop();
				$(this).animate({
					marginLeft: 0
				}, flapspeed, flapeffect);
			});
			
			if($(this).find(".video").length > 0)
			{
				curisvideo = true;
				var vals = $(this).find(".video").attr("rel").split(",");
				
				vals[0] = parseInt(vals[0]);
				vals[1] = parseInt(vals[1]);
			}
			
			addFlash(curitem);
			addFlash(previtem);
			addFlash(nextitem);
			
			if(curisvideo)
				maxheight = Math.max(maxheight, vals[1] + 40);
			
			gal.css("height", maxheight);
			gal.css("width", $("#contentInner").width());

			gal.find(".flash").each(function() {
				var maxwidth = Math.round(parseInt($(this).parent().find(".img span").css("width")) / parseInt($(this).parent().find(".img span").css("height")) * maxheight);
				
				if($(this).parent().get(0) == curitem.get(0) && !curisvideo)
				{
					if(maxwidth > $("#contentInner").width() - 160)
					{
						maxwidth = $("#contentInner").width() - 160;
						maxheight = parseInt($(this).parent().find(".img span").css("height")) / parseInt($(this).parent().find(".img span").css("width")) * maxwidth;
						gal.css("height", maxheight);
					}
				}
				
				if(curisvideo)
				{
					maxwidth = vals[0] / vals[1] * maxheight;
					maxwidth = vals[0];
					maxwidth = vals[0];
				}
				
				var thisleft = 0;
				if($(this).parent().get(0) == curitem.get(0))
					thisleft = ($("#contentInner").width() - maxwidth) / 2;
				else if($(this).parent().get(0) == nextitem.get(0))
					thisleft = $("#contentInner").width() - 40;
				else if($(this).parent().get(0) == previtem.get(0))
					thisleft = 40 - maxwidth;
				else
					$(this).hide();

				$(this).css("height", maxheight);
				$(this).css("width", maxwidth);
				$(this).css("left", thisleft);
				
				if($(this).parent().get(0) == curitem.get(0))
				{
				
					$(this).parent().prepend($("#closer"));
					
					$("#closer").css("left", parseInt(thisleft) + parseInt(maxwidth) - parseInt($("#closer").width()));
					var ctop = 0 - $("#closer").height();
					if(curisvideo)
						ctop += (maxheight - (vals[1])) / 2;
					$("#closer").css("top", ctop);
					
					//$("#closer").show();
				}
				
				/*
				$(this).animate({
					left: thisleft
				}, 500, "easeOutQuad");
				*/
				// Only do this for videos.
				if(curisvideo) {
					// Also prevent the controllers from being used as navigation part.
					if($(this).parents(".item").find(".v-navigation").size() <= 0) {
						var $this = $(this);
						var containerHeight = $(this).height();
						var height = vals[1];
						var width = vals[0];
						var controllerHeight = 20;
						var playButtonHeight = 40;
						var offset = containerHeight - height;
						// Subtract the size for the play button.
						height -= playButtonHeight;
						
						var $navigation_div = $("<div>").css("background", "transparent")
												        .css("width", width-4)
												        .css("height", (height/2))
												        .css("position", "absolute")
												        .css("left", thisleft)
												        .css("top", offset/2)
												        .css("zIndex", 20)
												        .addClass("v-navigation")
						if(showClickArea)
							$navigation_div.css("border", "2px solid red");
					    $this.parents(".item").append($navigation_div)
					    var $navigation_div = $navigation_div.clone()
					    $navigation_div.css("height", (height/2)-playButtonHeight)
									   .css("top", (height/2)+playButtonHeight+(offset/2))
						if(showClickArea)
							$navigation_div.css("border", "2px solid red");
					    $this.parents(".item").append($navigation_div)
				
					}
					$(this).parents(".item").find(".v-navigation").css("left", thisleft);
					$(this).parents(".item").find(".v-navigation").show();
					$(this).unbind("click");
					$(this).parents(".item").find(".v-navigation")
										   .unbind("click")
										   .click(clickFlash)
					// Hide the .v-navigation for each video which is not the current.
					if($(this).parents(".item.current").size() != 1)
						$(this).parents(".item").find(".v-navigation").hide()
				}
			});
			
			if(noFlashForImages && !curisvideo) {
				$(this).find("img.flash-image").css("width", $(this).width).css("height", $(this).height());
			}
			
			
			curitem.find(".flashover").hover(function(){
				$(this).closest(".item").prepend($("#balken"));
				$("#balkeninner").html('<img src="' + $(this).closest(".flash").attr("rel") + '">');
				//changeText($(this).closest(".flash").attr("rel"));
				$("#balken").css("top", ($(this).height() - $("#balken").height()) / 2);
				if($(this).closest(".flash").attr("rel") != "")
					$("#balken").show();
				else
					$("#balken").hide();
			}, function(){
				
			});
			
			previtem.find(".flash").unbind("click", clickFlash).click(clickFlash);
			nextitem.find(".flash").unbind("click", clickFlash).click(clickFlash);
			
			curitem.find(".flash").show();
			nextitem.find(".flash").show();
			previtem.find(".flash").show();
			
			curitem.find(".thumb").hide();
			nextitem.find(".thumb").hide();
			previtem.find(".thumb").hide();
			
			/*var mh = 0;
			if(isgal)
				mh = maxheight - 130;
			scrollToGal(gal, mh);*/
			scrollToGal(gal);
		}
		else
		{
			$(this).find("item:not(.current)").hide();
			$(this).find("item:not(.current)").find(".thumb").hide();
			$(this).find(".current").show();
			$(this).find(".current .thumb").show();
			$(this).css("height", $(this).find(".current .thumb img").height());
			$(this).css("width", $("#contentInner").width());
			$(this).find(".flash").hide();
			$(this).find(".v-navigation").hide()
		}
	});
	
	// Uncomment if this is wanted
	if(isgal)
		$("#contentInner").css("padding-bottom", maxheight - 130);
	
	if(!somecurrent)
		$("#closer").hide();
	if(!curisvideo)
		$("#video").hide();
	else
		$("#video").show();
}

function changeText(str)
{
	window.setTimeout("ffst('"+str+"')", 100);
}

function ffst(str)
{
	flashProxy.call('SetText', str);
}

function removeHaptic()
{
	$(".item").unbind("mouseenter");
	$(".item").unbind("mouseleave");
	$(".thumb img").unbind("mouseenter");
	$(".thumb img").unbind("mouseleave");
	$(".item").stop();
	$(".item").css("margin-left", "0px");
	$(".thumb img").stop();
	$(".thumb img").css("top", "0px");
}

/*
function changeText(str)
{
	$("#balkeninner").empty();
	$("#balkeninner").flash({
		src: 'img/text.swf',
		height: '100%',
		width: '100%',
		swliveconnect: 'true',
		name: 'balkenflash',
		id: 'balkenflash',
		allowscriptaccess: 'sameDomain',
		wmode: 'transparent',
		flashvars: {
			text: str
		}
	});
}
*/
