var __set = [];
var _papers = [];

(function($) {
	var has_VML, has_svg, is_ie, ie_hacks=false, elements = {};
	
	
	isTouchDevice = function() {
		try {
			document.createEvent("TouchEvent");
			return true;
		} catch (e) {
			return false;
		}
	};
	
	is_image_loaded = function(img) {
		if(!img.complete) { return false; } // IE
		if(typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) { return false; } // Others
		return true;
	};
	
	getAreas = function($img) {
		var usemap = $img.attr('usemap').split('#')[1];
		var $map = $('map[name='+usemap+']');
		return $map.find('area');
	};
	
	
	getShapes = function($areas, papper) {
		var shapes = [];
		
		$areas.each(function(){
			var uid =  Math.floor(Math.random()*100000000000);
			
			var allAttr = $(this).getAttributes();
			allAttr.uid = uid;
			
			shapes.push(allAttr);
			var imagemap = {
				'imagemap-svg': papper,
				'uid': uid
				}
			$(this).data(imagemap);
		});
		
		return shapes;
	};
	
	
	
	buildShape = function(papper, shape, options){
		//console.log('buildShapeForFloor');
		
		var attr;
		
		if (typeof(options.buildShape) == 'function') {
			attr = options.buildShape(papper, shape);
		} else {
			attr = {
				opacity: 0.2,
				fill: "#00958e",
				'fill-opacity': '0.5',
				stroke: "#ff0000",
				"stroke-opacity": "0",
				"stroke-width": 13,
				"stroke-linejoin": "round"
			};
		}
		
		// конвертируем точки из area shape в точки для SVG path
		var _points = shape.coords.split(',');
		var newpoints = '';
		for (var i=0; i<_points.length; i+=2){
			if (i==0) {
				newpoints += 'M'+_points[i]+' '+_points[i+1];
			} else {
				newpoints += 'L'+_points[i]+' '+_points[i+1];
			}
		}
		
		// сохраняем инстанс
		elements[shape.uid] = papper.path(newpoints).attr(attr);
		
		// сохраняем в элементе значения аттрибутов текущего area из imagemap.
		$(elements[shape.uid].node).data({'areaAttrs': shape});
		
		// проставляем дополнительный аттрибут с уникальным ID элемента
		$(elements[shape.uid].node).attr('uid', shape.uid);
		
		if (!isTouchDevice()) {
			
			// MOUSE OVER
			elements[shape.uid].mouseover(function(event){
				if (typeof(options.onMouseOver) == 'function') {
					options.onMouseOver(event, elements[shape.uid]);
				} else {
					elements[shape.uid].attr('opacity', 0.8);
				}
			});
			
			// MOUSE OUT
			elements[shape.uid].mouseout(function(event){
				if (typeof(options.onMouseOut) == 'function') {
					options.onMouseOut(event, elements[shape.uid]);
				} else {
					elements[shape.uid].attr('opacity', 0.2);
				}
			});
						
			// CLICK
			$(elements[shape.uid].node).bind('click', function(event){
				if (typeof(options.onClick) == 'function') {
					options.onClick(event, elements[shape.uid]);
				} else {
					alert('triggered click event on ' + elements[shape.uid]);
					elements[shape.uid].attr('opacity', 1);
				}
			});

			// MOUSE DOWN

			$(elements[shape.uid].node).bind('mousedown', function(event){
				if (typeof(options.onMouseDown) == 'function') {
					options.onMouseDown(event, elements[shape.uid]);
				}
			});
			   
		} else {
			
			// for iPad   
			
			// Touch End         
			$(elements[shape.uid].node).bind('click ontouchend', function(event){
				if (typeof(options.onTouchEnd) == 'function') {
					options.onTouchEnd(event, elements[shape.uid]);
				} else {
					alert('triggered click event on ' + elements[shape.uid]);
					elements[shape.uid].attr('opacity', 1);
				}
			});

			// Touch Start 
			$(elements[shape.uid].node).bind('touchstart', function(event){
				if (typeof(options.onTouchStart) == 'function') {
					options.onTouchStart(event, elements[shape.uid]);
				} else {
					alert('triggered onTouchStart event on ' + elements[shape.uid]);
					elements[shape.uid].attr('opacity', 1);
				}
			});
		}
	
	};
	

	
	
	addEvents = function(area){
		var $a = $(area);
		$a.mouseover(function(){
			var uid = $(this).data('uid');
			var options = $(this).metadata();
			showShape(uid, options);
		});
		$a.mouseout(function(){
			var uid = $(this).data('uid');
			var options = $(this).metadata();
			hideShape(uid, options);
		});
	}
	
	
	$.fn.imagemap = function(opts) {
		
		var config = {
			buildShape: null,
			onMouseOver: null,
			onMouseOut: null,
			onClick: null,
			onTouchEnd: null
			};  
		
		var options = $.extend(config, opts);
		
		return this.each(function(){
			var $img, $wraper, $map, papper, $areas, shapes;
			$img = $(this);
			$areas = getAreas($img);
			
			papper = new ScaleRaphael($img.parent().get(0), $img.attr('width'), $img.attr('height'));

			shapes = getShapes($areas, papper);

			$(shapes).each(function(){
				buildShape(papper, this, options);
				//buildShape(this.coords, this.type, this.uid, papper, this.moveto, this.markerColor, this.markerType, this.tip, this.tip_title, scale, this.href);
				//addEvents(this.self);
			});
			
			
			
			var $container = $(papper.canvas).parent().parent().parent();
			$container.data({'papper': papper});
			
			console.log("$container",$container);

			//$img/*.attr('width', $container.width())*/.attr('height', $container.height()).removeAttr('useMap').removeAttr('width');

			var newImgWidth = Math.round($container.height()*$img.attr('width')/$img.attr('height'));
			var newImgHeight = Math.round($container.width()*$img.attr('height')/$img.attr('width'));

			$img.removeAttr('useMap').removeAttr('height').removeAttr('width');
			
			var imgLeft = Math.round(( $container.width() - newImgWidth) / 2);
			var imgTop = Math.round(( $container.height() - newImgHeight) / 2);

			if(newImgWidth < $container.width())
			{
				$(papper.canvas)
				.parent()
				.append(
					$img.css({
						'position': 'absolute',
						'top': 0,
						'left': 0,
						'border-top': 'none',
						'border-bottom': 'none',
						'border-left': String(imgLeft) + "px #FFF solid",
						'border-right': String(imgLeft) + "px #FFF solid",
						'width': newImgWidth,
						'height': $container.height(),
						'z-index': '-1'
					})
				);	
			} else {
				$(papper.canvas)
				.parent()
				.append(
					$img.css({
						'position': 'absolute',
						'top': 0,
						'left': 0,
						'border-top': String(imgTop) + "px #FFF solid",
						'border-bottom': String(imgTop) + "px #FFF solid",
						'border-left': 'none',
						'border-right': 'none',
						'width': $container.width(),
						'height': newImgHeight,
						'z-index': '-1'
					})
				);
			}
			
			papper.changeSize($container.width(), $container.height());
						
			$container.bind('resized', function(e, newsize){
				$(this).css({
					width: newsize.width,
					height: newsize.height
				});
				$(this).data('papper').changeSize(newsize.width, newsize.height);
			});
			
			_papers.push(papper);
			
		});
		
		
	};
})(jQuery);


(function($) {
	$.fn.getAttributes = function() {
		var attributes = {}; 

		if(!this.length)
			return this;

		$.each(this[0].attributes, function(index, attr) {
			attributes[attr.name] = attr.value;
		}); 

		return attributes;
	}
})(jQuery);
