
var xC;
var infinityfixonlyonce = false;
var infinitytest  = false;
(function($) {

$.fn.simplyScroll = function(o) {
	return this.each(function() {
		new $.simplyScroll(this,o);
	});
};

var defaults = {
	className: 'simply-scroll',
	frameRate: 24,
	speed: 1,
	horizontal: true,
	autoMode: 'off', 
	pauseOnHover: true,
	startOnLoad: false,
	localJsonSource: '', //format [{"src":"images/pic.jpg","title":"title","link":"http://"},{etc..}]
	flickrFeed: '',
	jsonImgWidth: 240,
	jsonImgHeight: 180
};
	
$.simplyScroll = function(el,o) {
	
	var self = this;
	var doreturn = self;
  
	this.o = $.extend({}, defaults, o || {});
	this.auto = this.o.autoMode!=="off" ? true : false;
	
	//called on ul/ol/div etc
	this.$list = $(el);
	
	//generate extra markup
	this.$list.addClass('simply-scroll-list')
		.wrap('<div class="simply-scroll-clip"></div>')
		.parent().wrap('<div class="' + this.o.className + ' simply-scroll-container"></div>');
	
	if (!this.o.auto) { //button placeholders
		this.$list.parent().parent()
		.prepend('<div class="simply-scroll-forward"></div>')
		.prepend('<div class="simply-scroll-back"></div>');
	}
	
	//load image data
	if (this.o.flickrFeed) {
		$.getJSON(this.o.flickrFeed + "&format=json&jsoncallback=?",
			function(data) {
				json = [];
				$.each(data.items, function(i,item) {
					json.push({
						"src": item.media.m,
						"title": item.title,
						"link": item.link
					});
				});
				self.renderData(json);
			}
		);
	} else if (this.o.localJsonSource) {
		$.getJSON(this.o.localJsonSource,
			function(json) {
				self.renderData(json);
			}
		);
	} else {
		
		if (!this.o.startOnLoad) {
			this.init();
		} else {
			//wait for load before completing setup
			$(window).load(function() { self.init(); });
		}
		
	}
		
return doreturn};
	
$.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;
		this.$list.css(this.dimension,this.posMax +'px');        
    
		if (this.o.autoMode=='loop') {
      isToInfinit = false;
      if (isToInfinit ==  true)
      { var addItems = 0; }
      else
      { var addItems = Math.ceil(this.clipMax / this.itemMax);
        var addItems  = this.$items.length;
  			this.$items.slice(0,addItems).clone(true).appendTo(this.$list);
  			this.posMax += (this.clipMax - this.o.speed);
  			this.$list.css(this.dimension,this.posMax+(this.itemMax*addItems) +'px');
      };      
		}
		
		this.$container.css('left','0px');
    this.$clip.css('left','0px');
    this.$list.css('left','0px');
    
    this.$container.scrollLeft(0);
    this.$clip.scrollLeft(0);
    this.$list.scrollLeft(0);
    this.$clip[0].scrollLeft  = 0;    
    
		this.interval = null;
    this.mouseMoveInterval = 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;	
			}
		}
		
		// SPEED
    //this.o.speed  = 0.2;    
    
		var self = this;
		this.trigger = null;
		this.funcMoveBack = function() { self.trigger=this;self.moveBack(); };
		this.funcMoveForward = function() { self.trigger=this;self.moveForward(); };
		this.funcMoveStop = function() { self.moveStop(); };
		this.funcMoveResume = function() { self.moveResume(); };
    
    this.funcMouseMove  = function() { self.mouseMove(); };
		xC = self;
		if (this.auto) {
			if (this.o.pauseOnHover) {
				this.$clip.hover(this.funcMouseMove,this.funcMoveResume);
			}
			//this.moveForward();
      //self.resetPos();      
      this.movement = 'forward';                      
      
		} else {
			this.$btnBack = $('.simply-scroll-back',this.$container)
				.addClass('simply-scroll-btn' + ' ' + this.moveBackClass + ' ' + 'disabled')
				.hover(this.funcMoveBack,this.funcMoveStop);
			this.$btnForward = $('.simply-scroll-forward',this.$container)
				.addClass('simply-scroll-btn' + ' ' + this.moveForwardClass)
				.hover(this.funcMoveForward,this.funcMoveStop);
		}
	return self},
	moveForward__in_work: function() {
		var self = this;
    clearInterval(self.mouseMoveInterval);
		this.movement = 'forward';
		if (this.trigger !== null) {
			this.$btnBack.removeClass('disabled');
		} 
    windowWidth = $(window).width();                                 
		self.interval = setInterval(function() {                  
			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.scrollLeft() < (self.posMax-windowWidth)) {
        if (self.$clip.scrollLeft() > 2000)
        { $('#debug').append(self.$clip.scrollLeft() + ' ' + self.$clip[0].scrollLeft + ' ' + self.posMax + ' ' + self.clipMax + ' ' + (self.posMax-self.clipMax) + '<br>');  };        
				self.$clip[0].scrollLeft += self.o.speed; 
			} else if (self.o.autoMode=='loop') {
        $('#debug').append(self.$clip.scrollLeft() + ' ' + self.$clip[0].scrollLeft + ' ' + self.posMax + ' ' + self.clipMax + ' ' + (self.posMax-self.clipMax) + '<br>');
				self.resetPos();
			} else {
				self.moveStop(self.movement);
			}
		},self.intervalDelay);
	},  
	moveForward: function() {
		var self = this;
    clearInterval(self.mouseMoveInterval);
		this.movement = 'forward';
		if (this.trigger !== null) {
			this.$btnBack.removeClass('disabled');
		}
		self.interval = setInterval(function() {
			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 if (self.o.autoMode=='loop') {
				self.resetPos();
			} else {
				self.moveStop(self.movement);
			}
		},self.intervalDelay);
	},   
	moveBack: function() {
		var self = this;
    clearInterval(self.mouseMoveInterval);
		this.movement = 'back';
		if (this.trigger !== null) {
			this.$btnForward.removeClass('disabled');
		}
		self.interval = setInterval(function() {
			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 if (self.o.autoMode=='loop') {
				self.resetPos();
			} else {
				self.moveStop(self.movement);
			}
		},self.intervalDelay);
	},
	moveStop: function(moveDir) {
		clearInterval(this.interval);
    clearInterval(self.mouseMoveInterval);	
		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() {
    var self = this; 
    clearInterval(self.mouseMoveInterval);
		if (!this.o.horizontal) {
			this.$clip[0].scrollTop = 0;
		} else {
      theNewValue = (browserName!=IDie ? 237  : 0);
      		this.$container.css('left', '0px');
          this.$clip.css('left','0px');
          this.$list.css('left','0px');
          
          this.$container.scrollLeft(0);          
          this.$list.scrollLeft(0);
          this.$clip.scrollLeft(theNewValue);
          this.$clip[0].scrollLeft  = theNewValue;
		}
	},
	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();
		}
	},
  
	moveLeftToRight: function(theM) {
		var self = this;
		this.movement = 'forward';
		if (this.trigger !== null) {
			this.$btnBack.removeClass('disabled');
		}        
    var thisMovementInterval  = (thisIsIE == true ? 3 : 6);    
    self.mouseMoveInterval = setInterval(function() {          
     //self.$clip[0].scrollLeft += (self.o.speed  + (theM/400));     
     // The cloning
        isToInfinit = true;
        if (isToInfinit ==  true)     
        { theLastC  = self.$list.children("li:last");
          theFirstC = self.$list.children("li:first");                        
          howMuch   = (self.$clip.scrollLeft() + (self.o.speed  + ((theM/(thisIsIE == true ? 200 : 200)) + (thisIsIE == true ? 1 : 0))));
          thisWidth  = theFirstC.outerWidth();                              
          CLeft      = self.$clip.scrollLeft();                            
          if(CLeft >=  thisWidth)
          { theLastC.after(theFirstC);                        
            cval  = theFirstC.outerWidth();
            if (cval  < 200)  { cval  = 237;  };
            howMuch = howMuch - cval;                                    
          };           
          self.$clip.scrollLeft(howMuch);                 
        }
        else
        { self.$clip[0].scrollLeft += (self.o.speed  + (theM/400)); };                
            
    }, thisMovementInterval);    
	},    
  
	moveRightToLeft: function(theM) {
		var self = this;
		//this.movement = 'back';
    this.movement = 'forward';
		if (this.trigger !== null) {
			this.$btnForward.removeClass('disabled');
		}
        var thisMovementInterval  = (thisIsIE == true ? 3 : 6);      
        self.mouseMoveInterval = setInterval(function() {        
        //self.$clip[0].scrollLeft -= ((self.o.speed/2)  + (theM/400));                
        // the cloning        
        isToInfinit = true;
        if (isToInfinit ==  true)
        {   theLastC  = self.$list.children("li:last");
            theFirstC = self.$list.children("li:first");
            howMuch   = (self.$clip.scrollLeft()  - parseInt(self.o.speed  + ((theM/(thisIsIE == true ? 200 : 200)) + (thisIsIE == true ? 1 : 0))));
            thisLeft    = theFirstC.offset().left;                   
            if(thisLeft === 0)
            { theFirstC.before(theLastC);               
              cval      = theFirstC.outerWidth();           
              if (cval  < 200)  { cval  = 237;  };
              howMuch = howMuch + cval;
            };
              self.$clip.scrollLeft(howMuch);                                                      
        } else
        { self.$clip[0].scrollLeft -= ((self.o.speed/2)  + (theM/400));  };
                                                                    
        },thisMovementInterval);
	},
    
  doTheMouseMove: function(e) {
          var self = this;
          //clearInterval(this.interval);
          clearInterval(self.mouseMoveInterval);
          infinityfixonlyonce = false;
          var pageCoordsX     = e.pageX;      
          var clientCoordsX   = e.clientX;          
          var pageWidth       = $(window).width();
          var pageMiddle      = parseInt(pageWidth / 2);      
          var pageLeft        = pageMiddle  - 50;
          var pageRight       = pageMiddle  + 50;                             
          if (pageCoordsX < pageLeft) {  scrollXpos  = pageLeft  - pageCoordsX;  self.moveRightToLeft(scrollXpos);  };
          if (pageCoordsX > pageRight) { scrollXpos = pageCoordsX  - pageRight; self.moveLeftToRight(scrollXpos); };    
  },
	mouseMove: function() {
        var self = this;
        //self.moveStop();
        clearInterval(this.interval); clearInterval(self.mouseMoveInterval);                
        self.$clip.bind('mouseover', function(e) { self.doTheMouseMove(e);  });           
	}    
});
		  
})(jQuery);