/**
 * jquery.scrollable 1.0.2. Put your HTML scroll.
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/scrollable.html
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 *
 * Launch  : March 2008
 * Version : 1.0.2 - Tue Feb 24 2009 10:52:08 GMT-0000 (GMT+00:00)
 */
(function($) {
		
	function fireEvent(opts, name, self, arg) {
		var fn = opts[name];
		
		if ($.isFunction(fn)) { 
			try {  
				return fn.call(self, arg);
				
			} catch (error) {
				if (opts.alert) {
					alert("Error calling scrollable." + name + ": " + error);
				} else {
					throw error;	
				}
				return false;
			} 					
		}
		return true;			
	}
				
	var current = null;	
	
	
	// constructor
	function Scrollable(root, conf) {   
				
		// current instance
		var self = this;  
		if (!current) { current = self; }		
		
		// horizontal flag
		var horizontal = !conf.vertical;		
		
		// wrap (root elements for items)
		var wrap = $(conf.items, root);				
		
		// current index
		var index = 0;
		
		var showreel = conf.showreel;
		
		// get handle to navigational elements
		var navi = root.siblings(conf.navi).eq(0);
		var prev = root.siblings(conf.prev).eq(0);
		var next = root.siblings(conf.next).eq(0);
		var prevPage = root.siblings(conf.prevPage).eq(0);
		var nextPage = root.siblings(conf.nextPage).eq(0);
		
		var num_children = $(conf.items,root).children().size();
		var count_i = 0;
		var width = 0;
		var total_width = 650;
		var movement_step = 50;
		var custom_width = 0;
		var margin_left = 0;
		var p = conf.start_offset;
		var width_left = 0;
		var width_right = 0;
		var is_item = conf.item_selected;
		var right_of_center = ((total_width / 2) + 50);
		var left_of_center = ((total_width / 2) - 50);

		for(j=0;j<num_children;++j) {
			width += $(conf.items,root).children().eq(j).outerWidth(true);
		}
		
		//if p is set - then we want to know what the width is on either side of p (the offset)
		if(p){
			//width left is the width of the items up until p
			for(j=0;j<p;++j) {
				width_left += $(conf.items,root).children().eq(j).outerWidth(true);
			}
			width_right = width - width_left;
			//width right is the total with, minus width_left
		}else{
			width_left = 0;
			width_right = width;
		}
		
		//negative is move to the left, positive is to the right
		if(is_item){
			var negative_max_i = Math.ceil(-((width_right - right_of_center) / movement_step));
			if(negative_max_i > 0){ negative_max_i = 0; } //if there's a gap to the right, then don't move here, obviously.
			var positive_max_i = Math.floor((width_left - left_of_center)/movement_step);
			if(positive_max_i < 0){ positive_max_i = 0; } //if there's a gap to the left, then don't move here, obviously.
		}else{
			var negative_max_i = Math.ceil(-((width_right - total_width) / movement_step));
			var positive_max_i = Math.ceil((width_left)/movement_step);
		}
		
		// methods
		$.extend(self, {
				
			getVersion: function() {
				return [1, 0, 1];	
			},
			
			getIndex: function() {
				return index;	
			},
	
			getConf: function() {
				return conf;	
			},
			
			getSize: function() {
				//return self.getItems().size();	
				//set to 200 items so we can scroll enough?
				return 200;
			},
	
			getPageAmount: function() {
				return Math.ceil(this.getSize() / conf.size); 	
			},
			
			getPageIndex: function() {
				return Math.ceil(index / conf.size);	
			},

			getRoot: function() {
				return root;	
			},
			
			getItemWrap: function() {
				return wrap;	
			},
			
			getItems: function() {
				return wrap.children();	
			},
			
			/* all seeking functions depend on this */		
			seekTo: function(i, time, fn) {
				//set up the offset depending on the page type we're viewing
				var allow_scroll = true;
				
				
				//alert('i = '+i+'\n width = '+width+'\n width_left = '+width_left+'\n width_right = '+width_right+'\n negative_max_i = '+negative_max_i+'\n positive_max_i = '+positive_max_i+'\n p = '+p+'\n movement = '+movement+'\n margin_left = '+margin_left+'');

				
				if(is_item){
					//this means we have an item, so we want to follow one set of rules
					//RULES
					//center the currently selected item
					//if width_left and width_right are less than 1/2 total width of playlist bar, don't allow scrolling (although, this really could be inherit from main rules of scrolling)
					//scrolling left/right should only go as far as the edge of the playlist container
					margin_left = ((total_width / 2) - 50); //get the center point (i.e. 270) this also sets the default if we have an item, but it's the first (0th) one.
					if(p){
						margin_left = margin_left - width_left;
					}
					wrap.css('margin-left',margin_left+'px');
					
					if((width_left < left_of_center) && (width_right < right_of_center)){
						//alert('not moving this because the playlist fits');
						allow_scroll = false;
					}
					//alert('we can scroll the playlist left/right to move items onto the screen');
				}else{
					//this means we don't have an item, so follow a different set
					
					//if total width is less than total width of playlist bar, center the whole thing and don't allow scrolling (inherit?)
					// if width is more than the total width, left align the playlist, and allow scrolling to the right as far as the last item fits into the playlist bar.
					
					if(width < total_width){
						//alert('item list is less than the total width - centering the whole thing');
						margin_left = ((total_width - width)/2);
						wrap.css('margin-left',margin_left+'px');
						
						allow_scroll = false;
					}else{
						//alert('item list is more than the total width');
						margin_left = 0;
						wrap.css('margin-left',margin_left+'px');
						
						allow_scroll = true;
					}
					
				}
				
				
				//i is seek to offset by scrolling
				//p is seek to (setup)

				// default speed
				time = time || conf.speed;
				
				// function given as second argument
				if ($.isFunction(time)) {
					fn = time;
					time = conf.speed;
				}
				
				// onBeforeSeek
				if (fireEvent(conf, "onBeforeSeek", self, i) === false) {
					return self;
				}	
				
				//do the scrolling
				var movement = false; //declare

				if(allow_scroll){
					
					//update code so that scrolling in either direction stops when the first/last item hits the start/end of the playlist area
					
						var movement = (movement_step * i); //the standard movement
						if(i < 0){
							//if i is negative, then keep moving the playlist to the left while the movement is greater than the width_right 
							if(-movement < (width_right - 90)){
								//fine to move, don't do anything
							}else{
								//we've reached the end, stop it from adding
								var movement = (-width_right + 90); //this stops the actual movement
								//stop i from incrementing (negatively) - this is done below
							}
						}
						if(i > 0){
							//if i is positive, then keep moving the playlist right while width_left is greater than the movement
							if(movement < (width_left)){
								//keep on moving, we've got more to go
							}else{
								//we've reached the end, stop it from adding
								var movement = (width_left); //this stops the actual movement
								//stop i from incrementing - this is done below
							}
						}
					
					
					
				}
				
				wrap.animate({left: movement}, time, conf.easing, fn ? function() { fn.call(self); } : null);							
				
				
				// prev buttons disabled flag
				if (i === 0) {
					prev.add(prevPage).addClass(conf.disabledClass);					
				} else {
					prev.add(prevPage).removeClass(conf.disabledClass);
				}
								
				// next buttons disabled flag
				if (i >= self.getSize()) {
					next.add(nextPage).addClass(conf.disabledClass);
				} else {
					next.add(nextPage).removeClass(conf.disabledClass);
				}				
				
				current = self;

				if(i <= negative_max_i){
					index = negative_max_i;
				}else if(i >= positive_max_i){
					index = positive_max_i;
				}else{
					index = i;
				}

				// onSeek after index being updated
				fireEvent(conf, "onSeek", self, i);	
				
				return self;
				
			},			
				
			move: function(offset, time, fn) {
				var to = index + offset;
				if (conf.loop && to > (self.getSize() - conf.size)) {
					to = 0;
				}
				//set to to something dumb
				return this.seekTo(to, time, fn);
			},
			
			next: function(time, fn) {
				return this.move(-1, time, fn);	
			},
			
			prev: function(time, fn) {
				return this.move(1, time, fn);	
			},
			
			movePage: function(offset, time, fn) {
				return this.move(conf.size * offset, time, fn);		
			},
			
			setPage: function(page, time, fn) {
				var size = conf.size;
				var index = size * page;
				var lastPage = index + size >= this.getSize(); 
				if (lastPage) {
					index = this.getSize() - conf.size;
				}
				return this.seekTo(index, time, fn);
			},
			
			prevPage: function(time, fn) {
				return this.setPage(this.getPageIndex() + 1, time, fn);
			},  
	
			nextPage: function(time, fn) {
				return this.setPage(this.getPageIndex() - 1, time, fn);
			}, 
			
			begin: function(time, fn) {
				return this.seekTo(0, time, fn);	
			},
			
			end: function(time, fn) {
				return this.seekTo(this.getSize() - conf.size, time, fn);	
			},
			
			reload: function() {
				return load();	
			},
			
			click: function(index, time, fn) {
								
				var item = self.getItems().eq(index);
				var klass = conf.activeClass;			
				
				if (!item.hasClass(klass) && (index >= 0 || index < this.getSize())) {				
					self.getItems().removeClass(klass);
					item.addClass(klass);
					var delta = Math.floor(conf.size / 2);
					var to = index - delta;

					// next to last item must work
					if (to > self.getSize() - conf.size) { to--; 	}
					
					if (to !== index) {
						return this.seekTo(to, time, fn);		
					}				 
				}
				
				return self;
			}			
			
		});
	
		
		// mousewheel
		if ($.isFunction($.fn.mousewheel)) { 
			root.bind("mousewheel.scrollable", function(e, delta)  {
				// opera goes to opposite direction
				var step = $.browser.opera ? -1 : 1;
				
				self.move(delta > 0 ? step : -step, 50);
				return false;
			});
		}  
		
		// prev button		
		prev.addClass(conf.disabledClass).click(function() { 
			self.prev(); 
		});
		

		// next button
		next.click(function() { 
			self.next(); 
		});
		
		// prev page button
		nextPage.click(function() { 
			self.nextPage(); 
		});
		

		// next page button
		prevPage.addClass(conf.disabledClass).click(function() { 
			self.prevPage(); 
		});		

		
		// keyboard
		if (conf.keyboard) {
			
			// unfortunately window.keypress does not work on IE.
			$(window).unbind("keypress.scrollable").bind("keypress.scrollable", function(evt) {
				
				var el = current;	
				if (!el) { return; }
					
				if (horizontal && (evt.keyCode == 37 || evt.keyCode == 39)) {					
					el.move(evt.keyCode == 37 ? 1 : -1);
					return evt.preventDefault();
				}	
				
				if (!horizontal && (evt.keyCode == 38 || evt.keyCode == 40)) {
					el.move(evt.keyCode == 38 ? 1 : -1);
					return evt.preventDefault();
				}
				
				return true;
				
			});	 
		}

		// navi 			
		function load() {			
			
			navi.each(function() {
				
				var nav = $(this);
				
				// generate new entries
				if (nav.is(":empty") || nav.data("me") == self) {
					
					nav.empty();
					nav.data("me", self);
					
					for (var i = 0; i < self.getPageAmount(); i++) {		
						
						var item = $("<" + conf.naviItem + "/>").attr("href", i).click(function(e) {							
							var el = $(this);
							el.parent().children().removeClass(conf.activeClass);
							el.addClass(conf.activeClass);
							self.setPage(el.attr("href"));
							return e.preventDefault();
						});
						
						if (i === 0) { item.addClass(conf.activeClass); }
						nav.append(item);					
					}
					
				// assign onClick events to existing entries
				} else {
					
					// find a entries first -> syntaxically correct
					var els = nav.children(); 
					
					els.each(function(i)  {
						var item = $(this);
						item.attr("href", i);
						if (i === 0) { item.addClass(conf.activeClass); }
						
						item.click(function() {
							nav.find("." + conf.activeClass).removeClass(conf.activeClass);
							item.addClass(conf.activeClass);
							self.setPage(item.attr("href"));
						});
						
					});
				}
				
			});
			
			
			// item.click()
			if (conf.clickable) {
				self.getItems().each(function(index, arg) {
					var el = $(this);
					if (!el.data("set")) {
						el.bind("click.scrollable", function() {
							self.click(index);		
						});
						el.data("set", true);
					}
				});				
			}
			
			
			// hover
			if (conf.hoverClass) {
				self.getItems().hover(function()  {
					$(this).addClass(conf.hoverClass);		
				}, function() {
					$(this).removeClass(conf.hoverClass);	
				});
			}			
			
			return self;
		}
		
		load();
		
		
		// interval stuff
		var timer = null;

		function setTimer() {
			timer = setInterval(function()  {
				self.next();
				
			}, conf.interval);	
		}	
		
		if (conf.interval > 0) {			
			
			root.hover(function() {			
				clearInterval(timer);		
			}, function() {		
				setTimer();	
			});
			
			setTimer();	
		}
		
	} 

		
	// jQuery plugin implementation
	jQuery.prototype.scrollable = function(conf) { 
			
		// already constructed --> return API
		var api = this.eq(typeof conf == 'number' ? conf : 0).data("scrollable");
		if (api) { return api; }		
		
 
		var opts = {
			
			// basics
			size: 5,
			vertical:false,			
			clickable: true,
			loop: false,
			interval: 0,			
			speed: 400,
			keyboard: true,	
			start_offset: 0,
			item_selected: false,
			
			// other
			activeClass:'active',
			disabledClass: 'disabled',
			hoverClass: null,			
			easing: 'swing',
			
			// navigational elements
			items: '.items',
			prev: '.prev',
			next: '.next',
			prevPage: '.prevPage',
			nextPage: '.nextPage',			
			navi: '.navi',
			naviItem: 'a',

			
			// callbacks
			onBeforeSeek: null,
			onSeek: null,
			alert: true
		}; 
		
		
		$.extend(opts, conf);		
		
		this.each(function() {			
			var el = new Scrollable($(this), opts);
			$(this).data("scrollable", el);	
		});
		
		return this; 
		
	};
			
	
})(jQuery);

