jQuery.fn.extend({
	opts : new Object ,
	o 	 : new Object ,
	pos : new Array,
	interval : new String,
	curPos : new String,
	left : new String,
	galInit : function(opts) {
		cont = jQuery(this);
		o = opts;
		o.inAction = false;
		cont.append('<div class="galLoading" style="float:left"><img src="/loading.gif"/></div>');
		cont.find('ul').css('visibility','hidden');
		var LoadInt = window.setInterval(function() {
			totalItems = new Array;
			loadedItems = new Array();
			  	// register mouse event
			cont.hover(function() {
					cont.mousemove(function(e){
						o.x  = e.clientX-cont.offset().left;
					});
			},function() {
				o.x = false;
				cont.unbind('mousemove');
			});

			cont.find('ul li img').each(function(index) {
				var item = jQuery(this);
				
				if(item.width()>5) {
					loadedItems.push(1);					
				} 
				totalItems.push(1);
			});
			if(loadedItems.length>=totalItems.length) {
				window.clearInterval(LoadInt);
				jQuery.fn.gal();
			}
		},200);
	},
	
	gal : function() {
		cont.find('ul').css('visibility','visible');
		jQuery('.galLoading').hide();
		
		interval = 0;
		curPos = 0;
		pos = new Array;
			var totalWidth = 0;
			 cont.find('ul li img').each(function(index) {
			       var item = jQuery(this);
				   pos.push(totalWidth);
			       totalWidth+=item.width()+10;
				   
	        });
	    	cont.find('ul').css('width',pos.length*950);  
			cont.css('position','relative');
    		cont.find('ul').css('position','relative');
			left = 0;

			jQuery.fn.galStart(1);
	},
	galStart : function(i) {
		if (interval) {
			window.clearInterval(interval);
		}
					 
		interval = window.setInterval(function() {
			jQuery.fn.galDirect(i);
		},o.waitDuration);
	},
	galDirect : function(i) {
			// MOUSE FUNCTION
			if (o.x > 0) {
				if (o.x > (cont.width() / 2)) {
					i=1;
				}
				else {
					i=-1;
				}
			}
			
			
			/////
			curPos+=i;
			if(curPos<0) {
				i=1;
				curPos = 1;
			} else if(curPos>(pos.length-1)) {
				i=-1;
				curPos = pos.length-2;
			}
		
			o.inAction = true;
	    	cont.find('ul').animate({ 
		        left: -pos[curPos]
		      }, o.animationDuration,function() {
			  	o.inAction = false;
			  });
		if (interval) {
			window.clearInterval(interval);
		}
		window.setTimeout(function() {
			jQuery.fn.galStart(i);
		},o.animationDuration)	
	}
});

jQuery.fn.gal.defaults = {
  animationDuration : 1000,
  waitDuration      : 1000
}; 