// preload images
(function ($) {
	$.preLoadImages = function(imageList,callback) {
		var pic = [], i, total, loaded = 0;
		if (typeof imageList != 'undefined') {
			if ($.isArray(imageList)) {
				total = imageList.length; // used later
					for (i=0; i < total; i++) {
						pic[i] = new Image();
						pic[i].onload = function() {
							loaded++; // should never hit a race condition due to JS's non-threaded nature
							if (loaded == total) {
								if ($.isFunction(callback)) {
									callback();
								}
							}
						};
						pic[i].src = imageList[i];
					}
			}
			else {
				pic[0] = new Image();
				pic[0].onload = function() {
					if ($.isFunction(callback)) {
						callback();
					}
				}
				pic[0].src = imageList;
			}
		}
		pic = undefined;
	};
})(jQuery);

function urldecode(str) {
	var a = unescape(str);
	b = a.replace(/\+/g, ' ');
	return b;
}

function createCookie(name, value) {
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + 365);
	document.cookie = name + "=" + escape(value) + ";expires=" + exdate.toGMTString() + ";path=/";
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function flashPop(url,w,h,n) {
	var windowprops = 'width=' + w + ',height=' + h + ',toolbar=0,location=0,directories=0,status=0,scrollbars=yes,resizable=yes,copyhistory=0';
	popup = window.open(url,'n',windowprops);
	popup.focus();
}

function slideShow(x, j) {
	if (stop == false) {
		stop = true;
	} else {
		stop = false;
		slidecontroller = '<img class="icon" src="/assets/stop.png" width="20" height="20" alt="Stop" />'
		$("#slideShowControl").html(slidecontroller);
	}
	doSlideShow(x, j);
}

function doSlideShow(x, j) {
	if (stop == true) {
		clearInterval(interval);
		slidecontroller = '<img class="icon" src="/assets/play.png" width="20" height="20" alt="Play" />';
		$("#slideShowControl").html(slidecontroller);
		return;
	}
	pid = j;
	pidslen = x;
	interval = setInterval("advanceSlideShow();", 5000);
}

function advanceSlideShow() {
	$("#showPhoto").animate({opacity: 0.0}, 800, function(){
		showPic(pid, true);
		(pid >= pidslen)? pid = 0: pid++;
	})
}
// end slideshow stuff

function showPic(i, a)
{

	$("#two").hide();
	if (len > 1) {
		var x = (len - 1);
		if (i == 0) {
			var prev = x;
			var next = 1;
		} else if (i == x) {
			var j = i - 1;
			var prev = j;
			var next = 0;
		} else {
			var prev = i - 1;
			var next = i + 1;
		}
		var nav = '<a onclick="showPic(' + prev + ');return false;" href="/photography/' + prev + '">&laquo;</a> <a onclick="showPic(' + next + ');return false;" href="/photography/' + next + '">&raquo;</a> <a id="slideShowControl" onclick="slideShow(' + x + ', ' + next + ');return false;" href="#">' + slidecontroller + '</a>';
		$("#prevnext").html(nav);
		var navCtrl = 0;
		$("html").keyup(function(e){
			if (navCtrl == 0) {
				if (e.which == 37) {
					e.preventDefault();
					showPic(prev);
					navCtrl = 1;
				}
				if (e.which == 39) {
					e.preventDefault();
					showPic(next);
					navCtrl = 1;
				}
				if (e.which == 38) {
					e.preventDefault();
					showPic(prev);
					navCtrl = 1;
				}
				if (e.which == 40) {
					e.preventDefault();
					showPic(next);
					navCtrl = 1;
				}
			}
		});
	}

	var t = '<p id="picInfo">';
	if ((pids[i][3] != pids[i][0]) && (pids[i][0].length > 0)) {t += urldecode(pids[i][0]); t += ' ';}
	t +=  ' <span class="roll"><a class="zig" href="/photography/search/roll/' + pids[i][3] + '">' + urldecode(pids[i][3]);
	if (pids[i][3].indexOf(pids[i][1]) == -1) t += ' ' + pids[i][1];
	t += '<\/a><\/span>';
	var z = readCookie('cookieusername');
	if (z == 'charlie') {
		t += ' <a class="zig" href="/mygallery/admin/edit/' + pids[i][9] + '" target="edit">edit<\/a>';
	}
	t += '<\/p>';
	t += '<div id="elPic"><img src="/mygallery/photos/' + pids[i][1] + '/photos/' + pids[i][2] + '" alt="' + urldecode(pids[i][0]) + '" \/></div>';
	//if (pids[i][6] == 1) {
		t +=  '<div id="description" class="turned">' + urldecode(pids[i][4]) + '<\/div>';
	//}
	t += '<p id="picTags"><\/p>';
	h = pids[i][8];
	$("#showPhoto").html(t);
	$("#elPic").css({"cursor": "pointer"});
	$("body").addClass("lightbox");
	$("#bigcredit").html('<a id="close" class="zig" onclick="return false;" href="#">X close<\/a>');
	$("#picTags").load("/assets/loadtags.php", {"id": pids[i][9]});
	linksheight();
	SizePhoto(pids[i][7], pids[i][8]);$(window).bind('resize',function(){SizePhoto(pids[i][7], pids[i][8])});
	$("#showPhoto").css({"display": "block"});
	if (a == true) $("#showPhoto").animate({opacity: 1.0}, 2000);

	// back to thumbs
	$("#elPic, #close").click(function(){
		/* stop and reset slideshow */
		clearInterval(interval);stop = true;
		$("#prevnext").html('');
		$("#two").show();
		$("#showPhoto").css("display", "none").html('');
		$("body").removeClass("lightbox");
		$("#bigcredit").html(navHtml);
		slidecontroller = '<img class="icon" src="/assets/play.png" width="20" height="20" alt="Play" />';
		$("#slideShowControl").html(slidecontroller);
		h = 0;
		linksheight();
	});

}

