(function($){

	var settings = {
		button_left:null,
		button_right:null,
		button_top:null,
		button_bottom:null,
		hlimit:null,
		vlimit:null,
		hpage:1,
		vpage:1,
		hindex:0,
		vindex:0,
		callback:null,
		view:null
	};

  	var methods = {
		config: function(options){
			$.extend(settings, options);
		},
		
		init:function(options){
			$.extend(settings, options);		
			$(this).each(function(){
				function updateVisibility() {
					options.left_button.css("visibility", hindex <= 0 ? "hidden" : "visible");
					options.right_button.css("visibility", hindex >= options.hlimit - options.hpage ? "hidden" : "visible");
				}
				
				function handleMouseWheel(e,delta) {
					//$.log(delta);
				}
				
				var vindex = 0;
				var hindex = 0;
				updateVisibility();
				options.left_button.click(function() {
					hindex = constrain(--hindex,0,options.hlimit);
					updateVisibility();
					options.callback({type:"left",x:hindex});
				});
				
				options.right_button.click(function() {
					hindex = constrain(++hindex,0,options.hlimit);
					updateVisibility();
					options.callback({type:"right",x:hindex});
				});
				
				if(options.view) {
					options.view.bind('mousewheel',handleMouseWheel);
				}
			});
		},
		
		update:function(){
			
		}
	};

	function updateVisibility() {
		if(hindex >= options.hlimit) {
			options.right_button.css("visibility","hidden");
		} else if(hindex <= 0) {
			options.left_button.css("visibility","hidden");
		}
	}
	
	function constrain(n,m,l) {
		if(n > l){
			n = l;
		} else if(n < m) {
			n = m;
		}
		
		return n;
	}

	$.fn.iwsGalleryController = function(method){
		if (methods[method]){
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error('Method ' +  method + ' does not exist on jQuery.iwsGalleryController');
		}    
	};
  
})(jQuery);
