/*
* jQuery UI carousel
* 
* Depends:
*   ui.core.js
* 
*/

(function($) {
	
	$.widget("ui.carousel", {
				
		_init: function() {	
			var self = this;
			self.initdata();
			self.hookLinks();
			self.autoplay();
		},
		
		initdata: function(){
			var self = this;
			var widthsplit = self.options.finalWidth;

			self.options.curposi = self.getCurPosi();
			self.options.maxwidth = Number(widthsplit);
			self.options.singlewidth = Number(widthsplit) / Number(self.options.sliders);

			self.element.css("width", (widthsplit+self.options.singlewidth)+"px");
				
			if(self.options.roundabout == true){
				var elementone = self.element.find("#slide_1").clone();	
				$(elementone).appendTo(self.element);
			}
			
			self.slide(self.options.to);
			
		},
		
		getCurPosi: function(){
			var self = this;
			var posi = self.element.css("left").split("px");
			posi = posi[0];	
			return Number(posi);
		},
		
		slide: function(to, reset){
			var self = this;
			
			if(to == "prev"){
				if(self.options.to > 1){
					to = (self.options.to - self.options.slidesteps)-1;
					if(to<1){
						to = 1;
					}
				}
				else{
					to = 1;
				}
			}else if(to == "next"){
				if(self.options.to < self.options.sliders){
					to = (self.options.to + self.options.slidesteps)+1;
					if(to > self.options.sliders){
						to = self.options.sliders;
					}
				}
				else{
					to = self.options.to;
				}
			}
			
			var to_ =  Number("-"+((to-1) * self.options.singlewidth));
			self.element.stop().animate({left: to_}, self.options.slidespeed, null , function(){
				if(reset == true){
					$(self.element).css("left", "0");
				}
			});
			if(to>self.options.sliders){
				$(self.element).css("left", "0");
				self.options.to = 1;
			}
			self.options.to = to;
			
		},
		
		hookLinks: function(){
			var self = this;
			self.options.hook_links(self);
		},
		
		stopplay: function(){
			var self = this;
			self.options.auto = false;
		},
		
		startplay: function(){
			var self = this;
			self.options.auto = true;
		},
		
		autoplay: function(){
			var self = this;
			var count = 2;
						
				setInterval(function(){
					if(self.options.auto === true){
					if(count > Number(self.options.sliders)){
						count = 1;		
						self.slide(self.options.sliders + 1, true);						
					}else{
						self.slide(count);
					}
					count++;
					}
					
				}, self.options.playtimer);
		}
	
	});
	
	$.extend($.ui.carousel,{
		defaults: {
			sliders: 3,
			hook_links: function(self){
				return false;
			},
			auto: true,
			playtimer: 5000,
			slidespeed: 1000,
			finalWidth: false,
			to: 1,
			slidesteps: 0,
			roundabout: true
		}
	});
})(jQuery);
