/**
 * Image Flipper - An div that contains a group of images that flip through on an event
 *   http://url-to-plugin.com/
 *
 * Copyright (c) 2009 Zero Hour Collective (http://zhc.com.au)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Built on top of the jQuery library (1.3.2)
 *   http://jquery.com
 *
 */
(function($) {

	// plugin definition
	$.fn.imageFlipper = function(options) {
  	return this.each(function() {
        new $imgF(this, options);
    });
	};

	// defaults
	var defaults = {
      imageArray 	: [],
			speed				: 200
  };
	
	// imageFlipper object
	$.imageFlipper = function(e, o) {
		this.options = $.extend({}, defaults, o || {});
		this.el = e;
		this.setup();
	};
	
	// create shortcut for internal use
  var $imgF = $.imageFlipper;
  $imgF.fn = $imgF.prototype = { imageFlipper: '0.1' };
  $imgF.fn.extend = $imgF.extend = $.extend;

  $imgF.fn.extend({
		/*
			setup description
		*/
		setup : function(e) {
			
			//if (this.options.imageArray.length > 1) {
				this.inCycle = false;
				this.loaded  = false;
				// hack
				this.defaultNav = this.findDefaultNav();
				this.preload();
			//}
    },
		/*
			findDefaultNav description
		*/
		findDefaultNav : function() {
			return $('.nav-home');
			/*
			// below code would make this script reusable on all pages of a website...
			// since we only use imageFlipper on the home page we can just assume the above :)
			
			var bc = $(document.body).attr('class');
			if (bc.indexOf('page-') >= 0) {
				
				var pos = bc.indexOf(" ");
				var found = false;
				while(pos > -1) {
						if (pos > bc.indexOf('page-') && !found) {
							found = $('.nav-'+bc.substring(bc.indexOf('page-')+5,pos));
						}
						pos = bc.indexOf(" ", pos+1);
				}
				
				return found;
			}
			*/
		},
		/*
			preload description
		*/
		preload : function(load_item) {
			this.loadedImages = 0;
			this.loadNextImage(this.loadedImages + 1);
		},
		/*
			loadNextImage description
		*/
		loadNextImage : function(num) {
			
			var self = this;
			var img = new Image();
			
			$(img).load(function () {
				$(this).hide();
				if(self.options.imageArray[num-1].link) {
					$(self.el).append($("<a href='"+self.options.imageArray[num-1].link+"'></a>").append(this));
					self.hasLink = true;
				} else {
					$(self.el).append(this);
				}
				
				if(self.options.imageArray[num-1].relItem) {
					self.hasRelItem = true;
					self.relItem = self.options.imageArray[num-1].relItem;
				}
				
				
				
				if(num == self.options.imageArray.length) {
					self.loaded = true;
					self.displayInitialState();
					self.enableEvents();
				} else {
					self.loadNextImage(num+1);
				}
		  })
			.error(function () {
		      // error
					//console.log('there was an error');
		  })
			.attr({ src: self.options.imageArray[num-1].src, className: 'grid-img' });
			//.attr({ src: self.options.imageArray[num-1].src, className: 'grid-img', style: 'top: '+num*8+'px; left: '+num*8+'px;' });
		},
		/*
			displayInitialState description
		*/
		displayInitialState : function() {
			
			var self = this;	
						
			// first loop removes any default SEO'ish images that are part of the source code
			jQuery.each($(this.el).children(), function(i) {
				if (i == 0) {
					$(this).remove();
				}
			});
			// second loop display's the first image in the stack
			jQuery.each($(this.el).find('img'), function(i) {
				if (i == 0)
					$(this).fadeIn();
			});
		},
		/*
			enableEvents description
		*/
		enableEvents : function() {
			var self = this;
			
			$(this.el).mouseenter(function(){
				if (self.hasLink) {
					$(self.el).addClass('hover');
				}
				if (self.hasRelItem) {
					$(self.defaultNav).addClass('non-active');
					$(self.relItem).addClass('active');
				}
				self.options.flipType = 1;
				self.startCycle();
			});
			$(this.el).mouseleave(function(){
				if (self.hasRelItem) {
					$(self.defaultNav).removeClass('non-active');
					$(self.relItem).removeClass('active');
				}
				// self.stopCycle();
				self.options.flipType = 3;
				self.reCycle();
			});
		},
		/*
			startCycle description
		*/
		startCycle : function() {
			
			this.inCycle = true;
			
			var self = this;
			
			this.currImages = $(this.el).find('img');
			this.currImage  = $(this.el).find('img:visible')[0];
			this.currIndex = 0;
			
			if (self.options.flipType == 3) {
				this.totalRotations = 0;
				this.rand = Math.floor(Math.random()*(self.options.imageArray.length * 2)) + 1;
			}
			$(this.el).everyTime( self.options.speed, function() {
		    self.cycleImage();
		  });
		},
		/*
			reCycle description
		*/
		reCycle : function() {
			
			this.inCycle = true;
			
			var self = this;
			
			this.currImages = $(this.el).find('img');
			this.currImage  = $(this.el).find('img:visible')[0];
			this.currIndex = this.currImages.length -1;
			
			if (self.options.flipType == 3) {
				this.totalRotations = 0;
				this.rand = Math.floor(Math.random()*(self.options.imageArray.length * 2)) + 1;
			}
			$(this.el).everyTime( self.options.speed, function() {
		    self.cycleImage();
		  });
		},

		/*
			stopCycle description
		*/
		stopCycle : function() {
			$(this.el).stopTime();
		},
		/*
			startCycle description
		*/
		cycleImage : function(el) {

			switch(this.options.flipType) {
				// flip through images to last index
				case 1:
				  if (this.currIndex < (this.currImages.length - 1)) {
						var nextImage = this.currImages[this.currIndex + 1];
						$(this.currImage).hide();
						$(nextImage).show();
						this.currImage = nextImage;
						this.currIndex = this.currIndex + 1;
					}
				break;
				// flip through images to previous index
				case 9:
				  if (this.currIndex > 0) {
						var nextImage = this.currImages[this.currIndex - 1];
						$(this.currImage).hide();
						$(nextImage).show();
						this.currImage = nextImage;
						this.currIndex = this.currIndex - 1;
					}
				break;
				// endlessly flip through images
				case 2:
					var nextIndex = (this.currIndex < this.currImages.length - 1) ? this.currIndex + 1 : 0 ;				  
					var nextImage = this.currImages[nextIndex];
					$(this.currImage).hide();
					$(nextImage).show();
					this.currImage = nextImage;
					this.currIndex = nextIndex;
				break;
				// flip through images until random numb is hit
				case 3:
					if (this.totalRotations != this.rand) {
						var nextIndex = (this.currIndex < this.currImages.length - 1) ? this.currIndex + 1 : 0 ;				  
						var nextImage = this.currImages[nextIndex];
						$(this.currImage).hide();
						$(nextImage).show();
						this.currImage = nextImage;
						this.currIndex = nextIndex;
						this.totalRotations++;
					} else {
						return false
					}
				break;
				default:
				  
			}
		}
		
	});
	
	$imgF.extend({ 
		defaults: function(d) { return $.extend(defaults, d || {}); }
	});
	
})(jQuery);
