/*
 * Copyright (c) 2009 Massimiliano Balestrieri
 * @requires jQuery v1.3.2
 * 
 * Copyright (c) 2009 Massimiliano Balestrieri
 * Examples and docs at: http://maxb.net/blog/
 * Licensed GPL licenses:
 * http://www.gnu.org/licenses/gpl.html
 */ 


;(function($){

function jCropMap(options){
	
	var _options = $.extend({
		imgselector : ".jcropbox",
		aselector   : "ul",
		shapes 		: false,
		shapes_opacity : 0.2
	}, options);
	
	function _check_dependencies(){
		if (!$.metadata) {
			alert("Include jQuery Metadata");
			return false;
		}	
		if (!$.Jcrop) {
			alert("Include jQuery Jcrop");
			return false;
		}
		return true;
	}
	
	if(!_check_dependencies())
		return this;
	
	return this.each(function(){
		
		var that = this;
		var _jcrop = false;
		var _startjcrop = false;
		//private
		function _one(){
			if (!$(that).is(".jcropmap-load")) {
				$(that).addClass("jcropmap-load");
				return true;
			}else{
				return false;
			}
		}
		function _get_coords(o){
			return [a[0], a[1], a[2], a[3]];	
		}
		function _links(){
			$(_options.aselector, that).find("a").each(function(){
				var _a = this;
				var _o = $(_a).metadata();
				var _coords = _o.coords;//_get_coords(_options);
				if(_options.shapes){
					
					var _text = $('<span>'+$(_a).text()+'</span>').hide();
					var _l = $('<a href="#"></a>')
					.append(_text)
					.css({
						position: "absolute",
						display : "block",
						height  : "100%",
						width   : "100%"
					})
					.bind("mouseover", function(){
						$(_a).addClass("jcropmap-hover");
					})
					.bind("mouseout", function(){
						$(_a).removeClass("jcropmap-hover");
					});
					
					$('<div class="jcropmap-shape"></div>')
					.append(_l)
					.hide()
					.css({
						 zIndex  : "10000",
						 position : "absolute",
						 top : _coords[1] + "px",
						 left: _coords[0] + "px",
						 width: _coords[4] + "px",
						 height: _coords[5] + "px",
						 opacity : _options.shapes_opacity
					})
					.appendTo(that);
				}	
				
				$(this).bind("mouseover", function(){
					if (!_startjcrop) {
						_jcrop.setSelect(_coords);
						_startjcrop = true;
					}
					else {
						_jcrop.animateTo(_coords);
					}
				});
			});
		}
		function _init_jcrop(){
			var _target = $(_options.imgselector, that);
			var _ojc = $.extend({
				allowSelect:false, 
				allowResize : false, 
				allowMove : false
			}, _options.jcrop);
			_jcrop = $.Jcrop(_target, _ojc);
		}
		function _append_shapes(){
			$(".jcropmap-shape").appendTo(".jcrop-holder", that).show();
		}
		//MAIN
		if(_one()){
			_init_jcrop();
			_links();
			if(_options.shapes)
				_append_shapes();
				//setTimeout(_append_shapes, 1);//
			
			$(that).bind("release", function(){
				_jcrop.release();
			});
				
		}else{
			return false;
		}
					
	});
};

$.fn.jcropmap = jCropMap;

})(jQuery);