var imagecount = 884;
var pictures = null;
var filledOffset = 0;
var filledX = 0;
var maxX = 0;
var newleft = 0;
var newpics = null;
var sw = 0;
var aw = 0;
var gw = 0;
var fw = 0;
var bgindent = 0;
var detailColumn = 0;
var detailRow = 0;
var detailImage = 0;
var slideShow = null;

$(document).ready(function(){
	$('#next').click(function(){
		window.clearInterval(slideShow);
		$('#pause').fadeOut(250, function(){$('#play').fadeIn(250);});
		nextPic();
	});
	$('#prev').click(function(){
		window.clearInterval(slideShow);
		$('#pause').fadeOut(250, function(){$('#play').fadeIn(250);});
		prevPic();
	});
	$('#play').click(function(){
		nextPic();
		slideShow = window.setInterval("nextPic()",5000);
		$('#play').fadeOut(250, function(){$('#pause').fadeIn(250);});
	});
	$('#pause').click(function(){
		window.clearInterval(slideShow);
		$('#pause').fadeOut(250, function(){$('#play').fadeIn(250);});
	});
	$('#close').click(function(){
		window.clearInterval(slideShow);
		$('#pause').fadeOut(250, function(){$('#play').fadeIn(250);});
		$('#bigimg').fadeOut(250);
		$("#bigequalizer").fadeIn(250);
		$("#miniequalizer").fadeIn(250);
		$("#left").fadeTo(250,1);
		$("#joinin").fadeIn(250);
		$("#bigimg .voted-rating").fadeOut(500);
		$("#thxforrating").fadeOut(500);
		$(".star-rating a").css({'display':'block'});
	});
	$('#flyout').mouseover(function(){$(this).hide(0);});
		
	jQuery.getJSON('/php/getGallery.php', function(jsondata){
		if(jsondata.images.length > 5){
			pictures = jsondata.images;
						
			if(pictures[(pictures.length-1)].length <= 0){
				pictures = pictures.slice(0,-1);	
			}
			//pictures = pictures.slice(0,100);
			var months = jsondata.cols;
			
			var divs = $('#months div');
			$.each(months, function(j, value){
				if(divs[j]){
					var newwidth = ((parseInt(value)*5)-1);
					if(newwidth > 0){
						$(divs[j]).css({width:newwidth,'display':'block'});
					}
				}
			});
			
			$('#picmatrix').hide();
			sw = (pictures.length)*5;
			aw = $('#miniequalizer_active').width();
			gw = Math.round($('#miniequalizer_grid').width()/5)*5;
			fw = sw > gw ? gw : sw;	

			if(sw<gw)
			{
				$('#miniequalizer_unfilled').fadeIn(500);
				$('#months').css({'width':gw}).show(500);
			}else{
				bgindent = (sw-gw);
				$('#months').css({width:(sw+10),left:'-'+bgindent+'px'}).show(500);
				$('#miniequalizer_filled').css({'background-position':'-'+(sw-gw)+'px 0px'});
				$('#months_left').fadeIn(500);
				$('#months_left')
					.mousehold(50, function(){
						$('#picmatrix').hide();
						$('#picmatrix table td').html('');
						movePeaks(-1);
					})
					.mouseup(function(){$('#loader').fadeIn(250); newPics();});
				$('#months_right')
					.mousehold(50, function(){
						$('#picmatrix').hide();
						$('#picmatrix table td').html('');
						movePeaks(1);
					})
					.mouseup(function(){$('#loader').fadeIn(250); newPics();});
			}
			
			$('#miniequalizer_filled')
				.css({width:fw})
				.fadeIn(500, function(){
					if(fw > aw){
						newleft = sw>gw ? Math.round((gw-aw)/5)*5 : Math.round((fw-aw)/5)*5;
						bgi = sw>gw ? Math.round((sw-aw)/5)*5 : newleft;
						$('#miniequalizer_active').css({'background-position':'-'+bgi+'px 2px', left:newleft+16});
						$("#bigequalizer").css({'background-position':'-'+(bgi*6)+'px 0px'});
						$('#miniequalizer_active').fadeIn(500);
						$('#bigequalizer').fadeIn(500);

						filledX = fw-aw;
						maxX = gw-aw;
						filledOffset = $('#miniequalizer_filled').offset();

						$('#miniequalizer_active')
							.bind('dragstart',function( event ){
								$('#picmatrix').hide();
								$('#picmatrix table td').html('');
							})
							.bind('drag',function(event){
								filledOffset = $('#miniequalizer_filled').offset();
								var newlefttest = Math.round( (event.offsetX-filledOffset.left)/5 ) * 5;
								if(newlefttest<=maxX && newlefttest>=0 && newlefttest<=filledX){
									newleft = newlefttest;
									$(this).css({left:newleft+16, 'background-position':'-'+bgindent-newleft+'px 2px'});
									$("#bigequalizer").css({'background-position':'-'+((bgindent+newleft)*6)+'px 0px'});
								}
							})
							.bind('dragend',function(){$('#loader').fadeIn(250); newPics();});
					} else {
						newleft = 0;
						bgi = 0;
						$("#bigequalizer").css({'background-position':'0px 0px'});
						$('#bigequalizer').fadeIn(500);

						filledX = fw-aw;
						maxX = gw-aw;
						filledOffset = $('#miniequalizer_filled').offset();
					}
					if(directlink != 0){
						var picture = 0;
						$(pictures).each(function(i, col){
							$(col).each(function(j, pic){
								if(pic.id == directlink){
									detailColumn = i;
									detailRow = j;
									picture = pic;
								}
							});
						});
						if(picture != 0){
							$("#imageid").attr("value", picture.id);
							$("#bigimg_title").text(picture.title);
							$("#bigimg_name").text(picture.user);
							$("#bigimg_date").text(picture.day+'/'+picture.month+'/'+picture.year);
							$("#bigimg .current-rating").css({'width':Math.round(picture.rating*25)});
							$("#bigequalizer").fadeOut(250);
							$("#miniequalizer").fadeOut(250);
							$("#joinin").fadeOut(250);
							$("#left").fadeTo(250, 0.5);
							$('#bigimg_img').attr("src", "/image/entries/detail/"+picture.id+".jpg");
							$("#bigimg").fadeIn(250);	
						}
					}
					newPics();
					showwinners();
				});
		}
	});
});

