/*
Leonardo Service Provider S.p.A.
Tutti i diritti registrati e riservati,(R)(C) 2009.
La riproduzione parziale o totale del presente software
delle pagine generate nonchè della strutturazione dei dati,
delle tabelle e di quant'altro è ad esso inerente  è illegale 
ed è punibile secondo tutte le Leggi vigenti sulla violazione del Diritto D'Autore.
L'utilizzo del presente software senza regolare licenza d'uso
è illegale e sarà perseguito secondo tutte le Leggi vigenti applicabili
*/

(function($){
	$.fn.zDrag = function(options){
		var opt = options;
		var defaults = {handler: this}; var options = $.extend(defaults, opt);
		var z = 0;
		$(this).each(function(){			
			var handler = typeof(options.handler) == 'string' ? $(this).find(options.handler) : $(this)			
		 	var self = $(this);
			self.addClass('zDrag');			
			self.css('z-index', isNaN($(highestDObj()).css('z-index')) ? 0 : parseInt($(highestDObj()).css('z-index'))+1);			
			var startDrag = function(e){
				var selfZ = self.css('z-index')
				var dObj = highestDObj(); self.css('z-index', dObj.css('z-index')+1);				
				$('.zDrag').each(function(i){
					if($(this).css('z-index') > selfZ)$(this).css('z-index',$(this).css('z-index')-1)
				})				
				self.mouseX = e.clientX;
				self.mouseY = e.clientY;	 
				$(document).mousemove(drag);
				$(document).mouseup(stopDrag);				
			} 
			var drag = function(e){
				var x = parseInt($(self).offset().left);
				var y = parseInt($(self).offset().top);
				if (0 < e.clientX && e.clientX < $(document).width()) {
					$(self).css('left', x + (e.clientX - self.mouseX) + 'px');
				}
				if (0 < e.clientY && e.clientY < $(document).height()) {
					$(self).css('top', y + (e.clientY - self.mouseY) + 'px');
				}
				self.mouseX = e.clientX;
				self.mouseY = e.clientY;
			}
		 	var stopDrag = function(){
				$(document).unbind('mousemove');
				$(document).unbind('mouseup');
			}					
			handler.mousedown(startDrag);
		});
	}
	function highestDObj(){
		var rObj = $('.zDrag:eq(0)');
		$('.zDrag').each(function(){
			if(parseInt($(this).css('z-index')) > parseInt($(rObj).css('z-index'))) {
				rObj = $(this)
			}
		});
		return rObj;
	}
})($)