

/*******************************************************************************************************/
// Some jQuery Extensions
(function($){  
    $.fn.extend({   
        imageScroller: function(options) {  
			var defaults = {
				height: 311,
				width: 129,
				speed: 675
				};
			var options = $.extend(defaults, options);			
			// Should be nested UL / LI
            return this.each(function() {  
            	
				var o = options;  
                var obj = $(this); 
                //console.log(obj);
                
                
				obj.css({
					"position":"relative",
					"height" : o.height,
					"width" : o.width
						});
				
				obj.find("li").css({"position" : "absolute","top" : "0", "left": "0"}).hide();
				var idx = 0;
				
				obj.find("li:eq("+idx+")").addClass("active").show(); // Show the first image.
				
				var i = findActiveIndex(obj.find("li"));
				
				var l = obj.children('li').size();
				//console.log("Size of array: ",l);
				//console.log("Current active: ",i);
				
				
				var c = $(document.createElement("div")).addClass("galleryControls");
				
				var d = $(document.createElement("span")).addClass("index"); // This will hold the X of Y values. 
				d.text((idx + 1) + "/" + l);
				//console.log("Index before any click: ",idx);

				var n = $(document.createElement("a")).addClass("next").attr("href","javascript:void(0)").attr("rel","nofollow").append(typeof o.nextImg != 'undefined' ? $(document.createElement("img")).attr("src",o.nextImg) : "Next").click(function(){
						i = findActiveIndex(obj.find("li"));
						if(i + 1 < l){
							idx = i + 1;
						} else {
							idx = 0;
						}
						d.text((idx + 1) + "/" + l);
						crossFade(obj,obj.children("li:eq("+idx+")"),o.speed);
						//console.log("Index after click: ",idx);
					});
				var p = $(document.createElement("a")).addClass("prev").attr("href","javascript:void(0)").attr("rel","nofollow").append(typeof o.prevImg != 'undefined' ? $(document.createElement("img")).attr("src",o.prevImg) : "Previous").click(function(){
						i = findActiveIndex(obj.find("li"));
						if(i - 1 > 0){
							idx = i - 1;
						} else {
							idx = l - 1;
						}
						d.text((idx + 1) + "/" + l);
						crossFade(obj,obj.children("li:eq("+idx+")"),o.speed);
						//console.log("Index after click: ",idx);
					});
					
				if(l > 1){
					c.insertAfter(obj).append(p).append(d).append(n);
				}
            });  
        }
    });        
})(jQuery); 

function crossFade(collection, el, speed){
	collection.children("li").fadeOut(speed);
	collection.children("li").removeClass("active");
	el.fadeIn(speed).addClass("active");
}

function findActiveIndex(collection){
	var i = -1;
	$.each(collection, function(x,y){
		if($(this).hasClass("active")){
			i = x;
		}
	})
	return i;
}