function movePeaks(step){
	var pxstep = step*5;
	bgindenttest = bgindent+pxstep;
	if(bgindenttest >= 0 && bgindenttest <= sw-gw){
		if(bgindenttest < sw-gw){
			$('#months_right').fadeIn(500);
		}
		if(bgindenttest > 0){
			$('#months_left').fadeIn(500);
		}
		bgindent = bgindenttest;
		bgi = bgindent+newleft;
		$('#months').css({left:'-'+bgindent+'px'});
		$('#miniequalizer_filled').css({'background-position':'-'+bgindent+'px 0px'});
		$("#bigequalizer").css({'background-position':'-'+(bgi*6)+'px 0px'});
		$('#miniequalizer_active').css({'background-position':'-'+bgi+'px 2px'});
	}
}

function newPics(){
	if(bgindent <= 0){
		$('#months_left').fadeOut(500);
	}
	if(bgindent >= sw-gw) {	
		$('#months_right').fadeOut(500);
	}
	var peak = ((bgindent+newleft)/5);
	//peak = (sw<gw && peak!=0) ? peak-1 : peak;
	//console.log(peak);
	var tds = $("#picmatrix table td");
	if(peak >= 0 && peak <= (pictures.length-27)){
		var r = 0;
		newpics = new Array();
		for(i=peak; i<(peak+27); i++){
			newpics[r] = new Array();
			var td = tds[r];
			$.each(pictures[i], function(j, pic){
				newpics[r][j] = new Image(23,13);
				newpics[r][j].src = '/image/entries/thumb/'+pic.id+'.jpg';
				td.innerHTML += '<img src="'+newpics[r][j].src+'" id="'+i+'_'+j+'" alt="" />';
			});
			r++;
		}
		window.setTimeout("equalize()",1000);
	} else {
		$('#months_left').fadeOut(500);
		$('#months_right').fadeOut(500);
		var r = 0;
		newpics = new Array();
		for(i=0; i<pictures.length; i++){
			newpics[r] = new Array();
			var td = tds[r];
			$.each(pictures[i], function(j, pic){
				newpics[r][j] = new Image(23,13);
				newpics[r][j].src = '/image/entries/thumb/'+pic.id+'.jpg';
				td.innerHTML += '<img src="'+newpics[r][j].src+'" id="'+i+'_'+j+'" alt="" />';
			});
			r++;
		}
		window.setTimeout("equalize()",1000);
	}
	$('#bigimg_img').load(function(){
		$("#bigimg_title").show(500);
		$("#bigimg_name").show(500);
		$("#bigimg_date").show(500);
		$('#bigimg_img').fadeIn(500);
		$("#bigimg .current-rating").fadeIn(500);
		picture = pictures[detailColumn][detailRow]
		if(picture.yourrating && picture.yourrating != 0){
			$("#bigimg .voted-rating").fadeIn(500);
			$("#thxforrating").fadeIn(500);
			$(".star-rating a").css({'display':'none'});
		}
	});
}

