(function($) {
	$.fn.zoomImage = function(settings){
		// Gestisce le impostazioni del plugin
		settings = jQuery.extend({
			// Se a true precarica le immagini senza attendere l'interazione dell'utente
			preloadImage: false,
			// La funzione che restituirą il codice html da inserire nel box creato
			template: function template(configs){
				alert('Codice html del template !');
			},
			// Id per prevenire eventuali conflitti
			id: 544
		}, settings);
		// Oggetto image usato per il precaricamento delle immagini
		img = new Image();
		// Elenco di immagini gią precaricate
		loadedImage = '';
		// If need preload of images
		if (settings.preloadImage) {
			_load_image($(this).find('.image-m-url').val());
		}

		// Carica le immagini
		function _load_image(image_url, onLoad) {
			if (onLoad) {
				img.onload = onLoad;
			}
			img.src = image_url;
		}

		// Genera il template da visualizzare
		function _inner_template(vars){
			// Templates of zoomPopup
			var template = '<div id="zoomImage-' + settings.id + '" style="display:block;position:absolute;' +
			'left:' +
			vars.left +
			'px;top:' +
			vars.top +
			'px;height:' +
			vars.height +
			'px;width:' +
			vars.width +
			'px">' +
			settings.template(vars) +
			'</div>';
			return template;
		}

		function _show_box(){
			_remove_box();
			var obj = $(this);
			var that = this;
			// Posizione del link
			var position = obj.position();
			// Dimensioni dell'immagine piccola
			var image_small = obj.find('img').eq(0);
			var image_small_width = image_small.width();
			var image_small_height = image_small.height();
			// Proprietą scaricate dal template
			variables = new Object();
			variables.object = obj;
			variables.image_m_url = obj.find('.image-m-url').val();
			variables.url = obj.attr('href');
			variables.top = position.top + image_small_height / 2 ;
			variables.left = position.left + image_small_width / 2;
			_load_image(variables.image_m_url, function () {
				variables.width = img.width;
				variables.height = img.height;
				variables.left -= variables.width / 2;
				variables.top -= variables.height / 2;
 				if ($('#zoomImage-' + settings.id).length == 0) {
 					$('body').append(_inner_template(variables));
 				 	obj.unbind('mouseover').unbind('mouseout');
 				 	$('#zoomImage-' + settings.id + ' img').mouseout(function (evt) {
				 		e = new Object();
 				 		e.currentTarget = that;
 				 		_remove_box(e);
 				 	});
 				}
			});
		}
		// Elimina lo zoom 
		function _remove_box(e){
			$('#zoomImage-' + settings.id).remove();
			if (e && e.currentTarget) {
				$(e.currentTarget).unbind('mouseover').unbind('mouseout').hover(_show_box, _remove_box);
			}
		}
		return this.unbind('mouseover').unbind('mouseout').hover(_show_box, _remove_box);
	}
})(jQuery);