$(function() {
	/**
	 * idx:
	 * index of photo that is currently hold
	 * idxLarge:
	 * index of photo that is currently on full mode
	 * mouseup:
	 * flag to use on the mouseup and mousedown events,
	 * to help preventing the browser default selection of elements
	 */
	var idx,idxLarge	= -1;
	var mouseup 		= false;
	var shuffled = true;
	
	/**
	 * the photos and options container
	 */
	var $container 		= $('#pd_container');
	
	var freeSpace = $(window).height() - $('#content').height() - 100;
	$container.height(freeSpace);
	
	var photosSize 		= $container.find('.pd_photo').length;
	
	/**
	 * spreads the photos on the table..
	 */
	var ie = false;
	if ($.browser.msie) {
		ie = true;
	}
	
	start();
	
	// $('#sort_facebook').hover(function() { sortclass("facebook"); }, function() { start(); });
	$('#sort_picasa').hover(function() { sortclass("picasa"); }, function() { start(); });
  	$('#sort_twitter').hover(function() { sortclass("twitter"); }, function() { start(); });
  	$('#sort_gplus').hover(function() { sortclass("gplus"); }, function() { start(); });
  	$('#sort_shuffle').mouseover(function() { start(); });
  	
  	function sortclass(classname){
		$(document).stop(true,true);
		start();
		$(document).find('.pd_photo').show().animate({'left': '-1000px'},3000);
		var top = 45;
		var left = 10;
		$(document).find('.'+classname).each(function(i){
			var $item 	= $(this);
			
			if (left + $(this).width() >= $('body').width()) {
				top += $(this).height() + 10;
				left = 10;	
			}
			
			
			if(ie){
			var param = {
				'top' 		: top +'px',       
				'left'		: left +'px'
				};
			}
			else {
				var param	= {
					'top' 		: top +'px',       
					'left'		: left +'px',
					'rotate' : '0deg'
				};
			}
			$item.stop(true,true).animate(param,1000);
			left += $(this).width() + 10;
			$(this).css('z-index',top);
		});	
		
		
		shuffled = false;
	}
  	
	
	function start(){
		shuffled = true;
		$(document).find('.pd_photo').show();
		
		var horizontalMax 	= $container.width() - 300;
		var verticalMax 	= $container.height() - 200;


		/**
		* display all the photos on the desk, with a random rotation,
		 * and also make them draggable.
		 * on mouse down, we want the photo to enlarge in a few pixels,
		 * and to rotate 0 degrees
		 */
		var cntPhotos = 0;
		$container.find('.pd_photo').each(function(i){
			
			var $photo 	= $(this);
			++cntPhotos;
		
			var r		= Math.floor(Math.random()*100)-30;
			var left	= Math.floor(Math.random()*horizontalMax);
			var top		= Math.floor(Math.random()*verticalMax);
			var maxzidx = parseInt(findHighestZIndex()) + 1;
			
			var param	= {
				'top' 		: top +'px',       
				'left'		: left +'px',
				'z-index'	: maxzidx
			};
			
			if(ie){ $photo.stop(true,true).css(param); }
			if(!ie){ $photo.stop(true,true).animate(param); }
			if(!ie){ $photo.transform({'rotate'	: r + 'deg'}); }
				
			$photo.show();	
			if(cntPhotos == photosSize){
				bindEvents();
			}
			
		});	
	}
	
	/**
	 * grab a photo
	 */
	function mouseDown($photo){
			mouseup 	= true;
			idx			= $photo.index() + 1;
			var maxzidx = parseInt(findHighestZIndex()) + 1;
			$photo.css('z-index',maxzidx);
			if(ie)
			var param = {
			};
			else
			var param = {
				'rotate'	: '0deg',
				'shadow'	: '5px 5px 15px #222'
			};
			$photo.stop(true,true).animate(param,100);
	}
	
	
	/**
	 * we do the mouseup on the document to prevent the
	 * case when we release the mouse outside of a photo.
	 * also, we want the photo to get smaller again,
	 * rotate some random degrees, and also move it some pixels
	 */
	$(document).bind('mouseup',function(e){
		if(mouseup){
			mouseup 	= false;
			var $photo 	= $container.find('.pd_photo:nth-child('+idx+')');
			var r		= Math.floor(Math.random()*101)-50;
			var $photoT	= parseFloat($photo.css('top'),10);
			var $photoL	= parseFloat($photo.css('left'),10);
			var newTop	= $photoT + r;
			var newLeft	= $photoL + r;
			if(ie)
			var param = {
				'top'		: newTop + 'px', 
				'left'		: newLeft + 'px'
			};
			else
			var param = {
				'top'		: newTop + 'px',
				'left'		: newLeft + 'px',
				'rotate'	: r+'deg',
				'shadow'	: '0 0 5px #000'
			};
			$photo.stop(true,true).animate(param,200);
			var maxzidx = parseInt(findHighestZIndex()) + 1;
			$photo.css('z-index',maxzidx);
		}
		e.preventDefault();
	});
	
	
	$(window).resize(function() {
		$container.width($('body').width());
		$container.height($(window).height() - $('#content').height() - 100);
	});

	var isDown = false;   // Tracks status of mouse button

	  $(document).mousedown(function() {
	    isDown = true;      // When mouse goes down, set isDown to true
	  })
	  .mouseup(function() {
	    isDown = false;    // When mouse goes up, set isDown to false
	  });

	
	function bindEvents(){
		$container.find('.pd_photo').each(function(i){
			var $photo = $(this);
			
			$photo.draggable({
				containment	: '#pd_container'
			})
			
		}).bind('mousedown',function(e){
			mouseDown($(this));
			e.preventDefault();
		});
		
	}
	
	function findHighestZIndex(){
		var photos = $container.find('.pd_photo');
		var highest = 0;
		photos.each(function(){
			var $photo = $(this);
			var zindex = $photo.css('z-index');
			if (parseInt(zindex) > highest) {
				highest = zindex;
			}
		});
		return highest;
	}
	
	function findElementHighestZIndex(){
		var photos = $container.find('.pd_photo');
		var highest = 0;
		var $elem;
		photos.each(function(){
			var $photo = $(this);
			var zindex = $photo.css('z-index');
			if (parseInt(zindex) > highest) {
				highest = zindex;
				$elem	= $photo;
			}
		});
		return $elem;
	}
	
	// Array Remove - By John Resig (MIT Licensed)
	Array.prototype.remove = function(from, to) {
		var rest = this.slice((to || from) + 1 || this.length);
		this.length = from < 0 ? this.length + from : from;
		return this.push.apply(this, rest);
	};
});