function showwinners(){
	$('#joinin').fadeOut(250);
	$('#miniequalizer').fadeTo(250, 0.3);
	$('#bigequalizer').fadeTo(250, 0.3,
		function(){
			$('#winnersoverlay').fadeIn(250);
		}
	);
}

function hidewinners(){
	$('#winnersoverlay').fadeOut(250,
		function(){
			$('#joinin').fadeIn(250);
			$('#miniequalizer').fadeTo(250, 1);
			$('#bigequalizer').fadeTo(250, 1);
		}
	);
}

function equalize(){
	var readycount = 0;
	var picturecount = 0;
	
	$.each(newpics, function(i, col){
		$.each(col, function(j, pic){
			if(pic.complete){
				readycount++;
			}
			picturecount++;
		})
	});
	if(readycount != 0 && readycount>=(picturecount-10)){
		newpics = null;
		$('#loader').fadeOut(250, function(){
			$('#picmatrix').show(0);
			$('#picmatrix img').hide(0);
			
			var tds = $('#picmatrix table td');
			tds.each(function(i, col){
				var column = $('img', col).reverse();
				column.each(function(j, pic){
					$(pic).mouseover(function(){
						keys = this.id.split('_');
						picture = pictures[keys[0]][keys[1]];
						$('#flyout').hide(0);
						pio = $(this).offset();
						$('#flyout').html("");
						var tmptitle = picture.title.length > 14 ? picture.title.substr(0,14)+'&hellip;' : picture.title;
						$('#flyout').append('<span class="roimg"><img src="'+this.src.replace(/thumb/g, "ro")+'" height="115" alt="" /></span><span class="rodetails">'+tmptitle+'<br />'+picture.user+'</span><span class="rometa"><img src="/img/small'+picture.rating+'stars.png" alt="" /><br />'+picture.day+'/'+picture.month+'/'+picture.year+'</span><span class="clear"></span>');
						if(i < 13){
							$('#flyout').css({left:(pio.left+30)});
						} else {
							$('#flyout').css({left:(pio.left-213)});
						}
						if(j > 7)
						{
							$('#flyout').css({top:pio.top});
						}else{
							$('#flyout').css({bottom:($(document).height()-(pio.top+13)), top:null});
						}
						$('#flyout').show(0);
					});
					$(pic).mouseout(function(){
						$('#flyout').hide(0);
					});
					$(pic).click(function(){
						keys = this.id.split('_');
						picture = pictures[keys[0]][keys[1]];
						detailColumn = parseInt(keys[0]);
						detailRow = parseInt(keys[1]);
						var tmplongtitle = picture.title.length > 55 ? picture.title.substr(0,40)+'...' : picture.title;
						$("#imageid").attr("value", picture.id);
						$("#bigimg_title").text(tmplongtitle);
						$("#bigimg_name").text(picture.user);
						$("#bigimg_date").text(picture.day+'/'+picture.month+'/'+picture.year);
						$("#bigimg .current-rating").css({'width':Math.round(picture.rating*25)});
						$("#bigequalizer").fadeOut(250);
						$("#miniequalizer").fadeOut(250);
						$("#joinin").fadeOut(250);
						$("#left").fadeTo(250, 0.5);
						$('#bigimg_img').attr("src", this.src.replace(/thumb/g, "detail"));
						$("#bigimg").fadeIn(250);
						if(picture.yourrating && picture.yourrating != 0){
							$("#bigimg .voted-rating")
								.css({'width':Math.round(picture.yourrating*25)})
								.fadeIn(250);
							$("#thxforrating").fadeIn(500);
							$(".star-rating a").css({'display':'none'});
						}
					});
					//$(pic).wait((((1000*j)/column.length)+1)).slideDown(50);
					$(pic).wait((((1000*j)/column.length)+1)).fadeIn(125);
					//$(pic).wait((((1000*j)/column.length)+1)).show(125);
				})
			});
		});
		//show all together (for low performance PCs)
		//$('#loader').fadeOut(250, function(){$('#picmatrix').fadeIn(1000)});
	} else {
		window.setTimeout("equalize()",1000);
	}
}


