/////////////////////////////////
// jQuery Mosaic Gallery V1.0 ///
/////////////////////////////////
//
// DETAILS: 		HTTP://WWW.JQUERYMOSAICGALLERY.COM
// AUTHOR:			STEPHEN CUNNINGHAM
// TYPICAL USE: 	$("#your_div").picnmix();
// COPYRIGHT: 		(C) 2010 Steve Cunningham sjacunningham@gmail.com
// 					Licensed under the MIT License:
// 					http://www.opensource.org/licenses/mit-license.php
// 
// HAVE FUN!

(function($){
		  
$.fn.mosaic = function(options) {

//////////////////////////////////////////////////
//INITIALISE

//SET DEFAULTS
	var defaults = {
		autoPopulate: true,
		rotationEffect: 'fade',
		rotationSpeed: 1000,
		pulse: false,
		popup: false
	};
//MERGE USER DEFINED AND DEFAULT OPTIONS
	var options = $.extend(defaults, options);
	
	
return this.each(function() {
	//Constrain function scope
	var obj = this;

	//Hide the photos
	$(".mosaic_img, ul", obj).hide();
	$("#nojavascript", obj).hide();
	//Override css - gracefull degregation failsafe incase javascript is not enabled
	$(obj).css("overflow","hidden");
	$(".mosaic_box", obj).css("display","block");
	var interval = '';

//////////////////////////////////////////////////
//AUTOPOPULATE
	//Populate each of the mosaic boxs with a picture
	if (options.autoPopulate) {
		$('.mosaic_box', obj).each(function(){
		
			$(".mosaic_list  .mosaic_img", obj).random(1).appendTo(this).show();
			
			var box_h = parseInt($(this).css('height'));
			var box_w = parseInt($(this).css('width'));
			var img = $(this).find('img');
				var img_w = img.attr('width');
				var img_h = img.attr('height');
			
				if ((img_w / box_w) > (img_h / box_h)){ //Aspect is landscape

						var ratio =  box_h  / img_h; // Get ratio for scaling image
						img.css("height",  box_h ); // Set new height
						img.css("width",  (Math.round(img_w * ratio))); // Scale width based on ratio

					}else{//aspect is portrate
					
						var ratio =  box_w  / img_w; // Get ratio for scaling image
						img.css("width", box_w); // Set new height
						img.css("height", (Math.round(img_h * ratio))); // Scale width based on ratio
					
					}
	
				img_w = img_w * ratio;  // Reset width to match scaled image
				img_h = img_h * ratio; // Reset height to match scaled image
			
				//Center image in box
				img_css = {
					left: (Math.round((box_w - img_w)/2)) + 'px',
					top: (Math.round((box_h - img_h)/2)) + 'px'
				};
				img.css(img_css);  

		});//End mosaic each function
		
		//$('ul li:empty').remove();//Remove the empty list items from the pic list
	
	}//End if autopopulate
	
//////////////////////////////////////////////////
//FADE
	//Start auto rotate
	if(options.rotationEffect == 'fade') {

		$.fn.mosaic.fade_in_out = function () {	
		
		//Select random box but not the last one and not one that is hovered over
		var mosaic_box = $('.mosaic_box:not(.mosaic_last_box):not(.mosaic_hover)', obj).random(1);
		$('.mosaic_box').removeClass('mosaic_last_box');
		mosaic_box.addClass('mosaic_last_box');
		
		//Swap its child image with a new one but not the last one	
		clear_old_img_css = {
					left: '0px',
					top: '0px',
					margin: '0px',
					height: 'auto',
					width: 'auto',
					display: 'none'
			};
		$('.mosaic_list li:empty', obj).random(1).html(mosaic_box.find('img').addClass('mosaic_last_img').css(clear_old_img_css));
		
		$('.mosaic_list .mosaic_img:not(.mosaic_last_img)', obj).random(1).appendTo(mosaic_box).fadeIn('slow');		
		$('.mosaic_list .mosaic_img', obj).removeClass('mosaic_last_img');
			
			var box_h = parseInt(mosaic_box.css('height'));
			var box_w = parseInt(mosaic_box.css('width'));
			var img = mosaic_box.find('img');
				var img_w = img.attr('width');
				var img_h = img.attr('height');
			
				if ((img_w / box_w) > (img_h / box_h)){ //Aspect is landscape

						var ratio =  box_h  / img_h; // Get ratio for scaling image
						img.css("height",  box_h ); // Set new height
						img.css("width",  (Math.round(img_w * ratio))); // Scale width based on ratio

					}else{//aspect is portrate
					
						var ratio =  box_w  / img_w; // Get ratio for scaling image
						img.css("width", box_w); // Set new height
						img.css("height", (Math.round(img_h * ratio))); // Scale width based on ratio
					
					}
	
				img_w = img_w * ratio;  // Reset width to match scaled image
				img_h = img_h * ratio; // Reset height to match scaled image
			
				//Center image in box
				img_css = {
					left: (Math.round((box_w - img_w)/2)) + 'px',
					top: (Math.round((box_h - img_h)/2)) + 'px'
				};
				img.css(img_css);  
		
		}
		interval = setInterval('$.fn.mosaic.fade_in_out()',options.rotationSpeed);
	
	}//End if fade
	
//////////////////////////////////////////////////
//DRIFT
	//Start DRIFT
	if(options.rotationEffect == 'drift') {

		$.fn.mosaic.drift = function () {	
		
		//Select random box but not the last one and not one that is hovered over
		var mosaic_box = $('.mosaic_box:not(.mosaic_last_box):not(.mosaic_hover)', obj).random(1);
		$('.mosaic_box').removeClass('mosaic_last_box');
		mosaic_box.addClass('mosaic_last_box');
		
		//Swap its child image with a new one but not the last one	
		clear_old_img_css = {
					left: '0px',
					top: '0px',
					margin: '0px',
					height: 'auto',
					width: 'auto',
					display: 'none'
			};
		$('.mosaic_list li:empty', obj).random(1).html(mosaic_box.find('img').addClass('mosaic_last_img').css(clear_old_img_css));
		
		$('.mosaic_list .mosaic_img:not(.mosaic_last_img)', obj).random(1).appendTo(mosaic_box).fadeIn('slow');		
		$('.mosaic_list .mosaic_img', obj).removeClass('mosaic_last_img');
		
			var box_h = parseInt(mosaic_box.css('height'));
			var box_w = parseInt(mosaic_box.css('width'));
			var img = mosaic_box.find('img');
				var img_w = img.attr('width');
				var img_h = img.attr('height');
			
			if ((img_w / box_w) > (img_h / box_h)){//width is greatest
			
					var ratio =  box_h  / img_h; // get ratio for scaling image
					img.css("height",  box_h );   // Set new height
					img.css("width", img_w * ratio);    // Scale width based on ratio
				
				}else{//height is greatest
				
					var ratio =  box_w  / img_w; // get ratio for scaling image
					img.css("width",  box_w );   // Set new height
					img.css("height", img_h * ratio);    // Scale width based on ratio
				
				}
				
				img_w = img_w * ratio;  // Reset width to match scaled image
				img_h = img_h * ratio; // Reset height to match scaled image
		
			img_css = {
				left: '0px',
				top: '0px'
			};
			img.css(img_css);
			
			img.animate({
					marginLeft: '-' + (img_w - box_w) + 'px',
					marginTop: '-' + (img_h - box_h) + 'px'
				}, ((options.drift/4)*3));
		
		}
		interval = setInterval('$.fn.mosaic.drift()',options.rotationSpeed);
	
	}//end drift 


//////////////////////////////////////////////////
//PULSE POPULATE

if(options.rotationEffect == 'pulsePopulate') {

		$.fn.mosaic.pulse_populate = function () {	
		
		$('.mosaic_box:not(.mosaic_hover)').each(function(i) {
				$(this).children().delay(300*i).fadeOut(100, function() {
					
					clear_old_img_css = {
						left: '0px',
						top: '0px',
						margin: '0px',
						height: 'auto',
						width: 'auto',
						display: 'none'
					};
					
					$(this).clone().css(clear_old_img_css).appendTo($('.mosaic_list li:empty', obj).random(1));
					
					var img = $('.mosaic_list .mosaic_img', obj).random(1).appendTo($(this).parent()).fadeIn(2000);
					
					//alert(img.attr('src'));
							var box_h = parseInt($(this).parent().css('height'));
							var box_w = parseInt($(this).parent().css('width'));
							//var img = $(this).find('img');
							var img_w = img.attr('width');
							var img_h = img.attr('height');
						
							if ((img_w / box_w) > (img_h / box_h)){ //Aspect is landscape
			
									var ratio =  box_h  / img_h; // Get ratio for scaling image
									img.css("height",  box_h ); // Set new height
									img.css("width",  (Math.round(img_w * ratio))); // Scale width based on ratio
			
								}else{//aspect is portrate
								
									var ratio =  box_w  / img_w; // Get ratio for scaling image
									img.css("width", box_w); // Set new height
									img.css("height", (Math.round(img_h * ratio))); // Scale width based on ratio
								
								}
				
							img_w = img_w * ratio;  // Reset width to match scaled image
							img_h = img_h * ratio; // Reset height to match scaled image
						
							//Center image in box
							img_css = {
								left: (Math.round((box_w - img_w)/2)) + 'px',
								top: (Math.round((box_h - img_h)/2)) + 'px'
							};
							img.css(img_css);  
				
					$(this).remove();
					
					});
			});
		
		}
		setInterval('$.fn.mosaic.pulse_populate()', options.rotationSpeed);
		}//End pulse populate


//////////////////////////////////////////////////
//PULSE POPULATE
/*
if(options.pulse_populate) {

		$.fn.mosaic.pulse_populate = function () {	
		
		$('.mosaic_box:not(.mosaic_hover)').each(function(i) {
				$(this).children().delay(300*i).fadeOut(100, function() {
					$(this).fadeIn(2000); 
					});
			});
		
		}
		setInterval('$.fn.mosaic.pulse_populate()', options.pulse_populate);
		}//End pulse populate

*/
//////////////////////////////////////////////////
//PULSE
	//Start pulse
	if(options.pulse){
		
	function pulse(){
			
			clearInterval(interval);
			
			$('.mosaic_box').each(function(i) {
				$(this).children().delay(300*i).fadeOut(100, function() {
					$(this).fadeIn(2000); 
					});
			});
			
			interval = setInterval('$.fn.mosaic.fade_in_out()',options.fade);
		}
		setInterval(pulse, options.pulse);
	}//End pulse
	
// if popup is enabled
if(options.popup) {

//////////////////////////////////////////////////
//HOVER
	//Stop annimation on this box and style
		$(function() {
			   $('.mosaic_box').hover( function(){
				  $(this).css({ 'opacity' : 0.7, 'cursor' : 'pointer' })
						 .append('<img id="mosaic_plus" src="images/plus2.png">')
						 .addClass('mosaic_hover');
			   },
			   function(){
				  $(this).css({ 'opacity' : 1, 'cursor' : 'auto' })
						 .removeClass('mosaic_hover');
				  $('#mosaic_plus').remove();
			   });
		});
		
		
//////////////////////////////////////////////////
//POP UP IMAGE
$('.mosaic_box', obj).click(function (){								
								
		//Setup the modal window
		$('body').append('<div id="overlay"></div><div id="modal"><div id="modalInner"><a href="#" id="close" title="Close">Close</a><div id="mosaic_img_show"><div class="clearing"></div></div><div class="clearing"></div></div></div>');

		//Get the image
		var mosaic_img_box = $(this).find('img');
		var imgUrl = mosaic_img_box.attr("src");
		
		var img_w_zoom = mosaic_img_box.attr('width');
		
		if($.browser.msie && $.browser.version <= 6.0) {
			var windowHeight = $(document).height();
			$('#overlay').height(windowHeight);
		}
		
		$('#overlay').css('opacity', 0.5).fadeIn('fast');
		$('#modal').fadeIn('slow');
		
		//Position it in the viewport
		var scrollPos = $(window).scrollTop() + 50;		
		$('div#modal').css('top',scrollPos+'px');
		
		//Handle the clicking of close button or clicking the background
		$('div#modal a#close,div#overlay').bind('click', function() {
			$('div#modal').fadeOut('fast',function() {
				$('div#overlay').fadeOut('fast',function() {
					$(this).remove();							   
				});
				$(this).remove();							   
			});
			return false;
		});	
		
		//Add the image

		$('div#mosaic_img_show').prepend('<img src="'+imgUrl+'" alt="" class="frame" style="display: block;" id="ornament"  />');
		$('img#ornament').load(function() {
			$(this).fadeIn();								
		});
		
		var zoom_w = $("#ornament").attr('width');
		$("#modal").css("margin-left", "-" + (((zoom_w)/2)+10) + "px");
		
		return false;
});//End popup function	
}//End if popup
	
	

	});//end return this.each(function() {	
		
	};
})( jQuery );

/**
 *
 * jQuery Random plugin
 *
 * @author   Michel Belleville <michel.belleville@gmail.com>
 * @version  1.1.0
 * @requires jQuery v1.3.2 or later
 * @license  GPLv3 [http://www.gnu.org/licenses/gpl.html]
 * 
 * @description Picks element(s) at random in a selection.
 * @param integer num (optional) number of elements to pick
 * 
 * Use :
 * $('#whatever .you .like').random();
 * $('.you_can_event select .more_than_one').random(10);
 * 
 */
(function($) {
  jQuery.fn.random = function(num) {
    num = parseInt(num);
    if (num > this.length) return this.pushStack(this);
    if (! num || num < 1) num = 1;
    var to_take = new Array();
    this.each(function(i) { to_take.push(i); });
    var to_keep = new Array();
    var invert = num > (this.length / 2);
    if (invert) num = this.length - num;
    for (; num > 0; num--) {
      for (var i = parseInt(Math.random() * to_take.length); i > 0; i--)
        to_take.push(to_take.shift());
      to_keep.push(to_take.shift());
    }
    if (invert) to_keep = to_take;
    return this.filter(function(i) { return $.inArray(i, to_keep) != -1; });
  };
}) (jQuery);
