/**
 * @author trixta
 */
(function($){
	
	$.widget("ui.canvasmap", {
		init: function(){
			
			var that = this;
			this.canvas = $(document.createElement('canvas'));
			this.img = $('img[usemap]:first', this.element[0]);
			var ieDiv = $('<div class="canvas"><div>').insertBefore(this.img[0]);
			ieDiv.prepend(this.canvas[0]);
			if($.browser.msie && this.canvas[0] && !this.canvas[0].getContext && typeof G_vmlCanvasManager != 'undefined'){
				 this.canvas = $(G_vmlCanvasManager.fixDynamicElement(this.canvas[0]));
			}
			if(this.canvas[0] && this.canvas[0].getContext){
				this.ctx = this.canvas[0].getContext('2d');
				this.areas = $('area', this.element[0]);
				if(!this.img[0].complete){
					this.img.bind('load.canvasmap', function(){
						that.addCanvasSize.call(that);
					});
				} else {
					this.addCanvasSize();
				}
				
				function over(e){
					var area = that.getArea(e, this);
					
					if(area){
						that.ctx.clearRect(0,0,that.cWidth,that.cHeight);
						that.drawArea.call(that, area, {
							bg: that.options.overBG, 
							borderColor: that.options.overBorderColor,
							borderWidth: that.options.overBorderWidth
						});
						that.propagate.call(that, 'over', e, {area: area});
						that.drawClickArea.call(that);
					}
					e.preventDefault();
					return false;
				}
				
				function out(e){
					that.ctx.clearRect(0,0,that.cWidth,that.cHeight);
					that.propagate.call(that, 'out', e);
					that.drawClickArea.call(that);
				}
				
				function click(e){
					that.clickArea = that.getArea(e, this);
					that.ctx.clearRect(0,0,that.cWidth,that.cHeight);
					that.drawClickArea.call(that);
					that.propagate.call(that, 'click', e, {area: that.clickArea});
					e.preventDefault();
					return false;
				}
				
				if(this.options.clickBorderWidth || this.options.clickBG){
					this.img
						.bind('click.canvasmap', click);
					this.areas
						.bind('click.canvasmap', click);
				}
				
				if(this.options.overBorderWidth || this.options.overBG){
					
				
					this.img
						.bind('mouseover.canvasmap focus.canvasmap', over)
						.bind('mouseout.canvasmap blur.canvasmap', out);
					this.areas
						.bind('focus.canvasmap mouseenter.canvasmap', over)
						.bind('blur.canvasmap mouseleave.canvasmap', out);
				}
				this.propagate('init');
			}
		},
		drawClickArea: function (){
			this.drawArea(this.clickArea, {
				bg: this.options.clickBG, 
				borderColor: this.options.clickBorderColor,
				borderWidth: this.options.clickBorderWidth
			});
		},
		getCoords: function(area){
			var coords = area.attr('coords').split(','), numCoords = [];
			for(var i = 0, len = coords.length; i < len; i++){
				numCoords[i] = parseInt($.trim(coords[i]), 10);
			}
			return numCoords;
		},
		getArea: function(e, elm){
			var area = $(e.target);
			if(!area[0] || !area.is('area')){
				area = $(elm);
				if(!area[0] || !area.is('area')){
					area = false;
				}
			}
			return area;
		},
		drawArea: function(area, options){
			if(area && area[0]){
				var shapeStyle = (area.attr('shape'))?area.attr('shape').toLowerCase():false;
				if(shapeStyle && this[shapeStyle]){
					var coords = this.getCoords(area);
					this.propagate({type: 'drawArea'}, {area: area, coords: coords, shapeStyle: shapeStyle, curOptions: options});
					this[shapeStyle](coords, options);
				}
			}
		},
		poly: function(coord, o){
				this.ctx.beginPath();
				this.ctx.moveTo(coord[0],coord[1]);
				for(var i = 2, len = coord.length; i < len; i++){
					this.ctx.lineTo(coord[i],coord[i+1]);
					i++;
				}
				this.ctx.lineTo(coord[0],coord[1]);
				if(o.bg){
					this.ctx.fillStyle = o.bg;
					this.ctx.fill();
				}
				if(o.borderWidth){
					this.ctx.strokeStyle = o.borderColor;
					this.ctx.lineWidth = o.borderWidth;
					this.ctx.stroke();
				}
		},
		plugins: {},
		ui: function(){
	        return {
	            instance: this,
	            options: this.options
	        };
	    },
		propagate: function(n, e, extraData){
			e = e ||
			 {type: n, preventDefault: true};
			var args = [e, $.extend({}, this.ui(), extraData)];
			$.ui.plugin.call(this, n, args);
	        this.element.triggerHandler(this.widgetName + n, args);
	    },
		addCanvasSize: function(){
			this.cHeight = cHeight = Math.max(this.img[0].height, this.img.height());
			this.cWidth = Math.max(this.img[0].width, this.img.width());
			this.canvas
				.attr({width: this.cWidth, height: this.cHeight})
				.css({width: this.cWidth, height: this.cHeight});
			
		}
	});
	$.ui.canvasmap.defaults = {
		overBG: 'rgba(0,185,227,0.5)',
		overBorderColor: 'rgba(255,255,255,1)',
		overBorderWidth: 1,
		clickBG: 'rgba(0,185,227,1)',
		clickBorderColor: 'rgba(255,255,255,1)',
		clickBorderWidth: 2,
		overAlpha: 1
	};
})(jQuery);
