(function($){
	$.fn.mozyYak = function(options) {
    
    	var defaults = {
			galdirectory: null,	//if not specified, pulls from body class
   			randomizer: null,
			waitTime: 5000
  		};
  
  		var options = $.extend(defaults, options);
    
  		return this.each(function() {
  			
			obj = $(this);
			obj.after('<div id="mozyYakBuffer" style="display:none;"></div>');
			var beginning="true";
			

			if(!options.galdirectory) {
				options.galdirectory = obj.parents('body').attr('class');
			}
			
			function hitTheSwitch(){
				$.get("wp-content/themes/EBS/includes/gallery.php5",
						{ directory: options.galdirectory,
						  randomize: options.randomizer }, 
				  		function(data){
					 		$('#mozyYakBuffer').html(data);
							timer = setTimeout(afterAjax,options.waitTime);
					}
				);
			}
			
			//timer = setTimeout(hitTheSwitch,options.waitTime);
			// -- moved stall to after ajax images loaded
			hitTheSwitch();
			
			function fisherYates ( myArray ) {
			  var i = myArray.length;
			  if ( i == 0 ) return false;
			  while ( --i ) {
			     var j = Math.floor( Math.random() * ( i + 1 ) );
			     var tempi = myArray[i];
			     var tempj = myArray[j];
			     myArray[i] = tempj;
			     myArray[j] = tempi;
			   }
			}
			
			function indexBufferImgs(){
				bufferArray = [];
				var bufferCount = ($('#mozyYakBuffer').children().size());
				for (var i=0; i < bufferCount; i++) {
					bufferArray.push($('#mozyYakBuffer img').eq(i).attr('src'));
				}
				fisherYates(bufferArray);
				
			}
			
			
			function afterAjax() {
				
				var imageCount = obj.children().size();			
				var indexArray = [];
				indexBufferImgs();
								
				for (var i=0; i < imageCount; i++) {
					indexArray.push(i);
				}
				fisherYates(indexArray);
				
				
				
				function animateFader(x) {
					if ($.browser.msie && ($.browser.version < 7)) {
						$('#gallery img').eq(x).attr('src',bufferArray[x]);						
						flutterIndex++;
						flutter();
					} else {
						$('#gallery img').eq(x).fadeTo(100, 0.0, function() { 
						  	$('#gallery img').eq(x).attr('src',bufferArray[x]);
							$('#gallery img').eq(x).fadeTo(100, 1.0);
							flutterIndex++;
							flutter();
						});
					}					
				}
				
				var flutterIndex = 0;
				function flutter(){
					if (flutterIndex < imageCount) {
						//alert(flutterIndex);
						var y = indexArray[flutterIndex];
						animateFader(y);									
					} 
				}
				flutter();
				timer = setTimeout(afterAjax,options.waitTime);
			}
			
			
			
			
			
			

			

			//start timer(5sec.) (before animation)

			//animate image transition
				//initualize array with values 1-9
				//randomize the array
				//start image animation from for each image in array (make sure each stops)

			//remove first image and start over
   
		});
	};
})(jQuery);
