// onScreen jQuery plugin v0.2.1
// (c) 2011 Ben Pickles
//
// http://benpickles.github.com/onScreen
//
// Released under MIT license.
;(function($) {
  $.expr[":"].onScreen = function(elem) {
    var $window = $(window)
    var viewport_top = $window.scrollTop()
    var viewport_height = $window.height()
    var viewport_bottom = viewport_top + viewport_height
    var $elem = $(elem)
    var top = $elem.offset().top
    var height = $elem.height()
    var bottom = top + height

    return (top >= viewport_top && top < viewport_bottom) ||
           (bottom > viewport_top && bottom <= viewport_bottom) ||
           (height > viewport_height && top <= viewport_top && bottom >= viewport_bottom)
  }
})(jQuery);

var debug = false;
var totalImages = new Array();
var intervalImages = new Array();
var imStateArray = new Array();
var imPaths = new Array();
var imCache = new Array();
var imAutoDisplay = 5000;
var numCacheSet = 0;
var fetchSet = new Array();
var requestedSet = new Array();
var totalGalleries = 0;
var ua = $.browser;
//
$(window).ready(function() {
	prepDebug();
	if(ids!=null) {
		getImagePath(ids);
		numberOfGalleries();
	}
});
(function($){     
	$.fn.extend({         
		fetchGallery: function() {             
			// You must return jQuery object             
			return $();         
		},         
		fetchGallery: function() { 
			//alert("hola");
        	$(this).each(function(){   
				var id = getId("imageset_",$(this));
				fetchSet.push(id);	    
	        });                  
			//alert(fetchSet);
			preCacheSet(fetchSet[0]);         
		}     
	}); 
})(jQuery);

