var $XMAP=(function($){
	if(!$){return;}

	var $C={
			'hasVML':document.namespaces?document.namespaces:false,
			'hasCanvas':!!document.createElement('canvas').getContext,
			'vmlElements':['shape','rect','oval','circ','fill','stroke','imagedata','group','textbox']
		}
	;

	if(!($C.hasVML||$C.hasCanvas)){return;}

	var $O={
		'datakey':'xmap'
	}

	var fader=function(element, opacity, interval) {
		if(opacity<=1){
			element.style.opacity=opacity;
			window.setTimeout(fader, 10, element, opacity + 0.1, 10);
		}
	};
	var hex_to_decimal=function(hex){return Math.max(0, Math.min(parseInt(hex, 16), 255));};

	return{
			'addShape':function(canvas, shape, coords, options, name){
				if($C.hasCanvas){
					var i, context=canvas.getContext('2d');
					context.beginPath();
					if(shape=='rect') {
						context.rect(coords[0], coords[1], coords[2] - coords[0], coords[3] - coords[1]);
					}else if(shape=='poly') {
						for(i=0; i < coords.length; i+=2) {
							context.lineTo(coords[i], coords[i+1]);
						}
					}else if(shape=='circ' || shape=='circle') {
						context.arc(coords[0], coords[1], coords[2], 0, Math.PI * 2, false);
					}
					context.closePath();
					if(options.highlight.fill){this.fillShape(context,options.highlight.fill.color,options.highlight.fill.opacity);}
					if(options.highlight.stroke){this.strokeShape(context,options.highlight.stroke.color,options.highlight.stroke.opacity,options.highlight.stroke.width);}
					if(options.fade){fader(canvas,0);}
				}else{
					name='highlighted';
					var fill='', stroke='', opacity='', e;
					if(options.highlight.fill){
						fill='<v:fill color="'+options.highlight.fill.color+'" opacity="'+(options.highlight.fill.opacity ?options.highlight.fill.opacity:1)+'" />';
					}
					if(options.highlight.stroke){
						stroke=(options.highlight.stroke ? 'strokeweight="'+options.highlight.stroke.width+'" stroked="t" strokecolor="'+options.highlight.stroke.color+'"' : 'stroked="f"');
						if(options.highlight.stroke.opacity){
							opacity='<v:stroke opacity="'+options.highlight.stroke.opacity+'"/>';
						}
					}
					if(shape=='rect'){
						e=$('<v:rect name="'+name+'" filled="t" '+stroke+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+coords[0]+'px;top:'+coords[1]+'px;width:'+(coords[2] - coords[0])+'px;height:'+(coords[3] - coords[1])+'px;"></v:rect>');
					}else if(shape=='poly'){
						e=$('<v:shape name="'+name+'" filled="t" '+stroke+' coordorigin="0,0" coordsize="'+canvas.width+','+canvas.height+'" path="m '+coords[0]+','+coords[1]+' l '+coords.join(',')+' x e" style="zoom:1;margin:0;padding:0;display:block;position:absolute;top:0px;left:0px;width:'+canvas.width+'px;height:'+canvas.height+'px;"></v:shape>');
					} else if(shape=='circ' || shape=='circle'){
						e=$('<v:oval name="'+name+'" filled="t" '+stroke+' style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+(coords[0] - coords[2])+'px;top:'+(coords[1] - coords[2])+'px;width:'+(coords[2]*2)+'px;height:'+(coords[2]*2)+'px;"></v:oval>');
					}
					e.get(0).innerHTML=fill+opacity;
					$(canvas).append(e);
				}
			},
			'clearCanvas':function(canvas,e,options){
				var td=$.data(e.target),
					group=options.group && td['htmlmap.group'].name && (options.group instanceof Array?$.inArray(td['htmlmap.group'].name,options.group)<0:true);
				if(group){
					if(e.relatedTarget && e.relatedTarget.nodeName=='AREA'){
						if($.data(e.relatedTarget,'htmlmap.group').name==td['htmlmap.group'].name){return false;}
					}
				}
				if($C.hasCanvas){
					canvas.getContext('2d').clearRect(0,0,canvas.width,canvas.height);
				}else{
					$(canvas).empty();
				}
				return true;
			},
			'config':$C,
			'createCanvas':function(width,height){
				if($C.hasCanvas){
					var c=$('<canvas style="width:'+width+'px;height:'+height+'px;"></canvas>').get(0);
					c.getContext("2d").clearRect(0,0,c.width,c.height);
				}else{
					c=$('<var style="zoom:1;overflow:hidden;display:block;width:'+Math.round(width)+'px;height:'+Math.round(height)+'px;"></var>').get(0);
				}
				c.width=width;
				c.height=height;
				return c;
			},
			'createMap':function(object,scheme,options,imageAttributes,i){
				var name=scheme.id+'_map'+(i?'_'+i:''),
					scale={'width':imageAttributes.width/options.base.width,'height':imageAttributes.height/options.base.height},
					map='<map name="'+name+'">'
				;
				object.attr('usemap','#'+name);
				$.each(scheme.canvas,function(k,v){
					$.each(v.coords,function(i,c){
						var coords=[];
						$.each(c,function(n,p){
							if(v.shape=='rect' || v.shape=='poly' || !v.shape){
								coords[coords.length]=(n%2==0)?Math.round(p*scale.width):Math.round(p*scale.height);
								return true;
							}
							coords[coords.length]=(n!=2)?((n%2==0)?Math.round(p*scale.width):Math.round(p*scale.height)):Number(p);
						});
						map+='<area coords="'+coords.join(', ')+'" shape="'+(v.shape?v.shape:'poly')+'" title="'+k+'" href="'+(v['url']?v.url:'')+'" />';
					});
				});
				map+='</map>';
				return $(map).find('area').each(function(){
					var g=false;
					var obj=$(this);
					var k=obj.attr('title');
					$.each(scheme.groups,function(i,v){
						if($.inArray(k,v.keys)>=0){g={'name':i,'url':v.url};return false;}
					});
					obj.data({'htmlmap.key':k,'htmlmap.group':g}).addClass([k,g.name].join(' '));

					if(scheme.canvas[k].overlay){
						obj.data('htmlmap.overlay',scheme.canvas[k].overlay);
					}
//$framework.log($O.datakey,k+' data: ',obj.data());
					var item=scheme.canvas[k];
					obj.attr('title',(item['title']?item.title:k));

					if(!options.overlay && options.group){
						if(options.group instanceof Array){
							if($.inArray(g.name,options.group)>=0){
								if(!obj.attr('href')){
									obj.removeAttr('href');
								}
							}else{
								if(g['url'] && g.url){
									obj.attr('href',g.url);
								}else{
									obj.removeAttr('href');
								}
							}
						}else{
							if(g['url'] && g.url){
								obj.attr('href',g.url);
							}else{
								obj.removeAttr('href');
							}
						}
					}
				}).end();
			},
			'fillShape':function(shape,color,opacity){
				if(!opacity){opacity=1;}
				shape.fillStyle='rgba('+hex_to_decimal(color.substr(1,2))+','+hex_to_decimal(color.substr(3,2))+','+hex_to_decimal(color.substr(5,2))+','+opacity+')';
				shape.fill();
			},
			'highlight':function(canvas,area,options,areaOnly){
				var $this=this;
				if(areaOnly){
					$this.addShape(canvas,area.getAttribute('shape').toLowerCase(),area.getAttribute('coords').split(','),options);
				}else{
					var data=area.data();
					area.parent().find('area.'+data['htmlmap.key']).each(function(k,c){
						$this.addShape(canvas,c.getAttribute('shape').toLowerCase(),c.getAttribute('coords').split(','),options);
					});

/*
					var data=area.data();
					var group=options.group && data['htmlmap.group'].name && (options.group instanceof Array?$.inArray(data['htmlmap.group'].name,options.group)<0:true);
					area.parent().find('area.'+(group?data['htmlmap.group'].name:data['htmlmap.key'])).each(function(k,c){
						$this.addShape(canvas,c.getAttribute('shape').toLowerCase(),c.getAttribute('coords').split(','),options);
					});
					var $so=data['htmlmap.overlay'];
					if($so){
						if($.isArray($so)){
							$.each($so,function(i,v){
								$this.addShape(canvas,(v.shape?v.shape:'poly'),v.coords,{
									'fill':{
										'color':v.color,
										'opacity':v.opacity
										}
								});
							});
						}else{
							$this.addShape(canvas,($so.shape?$so.shape:'poly'),$so.coords,{
								'fill':{
									'color':$so.color,
									'opacity':$so.opacity
									}
							});
						}
					}
*/
				}
			},
			'setDataKey':function(key){
				$O.datakey=key;
			},
			'strokeShape':function(shape,color,opacity,width){
				if(!opacity){opacity=1;}
				shape.strokeStyle='rgba('+hex_to_decimal(color.substr(1,2))+','+hex_to_decimal(color.substr(3,2))+','+hex_to_decimal(color.substr(5,2))+','+opacity+')';
				shape.lineWidth=width;
				shape.stroke();
			}
		};

})(typeof(jQuery)!=='undefined'?jQuery:null);

