var imgList=[],
	i=0,
	thumbPaths=[];
var wh=0,
	ww=0;
var w=0,
	h=0,
	t=0,
	l=0,
	c=0;
var cpath,
	npath;
var first = true;
var infoOpen = false,
	jobsOpen = false,
	jobLoaded = false;
var jobClose = "<li><a class=\"close clearfix\" rel=\"job\" href=\"#\">&times; Close</a></li>";
var mask = "<div id=\"mask\"></div>";
var gtk = "<div id=\"info\"><iframe src=\"http://player.vimeo.com/video/24143362?title=0&amp;byline=0&amp;portrait=0\" width=\"721\" height=\"404\" frameborder=\"0\"></iframe><a class=\"clearfix\" rel=\"info\" href=\"#\">&times; Close</a></div>";
var contact	= "<div id=\"info\"><p>Jimmy Hansen Production AB<br />Br&auml;nnkyrkagatan 50<br />";
contact		+= "118 22 Stockholm<br /><span title=\"Office phone\">Office phone: +46 8 669 87 87</span><br />";
contact		+= "<span title=\"Cell phone\">Cell phone: +46 707 83 87 87</span><br />";
contact		+= "<span title=\"Cell US\">Cell US: +1 (718) 304-6547</span><br /><br />";
contact		+= "Email: <a href=\"mailto:jimmy@jimmyhansen.com\"><span class=\"mail\">moc.nesnahymmij@ymmij</span></a>";
contact		+= "<br />Assistant: <a href=\"mailto:valter@jimmyhansen.com\"><span class=\"mail\">moc.nesnahymmij@retlav</span></a>";
contact		+= "<br /><br />Represented by:<br />";
contact		+= "Sweden<br /><a href=\"http://www.b-martin.se/jimmy-hansen/\" title=\"Swedish representation\">www.b-martin.se</a><br />";
contact		+= "Germany<br /><a href=\"http://www.double-t-photographers.com/photographers/jimmy-hansen/\" title=\"German representation\">www.double-t-photographers.com</a>";
contact		+= "</p><a class=\"clearfix\" rel=\"info\" href=\"#\">&times; Close</a></div>";
var exhibition	= "<div id=\"info\"><div class=\"clearfix\">";
exhibition		+= "<a class=\"ex clearfix\" href=\"http://jimmyhansen.com/atog\" target=\"_blank\" title=\"A Thousand Shades of Gray\">";
exhibition		+= "<img src=\"./assets/img/gray.jpg\" /></a>";
exhibition		+= "<a class=\"ex clearfix\" href=\"http://jimmyhansen.com/blowup\" target=\"_blank\" title=\"Blow up\">";
exhibition		+= "<img src=\"./assets/img/blowup.jpg\" /></a>";
exhibition		+= "<a class=\"ex clearfix\" href=\"http://jimmyhansen.com/wrapped\" target=\"_blank\" title=\"Lis d'Automne\">";
exhibition		+= "<img src=\"./assets/img/wrapped.jpg\" /></a>";
exhibition		+= "</div><a class=\"clearfix\" rel=\"info\" href=\"#\">&times; Close</a></div>";