function numberOfGalleries() {
	totalGalleries = $(".imageset").length;	
}
function prepDebug() {
	if(debug) {
		$("body").append("<div id='debug'>test&nbsp;</div>");
	}
}
function pd(printToDebug) {
	$("#debug").append("<br>"+printToDebug);
}
function getImagePath(ids) {
	 $.ajax({
	   type: "POST",
	   url: "/templates/ajax/media_pictures.jsp",
	   data: "id="+ids+"&width="+imWidth,
	   success: function(msg){
		    //alert(msg);
			callBackPaths(msg);
			ajaxLoadComplete();
	   }
	 });
}
function callBackPaths(msg) {
	var imPathsIn = msg.split("\n");
	for(var i=0;i<imPathsIn.length;i++) {
		var subImPathsIn = imPathsIn[i].split("|");
		for(var j=0;j<subImPathsIn.length;j++) {
			if(subImPathsIn[j]=="") {
				subImPathsIn.splice(j,j);
			}
			totalImages[i] = subImPathsIn.length;
		}
		intervalImages[i] = null;
		imPaths[i] = subImPathsIn;
	}
}
function ajaxLoadComplete() {
	//alert("dude: "+imPaths[0].length);
	for(i=0;i<totalImages.length;i++) {
		imStateArray[i] = 0;
	}	
	//
	if(((ua.msie && ua.version==7.0) || (ua.msie && ua.version==8.0))) {
    	$(".imageset").fetchGallery();
	}
	else {
	    $(".imageset:onScreen").fetchGallery();
		$(window).scroll( function() {    
			$(".imageset:onScreen").fetchGallery();
		});
	}
	//alert(totalImages.length);

}
function setLoaded(id) {
	//alert(id);
	createButtons(id);
	prepareButtons(id);
	createNumberOf(id);		
	prepareGalleries(id);
	intervalImages[id] = setInterval("showNextImage("+id+")", imAutoDisplay);

}
function prepareGalleries(id) {
	$("#next_"+id).click(function() {
		showNextImage(id);
		if(intervalImages[id]!=undefined) {
			clearInterval(intervalImages[id]); 
		}
	});
	$("#prev_"+id).click(function() {
		showPrevImage(id);
		if(intervalImages[id]!=undefined) {
			clearInterval(intervalImages[id]); 
		}
	});	
	$("#imageset_"+id).mouseover(function() {
		$("#imageset_"+id+" .button").show();	
		$("#numberOf_"+id).show();			
	});	
	$("#imageset_"+id).mouseout(function() {
		$("#imageset_"+id+" .button").hide();		
		$("#numberOf_"+id).hide();			 
	});	
}
function createNumberOf(id) {
	$("#imageset_"+id).prepend("<div id=\"numberOf_"+id+"\" class=\"numberOf\">1 of "+totalImages[id]+"</div>");
	var numDivWidth = $("#numberOf_"+id).width();
	var pos = (imWidth/2)-(numDivWidth/2);
	$("#numberOf_"+id).css({left:pos});	
}
function createButtons(id) {
	$("#imageset_"+id).prepend("<div id=\"prev_"+id+"\" class=\"prevbutton button\"></div>");
	$("#imageset_"+id).prepend("<div id=\"next_"+id+"\" class=\"nextbutton button\"></div>");
}
function getId(lay,$but) {
	var l = lay.length;
	var idIn = $but.attr('id');
	var id = idIn.substring(l,idIn.length);	
	return id;
}
function resetInterval() {
	slideInterval = setInterval("showNextImage()", imAutoDisplay);
}
function preCacheSet(id) {
	//alert(imPaths[id].length);
	//alert("hel "+id + " " + $.inArray(id,requestedSet));
	fetchSet.shift();
	if($.inArray(id,requestedSet)==-1) {
		// WEIRD fix for an extra undefined item in the very last gallery of images.
		if(id==(totalGalleries-1)) {
			imPaths[id].pop();
			pd("last one: "+imPaths[id]);		
		}
		requestedSet.push(id);	
		imCache[id] = new Array();
		pd(totalGalleries);
		if(numCacheSet==(totalGalleries-1)) {
			//alert("loaded all the images");	
		}
                if(imPaths[id]!=null) {
                    for(i=0;i<imPaths[id].length;i++) {
                            cacheImage(id,i);
                    }
                }
	} 
	else if(fetchSet.length>0) {
		preCacheSet(fetchSet[0]);
	}
}
function cacheImage(id,i) {
	var path = imPaths[id][i];
	if(path!=null) {
	var img = new Image();
	$(img).load(function () {
		imCache[id][i] = this;
		if(i==(imPaths[id].length-1)) {
			setLoaded(id);
			numCacheSet++;
			preCacheSet(fetchSet[0])
			//alert("set loaded "+id);
		}
		//alert(i + " " + path);
	}).error(function () {
			numCacheSet++;
		//$(curr).remove();
	}).attr('src', path);
	}
}
function showPrevImage(id) {
	var pre = getPrevious(id);
	var nImg = imCache[id][pre];
	if(nImg!=null) {
		$("#debug").html(pre);
		$("#image_"+id).attr('src', nImg.src);
		$("#numberOf_"+id).html((pre+1)+" of "+totalImages[id]);	
	}
}
function showNextImage(id) {
	var next = getNext(id);	
	var nImg = imCache[id][next];
	if(nImg!=null) {
		$("#debug").html(next);
		$("#image_"+id).attr('src', nImg.src);
		$("#numberOf_"+id).html((next+1)+" of "+totalImages[id]);	
	}
}
function prepareButtons(id) {
	var $img = $("#image_"+id);
	var imgWidth = $img.attr('width');
	imgWidth = imWidth;
	var imgHeight = $img.attr('height');
	//alert(imgHeight);
	//alert(imgWidth);
	
	//$("#next_"+id).height(imgHeight/1);
	//$("#prev_"+id).height(imgHeight/1);
	//$("#next_"+id).width(imgWidth/2);
	//$("#prev_"+id).width(imgWidth/2);
	//$("#next_"+id).width(100);
	//$("#prev_"+id).width(100);

	var buttonWidth = $("#next_"+id).width();
	var pos = imgWidth-buttonWidth;
	//
	//alert(pos);
	$("#next_"+id).css({left:pos});
}
function getNext(iId) {
	var imState = imStateArray[iId];
	imState++;
	var total = totalImages[iId];
	if(total==imState) {
		imState=0;
	}
	imStateArray[iId] = imState;
	return imState;
}
function getPrevious(iId) {
	var imState = imStateArray[iId];
	imState--;
	var total = totalImages[iId];
	if(imState==-1) {
		imState=total-1;
	}
	imStateArray[iId] = imState;
	return imState;
}



// VERTICALLY ALIGN FUNCTION
(function ($) {
$.fn.vAlign = function(ah) {
	return this.each(function(i){
	//var ah = $(this).height();
	var ph = $(this).parent().height();
	var mh = Math.ceil((ph-ah) / 2);
	$(this).css('margin-top', mh);
	});
};
})(jQuery);

