/*
 * simplyScroll 1.0.4 - a scroll-tastic jQuery plugin
 *
 * http://logicbox.net/jquery/simplyscroll
 * http://logicbox.net/blog/simplyscroll-jquery-plugin
 * http://plugins.jquery.com/project/simplyScroll
 *
 * Copyright (c) 2009 Will Kelly - http://logicbox.net
 *
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Last revised: 03/07/2009 21:13
 *
 */

(function($) {

$.fn.simplyScroll = function(o) {
	return this.each(function() {
		new $.simplyScroll(this,o);
	});
};

var defaults = {
	className: 'simply-scroll',
	frameRate: 24, //No of movements per second
	speed: 1, //No of pixels per frame
	horizontal: true,
	autoMode: 'off', //disables buttons 'loop','bounce'
	pauseOnHover: true,
	startOnLoad: false, //use this if having rendering problems (safari 3 + Mac OSX?)
	localJsonSource: '', //format [{"src":"images/pic.jpg","title":"title","link":"http://"},{etc..}]
	flickrFeed: '',
	jsonImgWidth: 240,
	jsonImgHeight: 180
};
	
$.simplyScroll = function(el,o) {
	
	var self = this;
	
	this.o = $.extend({}, defaults, o || {});
	this.auto = this.o.autoMode!=="off" ? true : false;
	
	//called on ul/ol/div etc
	this.$list = $(el);
	
	if (!this.o.auto) { //button placeholders
		this.$list.parent().parent()
		.prepend('<div class="simply-scroll-forward"></div>')
		.prepend('<div class="simply-scroll-back"></div>');
	}
	

        if (!this.o.startOnLoad) {
                this.init();
        } else {
                //wait for load before completing setup
                $(window).load(function() { self.init();  });
        }
		
};
	
$.simplyScroll.fn = $.simplyScroll.prototype = {};

$.simplyScroll.fn.extend = $.simplyScroll.extend = $.extend;

$.simplyScroll.fn.extend({
	init: function() {
		//shortcuts
		this.$items = this.$list.children();
		this.$clip = this.$list.parent();
		this.$container = this.$clip.parent();

		if (!this.o.horizontal) {
			this.itemMax = this.$items[0].offsetHeight; //this.$items[0].offsetHeight;
			this.clipMax = this.$clip.height(); //this.$clip[0].offsetHeight;
			this.dimension = 'height';			
			this.moveBackClass = 'simply-scroll-btn-up';
			this.moveForwardClass = 'simply-scroll-btn-down';
		} else {
			this.itemMax = this.$items[0].offsetWidth;
			this.clipMax = this.$clip.width();			
			this.dimension = 'width';
			this.moveBackClass = 'simply-scroll-btn-left';
			this.moveForwardClass = 'simply-scroll-btn-right';
		}
		
		this.posMin = 0;
		//this.posMax = this.$items.length * this.itemMax;

                var total_height = 0;

                for (i = 0; i < this.$items.length; i++) {

                    total_height += this.$items[i].offsetHeight;

                }

		this.posMax = total_height;

                this.totalHeight = total_height;

		this.$list.css(this.dimension,this.posMax +'px');
                
                //window.status = 'item:' + this.$items.length.toString() + ' posMax:' + this.posMax.toString() + ' clipMax:' + this.clipMax.toString() + ' itemMax:' + this.itemMax.toString() + ' clipMax:' + this.clipMax.toString();
		
		if (this.o.autoMode=='loop' && this.posMax < (2*this.clipMax - this.o.speed)) {
			var addItems = this.$items.length;//Math.ceil(this.clipMax / this.itemMax);
			this.$items.slice(0,addItems).clone(true).appendTo(this.$list);
			this.posMax += (this.clipMax - this.o.speed);
			this.$list.css(this.dimension,this.posMax+total_height+'px');//(this.itemMax*addItems) +'px');
		}
		
		this.interval = null;	
		this.intervalDelay = Math.floor(1000 / this.o.frameRate);
		
		//ensure that speed is divisible by item width
		while (this.itemMax % this.o.speed !== 0) {
			this.o.speed--;
			if (this.o.speed===0) {
				this.o.speed=1; break;	
			}
		}
		
		var self = this;
                this.nomorehover = false;
		this.trigger = null;
                this.concreteResume = function() {self.nomorehover = false; self.o.speed = 1; self.trigger=this; self.moveForward();}
		this.funcMoveBack = function() { self.trigger=this;self.moveBack(); };
		this.funcMoveForward = function() { self.trigger=this;self.moveForward(); };
		this.funcClickMoveBack = function() { self.nomorehover = true; self.moveStop(); self.o.speed = 5; self.trigger=this;self.moveBack(); };
		this.funcClickMoveForward = function() { self.nomorehover = true; self.moveStop(); self.o.speed = 5; self.trigger=this;self.moveForward(); };
		this.funcMoveStop = function() { self.moveStop(); };
		this.funcMoveResume = function() { if (!self.nomorehover) {self.moveResume();} };
		this.funcMoveResumeAfterPause = function() { self.moveStop(); setTimeout(self.concreteResume, 1000); };
		
		if (this.auto) {
			if (this.o.pauseOnHover) {
				this.$clip.hover(this.funcMoveStop, this.funcMoveResume);
			}

			this.$btnBack = jQuery('.simply-scroll-back')
				.addClass('simply-scroll-btn' + ' ' + this.moveBackClass + ' ' + 'disabled')
				.mousedown(this.funcClickMoveBack)
				.mouseup(this.funcMoveResumeAfterPause);
			this.$btnForward = jQuery('.simply-scroll-forward')
				.addClass('simply-scroll-btn' + ' ' + this.moveForwardClass)
				.mousedown(this.funcClickMoveForward)
				.mouseup(this.funcMoveResumeAfterPause);

			this.moveForward();
                        
		} else {
			this.$btnBack = jQuery('.simply-scroll-back')
				.addClass('simply-scroll-btn' + ' ' + this.moveBackClass + ' ' + 'disabled')
				.hover(this.funcMoveBack,this.funcMoveStop);

			this.$btnForward = jQuery('.simply-scroll-forward')
				.addClass('simply-scroll-btn' + ' ' + this.moveForwardClass)
				.hover(this.funcMoveForward,this.funcMoveStop);
		}
	},
	moveForward: function() {
		var self = this;

                if (this.o.autoMode=='loop' && self.posMax < (2*self.clipMax - self.o.speed)) {

                    return;
                }

		this.movement = 'forward';
		if (this.trigger !== null) {
			this.$btnBack.removeClass('disabled');
		}

		self.interval = setInterval(function() {
//                window.status = 'scrollTop:' + self.$clip[0].scrollTop.toString() + ' minus:' + (self.posMax-self.clipMax).toString();
//                window.status = 'self.posMax:' + self.posMax.toString() + ' self.clipMax' + self.clipMax.toString();
			if (!self.o.horizontal && self.$clip[0].scrollTop < (self.posMax-self.clipMax)) {
				self.$clip[0].scrollTop += self.o.speed;
			} else if (self.o.horizontal && self.$clip[0].scrollLeft < (self.posMax-self.clipMax)) {
				self.$clip[0].scrollLeft += self.o.speed; 
			} else {
				self.resetPos();
			}
		},self.intervalDelay);
	},
	moveBack: function() {
		var self = this;

                if (this.o.autoMode=='loop' && self.posMax < (2*self.clipMax - self.o.speed)) {

                    return;
                }

		this.movement = 'back';
		if (this.trigger !== null) {
			this.$btnForward.removeClass('disabled');
		}

		self.interval = setInterval(function() {
//                window.status = 'scrollTop:' + self.$clip[0].scrollTop.toString() + ' minus:' + (self.posMax-self.clipMax).toString();
			if (!self.o.horizontal && self.$clip[0].scrollTop>0) {
				self.$clip[0].scrollTop -= self.o.speed;
			} else if (self.o.horizontal && self.$clip[0].scrollLeft>0) {
				self.$clip[0].scrollLeft -= self.o.speed;
			} else {
				self.resetPos();
			}
		},self.intervalDelay);
	},
	moveStop: function(moveDir) {
		clearInterval(this.interval);	
		if (this.trigger!==null) {
			if (typeof moveDir != "undefined") {
				$(this.trigger).addClass('disabled');
			}
			this.trigger = null;
		}
		if (this.auto) {
			if (this.o.autoMode=='bounce') {
				moveDir == 'forward' ? this.moveBack() : this.moveForward();
			}
		}
	},
	moveResume: function() {
		this.movement=='forward' ? this.moveForward() : this.moveBack();
	},
	resetPos: function() {
//                window.status = 'scrollTop:' + this.$clip[0].scrollTop.toString();
		if (!this.o.horizontal) {

                        if (this.movement=='forward') {

                            this.$clip[0].scrollTop = 0;

                        } else {
                            
                            this.$clip[0].scrollTop = this.totalHeight;
                            
                        }

		} else {
			this.$clip[0].scrollLeft = 0;
		}
	},
	renderData: function(json) {
		if (json.length>0) { //render json data
			var self = this;
			$.each(json, function(i,item) {
				$("<img/>").attr({
					src: item.src,
					title: item.title,
					alt: item.title,
					width: self.o.jsonImgWidth,
					height: self.o.jsonImgHeight
				}).appendTo(self.$list);
			});
			this.init();
		}
	}
});
		  
})(jQuery);