function loadThumbs() {
	$("#loader").fadeOut('slow', function(){
		$("#thumbarea").fadeIn('slow');
	});
}

function linksheight() {
	var wh = $(window).height();
	var rh = (wh - links_offset) + 'px';
	$links.css("top", rh).show();
}

// get dimensions of the first  image,
// in order to make it full size and centered
function getImageDim(img){
	var w_w	= $(window).width(),
		w_h	= $(window).height(),
		r_w	= w_h / w_w,
		i_w	= img.width(),
		i_h	= img.height(),
		r_i	= i_h / i_w,
		new_w, new_h;

	if (r_w > r_i){
		new_h	= w_h;
		new_w	= w_h / r_i;
	} else {
		new_h	= w_w * r_i;
		new_w	= w_w;
	}

	return {
		width	: new_w + 'px',
		height	: new_h + 'px',
		left	: (w_w - new_w) / 2 + 'px',
		top		: parseInt((w_h - new_h) / 2) + 'px'
	};
}

// show next / prev image
function bg_scroll(dir){
	// if dir is "down" (top -> bottom) increment current,
	// else if "up" decrement it
	current	= (dir == 'down')? current + 1: current - 1;
	if (current == total) current = 0;
	else if (current < 0) current = total - 1;
	// get the next image
	var $bg_img_next = $bg_images.eq(current),
	dim	= getImageDim($bg_img_next),
	// the top should be one that makes the image out of the viewport
	// the image should be positioned up or down depending on the direction
	top	= (dir == 'down')? $(window).height() + 'px': -parseFloat(dim.height) + 'px';

	// set the returned values and show the next image
	$bg_img_next.css({
		"width"		: dim.width,
		"height"	: dim.height,
		"left"		: dim.left,
		"top"		: top
	}).show();

	// now slide it to the viewport
	$bg_img_next.animate({
		"top" 	: dim.top
	}, 700);

	// we want the old image to slide in the same direction, out of the viewport
	var slideTo	= (dir == 'down')? -$bg_img.height() + 'px': $(window).height() + 'px';
	$bg_img.animate({
		"top" 	: slideTo
	}, 700, function(){
		// hide it
		$(this).hide();
		// the $bg_img is now the shown image
		$bg_img	= $bg_img_next;
	});
}

// shows the first image and initializes events
function bg_init(img){
	// get dimensions for the image, based on the windows size
	var dim	= getImageDim(img);
	// set the returned values and show the image
	img.css({width : dim.width, height : dim.height, left : dim.left, top : dim.top});

	// adjust links height
	$links.css("top", links_height + "px").fadeIn();

	// resizing the window resizes the img
	$(window).bind('resize',function(){
		var dim	= getImageDim(img);
		img.css({
			"width"		: dim.width,
			"height"	: dim.height,
			"left"		: dim.left,
			"top"		: dim.top
		});
		links_height = $(window).height() - links_offset;
		$links.css("top", links_height + "px").fadeIn();
	});
}

function SizePhoto(i_w, i_h) {

	var images = $("#showPhoto").find('img');
	var theImg = images.eq(0);

	var w_w	= $(window).width(),
		w_h	= ($(window).height() - 70);

	var height			= w_h + 'px';
	var m 				= w_h / i_h;
	var displayWidth 	= i_w * m;
	var y 				= ((w_w - displayWidth) / 2);
	var left 			= parseInt(y) + 'px';
	theImg.css({"position": "absolute", "top": "31px", "left": left, "height": height});

	var bg = (w_h + 45) + 'px';
	var bh = (w_h + 30) + 'px';
	var bi = (w_h - 230) + 'px';
	var bj = (w_w - 260) + 'px';
	var bk = $("#bigcredit").width();
	var bl = (bk + 20) + 'px';
	var bm = $links.width();
	var bn = (bm + 20) + 'px';

	$("#picTags").css({"top": bh});
	$("#description").css({"top": bi, "left": bj});
	$("#picInfo").css({"left": bl});

}