var loadJobList = function(cat){
	jobLoaded = false;
	if($("#info").length > 0){
		$("#info").remove();
	}
	if($("#jobList").children().length > 0){
		$("#jobList").children().remove();
	}
	$.ajax({
		type: "GET",
		data: "cat="+cat,
		dataType: "json",
		url: "lib/LoadJobs.php",
		success: function(rsp){
			rsp.splice(-2,2);
			var list = rsp;
			var find = /_/g;
			for(var i=0; i<=rsp.length-1; i++){
				var job = {
					id: i+1,
					cat: cat,
					path: list[i],
					name: list[i].substr(3).replace(find," ")
				}
				thumbPaths[i] = cat + "_thumbs/" + job.path;
				printJob(job);
			}
			addCloseBtn();
			$("#wrapper").append(mask);
			$("#mask").height(wh);
			$("#mask").animate({opacity:1},120);
			$("#jobList").show();
			$("#jobList").animate({opacity:1},240);
			jobsOpen = true;
		},
		error: function(rsp){
			// Error handling
		}
	});
}
var addCloseBtn = function(){
	$("#jobList").append(jobClose);
	$("a[rel=job]").click(function(){
		removeJobList();
	});
}
var removeJobList = function(){
	$("#jobList").animate({
		opacity:0
	},20,function(){
		$("#mask").remove();
		$(this).children().remove();
		$(this).hide();
	});
	jobsOpen = false;
}
var printJob = function(job){
	var element = "<li><a rel=\"job\" id="+job.id+" href=\"#"+job.cat+"/"+job.path+"/\">"+job.name+"</a></li>";
	$(element).appendTo("#jobList");
	assignMouseEvents(job.id);
}
var assignMouseEvents = function(id){
	var element = $("#"+id);
	var loadThumb, loading;
	var thumbPath;
	var jobPath;
	var num, _ch;
	var config = {
		sensitivity: 9,
		interval: 300,
		over: function(){
			if(jobLoaded !== true){
				var _id = this.id;
				$("#thumbHolder").css({
					top: (wh - $("#thumbHolder").height()) * 0.4,
					left: (ww - $("#thumbHolder").width()) * 0.5
				});
				$("#thumbHolder").fadeIn(120);
				num = (_id - 1);
				thumbPath = thumbPaths[num];
				loading = true;
				loadThumb = $.get("lib/LoadThumb.php",{thumb:thumbPath},function(data){
					var _data = $.parseJSON(data);
					loading = false;
					var thumb = new Image();
					thumb.src = _data.img.replace(/[\\"]/g,"").substr(1);
					$(thumb).attr("id","thumb"+_id);
					$(thumb).load(function(){
						_ch = thumb.height;
						$("#thumbHolder").append(thumb);
						$("#thumbHolder").css({
							height: _ch,
							top: (wh - _ch) * 0.4,
							left: (ww - $("#thumbHolder").width()) * 0.5
						});
					});
					$("#thumb"+_id).fadeIn(120);
				});
			}
		},
		timeout: 200,
		out: function(){
			if(loading !== undefined && loading){
				loadThumb.abort();
			}
			var _id = this.id;
			$("#thumbHolder").fadeOut(80,function(){
				$("#thumb"+_id).remove();
				$("#thumbHolder").hide();
			});
		}
	}
	$(element).hoverIntent(config);
	$(element).click(function(){
		jobPath = $(this).attr("href").substr(1);
		if($("img").length > 0){
		    flushData();
		}
		loadImages(jobPath);
	});
}
var clearThumb = function(){
	$("#thumbHolder").fadeOut(80,function(){
		$("#thumbHolder").children().remove();
		$("#thumbHolder").hide();
	});
}
var loadImages = function(job){
	jobLoaded = true;
	if($("#info").length > 0){
		$("#info").remove();
	}
	removeJobList();
	clearThumb();
	if($("img").length >= 0){
		$("img").fadeOut(120,function(){
			$(this).remove();
		});
	}
	$("#imgCounter").show(120);
	$("a[rel=nav]").show(120);
	$("#imgCounter > p").html("Loading...");
	$.ajax({
		type: "GET",
		data: "job="+job,
		dataType: "json",
		url: "lib/LoadImages.php",
		success: function(rsp){	
			for(var i = rsp.length - 1; i >= 0; i--){
				var img = new Image();
				img.src = rsp[i].substr(1);
				$(img).attr("id",i);
				imgList[i] = img;
			};
			addImage();
		},
		error: function(rsp){
			// Include error-handling for ajax-response
		}
	});
}
var loadStartImg = function(){
	$.ajax({
		type: "GET",
		dataType: "json",
		url: "lib/LoadStartImg.php",
		success: function(rsp){
			var img = new Image();
			img.src = rsp.substr(1);
			$(img).attr("id",i);
			$("#wrapper").prepend(img);
			$(img).load(function(){
				dynImgResize();
				$("#"+i).animate({opacity:1},1800);
			});
		},
		error: function(rsp){
			// Include error-handling for ajax-response
		}
	});
}
var addImage = function(){
	if($("img").length > 0){
		$("img").remove();
	}
	$("#wrapper").prepend(imgList[i]);
	if(i === 0 && first){
		$("#"+i).load(function(){
			first = false;
			updateImgCounter();
			dynImgResize();
			$(this).animate({
				opacity: 1
			},600);
		});
	} else {
		updateImgCounter();
		dynImgResize();
		$("#"+i).animate({
		    opacity: 1
		},600);
	}
}
var updateImgCounter = function(){
	$("#imgCounter > p").html(i+1+"/"+imgList.length);
}
var nextImage = function(){
	$("img").animate({
		opacity: 0
	},80,function(){
		$(this).remove();
		i++;
		if(i > imgList.length-1){
			i = 0;
		}
		addImage();
	});
}
var prevImage = function(){
	$("img").animate({
		opacity: 0
	},80,function(){
		$(this).remove();
		i--;
		if(i < 0){
			i = imgList.length-1;
		}
		addImage();
	});
}
var flushData = function(){
	$("img").animate({
		opacity: 0
	},80,function(){
		$(this).remove();
	});
	first = true;
	imgList=[];
	i=0;
}
var dynImgResize = function(){
	var img		= $("#"+i);
	var winRatio= ww / wh;
	var imgRatio= img.width() / img.height();
	var scaleX	= img.width() / img.height();
	var scaleY	= img.height() / img.width();
	if(imgRatio > winRatio){
	    w = ww;
	    h = (ww / img.width()) * img.height();
	} else {
	    w = (wh / img.height()) * img.width();
	    h = wh;
	}
	t = 0-((h - wh)*0.5);
	l = 0-((w - ww)*0.5);
	if(scaleY > scaleX){
	    img.css({
	    	height: h,
	    	width: "auto",
	    	top: t,
	    	left: l
	    });
	} else {
	    img.css({
	    	height: h,
	    	width: w,
	    	top: t,
	    	left: l
	    });
	}
}
var windowResize = function(){
	ww = $(window).width();
	wh = $(window).height();
	$("body").css("height",wh);
	if($("img").length > 0)
		dynImgResize();
}
var infoView = function(type){
	infoOpen = true;
	if($("#info").length > 0){
		$("#info").remove();
	}
	if(jobsOpen){
		$("#jobList").children().remove();
		$("a[rel=nav]").css("z-index",0);
		jobsOpen = false;
	}
	if($("#mask").length < 1){
		$("#wrapper").append(mask);
		$("#mask").height(wh);
		$("#mask").animate({
			opacity: 1
		},120,function(){
			switch(type){
				case "gtk":
					$("#mask").append(gtk);
					break;
				case "contact":
					$("#mask").append(contact);
					break;
				case "exhibition":
					$("#mask").append(exhibition);
				break;
			}
			$("#info").css({
				top: (wh - $("#info").height()) * 0.5,
				left: (ww - $("#info").width()) * 0.5
			});
			$("a[rel=info]").click(function(e){
				e.preventDefault();
				closeInfoView();
			});
		});
	} else {
		switch(type){
			case "gtk":
		    	$("#mask").append(gtk);
		    	break;
		    case "contact":
		    	$("#mask").append(contact);
		    	break;
		    case "exhibition":
		    	$("#mask").append(exhibition);
		    break;
		}
		$("#info").css({
		    top: (wh - $("#info").height()) * 0.5,
		    left: (ww - $("#info").width()) * 0.5
		});
		$("a[rel=info]").click(function(e){
		    e.preventDefault();
		    closeInfoView();
		});
	}
}
var closeInfoView = function(){
	infoOpen = false;
	window.location.hash = "";
	$("#mask").animate({
		opacity: 0
	},120,function(){
		$(this).remove();
	});
}
$(document).ready(function(){
	$("a[rel=nav]").hide();
	ww = $(window).width();
	wh = $(window).height();
	//console.log(ww,wh);
	$("body").css("height",wh);
	$(window).bind("resize",function(e){
		windowResize();
	});
	$(window).keyup(function(e){
		switch(e.keyCode){
			case 39:
				nextImage();
				break;
			case 37:
				prevImage();
				break;
			case 27:
				if(infoOpen){
					closeInfoView();
				}
				if($("#jobList").children().length > 0){
					clearThumb();
					removeJobList();
				}
				break;
			case 77:
				window.location.hash = "male";
				if($("#jobList").children().length > 0){
					removeJobList();
				}
				loadJobList("male");
				break;
			case 70:
				window.location.hash = "female";
				if($("#jobList").children().length > 0){
					removeJobList();
				}
				loadJobList("female");
				break;
		}
	});
	if(window.location.hash !== undefined && window.location.hash !== "" && window.location.hash !== "#gtk" && window.location.hash !== "#contact" && window.location.hash !== "#exhibition"){
		cpath = window.location.hash.substr(1);
		if(cpath === "male" || cpath === "female"){
			loadJobList(cpath);
		} else {
			loadImages(cpath);
		}
	} else if(window.location.hash !== ""){
		infoView(window.location.hash.substr(1));
	} else {
		loadStartImg();
	}
	$("a[rel=menu]").click(function(e){
		npath = $(this).attr("href").substr(1);
		if(npath === "gtk" || npath === "contact" || npath === "exhibition"){
			infoView(npath);
		} else {
			if(npath !== cpath){				
				loadJobList(npath);
				cpath = npath;
			} else {
				if($("#jobList").children().length <= 0){
					loadJobList(cpath);
				}
			}
		}
	});
	$("a[rel=menu]").mouseover(function(e){
		var id = $(this).attr("href").substr(1);
		if(id === "female" || id === "male"){
			npath = id;
			if(npath !== cpath){
				loadJobList(npath);
				cpath = npath;
			} else if($("#jobList").children().length <= 0){
				loadJobList(cpath);
			}
			window.location.hash = "#"+npath;
		}
	});
	$("a[rel=nav]").click(function(e){
		e.preventDefault();
		if($(this).attr("id") === "next"){			
			nextImage();
		} else {
			prevImage();
		}
	});
	$("a[rel=warn]").click(function(e){
		e.preventDefault();
		$("#warn").remove();
	});
});