function prevPic(){
	detailRow--;
	if(detailRow < 0){
		if(detailColumn == 0){
			detailColumn = pictures.length-1;
		}	
		detailRow = pictures[detailColumn].length-1;
	}	
	changeDetailPic();
}

function nextPic(){
	if(detailRow+1 >= pictures[detailColumn].length){
		detailRow = 0;
		detailColumn = detailColumn+1 >= pictures.length ? 0 : detailColumn+1;
	} else {	
		detailRow++;
	}	
	changeDetailPic();
}

function rate(r){
	var picture = pictures[detailColumn][detailRow];
	var c = 'panluaw';
	if(!picture.yourrating || picture.yourrating == 0){
		$.get("/php/rate.php", {i:picture.id, r:r, c:c}, function(result){
			if(result=="true"){
				$('.voted-rating')
					.css({width:r*25})
					.fadeIn(250);
				try{ 
					var pageTracker = _gat._getTracker("UA-930177-16"); 
					pageTracker._trackPageview('form.rating.'+lang); 
				} catch(err) {}
				picture.yourrating = r;
				$("#thxforrating").fadeIn(500);
				$(".star-rating a").css({'display':'none'});
			}
		});
	}
}

function changeDetailPic(){
	var picture = pictures[detailColumn][detailRow];
	$("#bigimg_title").hide(500);
	$("#bigimg_name").hide(500);
	$("#bigimg_date").hide(500);
	$("#bigimg .current-rating").fadeOut(500);
	$("#bigimg .voted-rating").fadeOut(500);
	$("#thxforrating").fadeOut(500);
	$(".star-rating a").css({'display':'block'});
	$('#bigimg_img').fadeOut(500, function(){		
		$("#bigimg_title").text(picture.title);
		$("#bigimg_name").text(picture.user);
		$("#bigimg_date").text(picture.day+'/'+picture.month+'/'+picture.year);
		$("#bigimg .current-rating").css({'width':Math.round(picture.rating*25)});
		if(picture.yourrating && picture.yourrating != 0){
			$("#bigimg .voted-rating").css({'width':Math.round(picture.yourrating*25)});
			$("#thxforrating").fadeIn(500);
			$(".star-rating a").css({'display':'none'});
		}
		$('#bigimg_img').attr("src", "/image/entries/detail/"+picture.id+".jpg");
	});
}

jQuery.fn.reverse = function()
{
	return this.pushStack(this.get().reverse(), arguments);
};

jQuery.fn.mousehold = function(timeout, f) {
	if (timeout && typeof timeout == 'function') {
		f = timeout;
		timeout = 100;
	}
	if (f && typeof f == 'function') {
		var timer = 0;
		var fireStep = 0;
		return this.each(function() {
			jQuery(this).mousedown(function() {
				fireStep = 1;
				var ctr = 0;
				var t = this;
				timer = setInterval(function() {
					ctr++;
					f.call(t, ctr);
					fireStep = 2;
				}, timeout);
			})

			clearMousehold = function() {
				clearInterval(timer);
				if (fireStep == 1) f.call(this, 1);
				fireStep = 0;
			}
			
			jQuery(this).mouseout(clearMousehold);
			jQuery(this).mouseup(clearMousehold);
		})
	}
}