Number.prototype.round = (function(dec) {
	dec = dec || 0;
	var n = '' +this;
	for(var c=1,l=dec, dec=1;c<=l;c++)
		dec*=10;
		
	if(n.match('.'))
		n = Math.round(n*dec)/dec;
	return n*1;
});
	
(function($) {
	var has_vml = false;
	var canvas;
	var image = { 'width'  : null, 'height' : null };
	
	if( window.ActiveXObject && !has_vml ) {
		document.namespaces.add("v","urn:schemas-microsoft-com:vml");
		vs = document.createElement('style');
		vs.setAttribute('type', 'text/css');
		vs.styleSheet.cssText = ' v\\:* { behavior: url(#default#VML); display:inline-block}';
		document.getElementsByTagName('head')[0].appendChild(vs)
	
		has_vml = true;
		canvas = document.createElement('div');
		canvas.setAttribute( 'class', 'canvas' );
	}
	else {
		canvas = document.createElement('canvas');
		var ctx = canvas.getContext('2d');
	}
	
	$.fn.canvas = function( options ) {
		var area = [];
		
		$.fn.canvas.defaults = {
			'fillColor'	: '#F00',
			'advertColor' : '#68B4EC',
			'persistentColor' : '#33dd22',
			'opacity'	: 30
		};
	
		var opts = $.extend( {}, $.fn.canvas.defaults, options );
		var pImg = null;
		
		hilight = function( area, isAdvert, isPersistent ) {
			isPersistent = isPersistent || false;
			var s = area.splice( 0, 2 ); // start point

			if( canvas &&  canvas.getContext ) {						// firefox
				var ctx = canvas.getContext('2d');
				
				ctx.beginPath();
				ctx.moveTo( s[0], s[1] );
				var color = getRgba( isPersistent ? opts.persistentColor : ( !isAdvert ? opts.fillColor : opts.advertColor ), opts.opacity );
				ctx.clearRect( 0, 0, canvas.width, canvas.height );
				
				ctx.fillStyle = 'rgba('+ color +')';
				do {
					p = area.splice( 0, 2 );
					ctx.lineTo( p[0], p[1] );
				}
				while( area.length );
				ctx.fill();
				if( isPersistent ) {
					pImg = new Image();
					pImg.className = 'imgPersist';
					
					$(pImg).load( function() {
						if( ( i = $this.parent().find('img[class=imgPersist]') ).length )
							$(i).remove();
							
						$(this).insertBefore( $this.prev() );
					});
					pImg.src = canvas.toDataURL();	// create image from area
				}
			}
			else {															// IE
				var path;
				path = 'm '+ s[0] +',' +s[1] +' l ';
				do {
					p = area.splice( 0, 2 );
					path += p[0] +',' +p[1] +',';
				}
				while( area.length );
				
				path.substr( 0, path.length-1 );	// remove leading ','
				path += 'x e';
				
				shape = document.createElement('v:shape');
				shape.style.cssText = 'position:absolute;width:100%;height:100%;filter:alpha(opacity=' +opts.opacity +')';
				shape.fillcolor = ( isPersistent ? opts.persistentColor : ( !isAdvert ? opts.fillColor : opts.advertColor ) );
				
				shape.path = path;
				shape.coordsize = image.width +',' +image.height;
				
				if( isPersistent ) {
					pImg =  shape;//cloneNode( false );

					if( node = canvas.firstChild ) {
						do {
							node.parentNode.removeChild( node );
						}
						while( node = node.nextSibling );
					}	
				}
				canvas.appendChild( shape );
			}
		}
		clear = function() {
			if( canvas &&  canvas.getContext ) {				// Firefox, Safari, Chrome. etc
				var ctx = canvas.getContext('2d');
				ctx.clearRect( 0, 0, image.width, image.height );
			}
			else {																// MSIE
				if( node = canvas.firstChild ) {
					do {
						if( node != pImg )
							canvas.removeChild( node );
					}
					while( node = node.nextSibling )
				}
			}
			$('#dvPopup').hide().find('span').html('');
		}
		
		$.fn.canvas.hl_area = function( index, isPersistent ) {
			if( typeof  area[index]  !== 'undefined' )
				hilight( area[index].split(','), null, isPersistent );
		}
		$.fn.canvas.clear_area = function() {
			clear();
		}
		
		return this.each( function() {
			pImg = null;
			if( $(this).find('usemap') ) {
				$this = $(this);
				data = $(this).metadata();
				var ratio = [];
				img_w = $(this).width();
				img_h = $(this).height();
				
				ratio_x = img_w / data.width;
				ratio_y = img_h / data.height;
				ratio[0] = ratio_x.round(3);
				ratio[1] = ratio_y.round(3);
			
				$this = $(this);
				image.width = $this.width();
				image.height = $this.height();

				canvas.width = img_w;
				canvas.height = img_h;
				canvas.style.cssText = 'display: inline-block;position:absolute;height:100%;width:100%;';
				$this[0].style.cssText = 'z-index: 100;opacity:0.0;filter:alpha(opacity=0)';
				
				var img = new Image();
				$(img).load( function() {
					this.style.width = '100%';
					var popup = $('<div id=\'dvPopup\'><span class=\'spHeader\' /><span class=\'spContent\' /></div>' );
					popup[0].cssText = 'display: inline-block;position: fixed;';
				
					if( ( d = $('div.cvImage') ).length ) {
						$(d).css('width', img_w +'px' );
						$(d).find('img:first').replaceWith($(this));
					}
					else {
						d = $('<div class=\'cvImage\' style=\'position: absolute;display: inline-block;width: '+ img_w +'px;height: 100%;overflow: hidden;\' \/>').html( $(this) ).append( canvas );
						$(d).insertBefore( $this );
						$(d).append( $this ).append( $('map[name=' +$this.attr('usemap').substr(1) +']') );
						$(d).append( popup );
					}
					$(d).parent().find('img[class=imgPersist]').remove();
				}).error( function() {
					return;
				});
				
				img.src = $this[0].getAttribute('src');
				
				var map = $this[0].getAttribute('usemap').substr(1);
				$('map[name='+map+'] area').each( function() {
					coords = $(this)[0].getAttribute('coords');
					
					$(this).attr('coords', recalc_coords(coords, ratio));
					area.push( coords );
				});
				
				$('map[name='+map+'] area').die();
				$('map[name='+map+'] area').live( 'mouseover', function(evt) {			//mouseover
					var area = $(this).attr('coords');
					m = $(this).metadata();
					isAdvert = m.type == 'advertentie';
					
					area = area.split(',');
					for( var a in area )
						area[a] = area[a] *1;
					
					hilight( area, isAdvert );
					
					var art;
					art = $(this).parent().find('area').index($(this)) +1;
					art = ep.getArticle( art, null, true );

					if( dvp = $('#dvPopup') ) {
						dvp.find('span:eq(0)').html( '&nbsp;' +art.title +'&nbsp' );
						dvp.find('span:eq(1)').html( art.short );
						dvp.show();
					}
					
				}, false).live('mouseout', function(evt) {												// mouseout
					clear();
				}).live( 'mousemove', function( evt ) {													// mousemove
					var popup = $('#dvPopup');
					popup.css('top', evt.clientY + 15 +'px');
					popup.css('left', evt.clientX + 15 +'px');
				}, false).live('click', function(evt) {
					var index = $(this).parent().find('area').index($(this)) +1;
					showArticle( index, null, null, null, true );
					$().canvas.hl_area( index-1, true );
				}, false );
			}
			clear();
		});
		
		return this;
	}
	
	function getRgba( color, opacity ) {
		var colors = { 'r' : 0, 'g' : 0 , 'b' : 0 };
		if( typeof color === 'string' ) {
			color = color.replace('#', '' );
			if( color.length == 3 ) {
				colors.r = parseInt( color[0] +color[0], 16 );
				colors.g = parseInt( color[1] +color[1], 16 );
				colors.b = parseInt( color[2] +color[2], 16 );
			}
			else if( color.length == 6 ) {
				colors.r = parseInt( color.substr( 0, 2 ), 16 );
				colors.g = parseInt( color.substr( 2, 2 ), 16 );
				colors.b = parseInt( color.substr( 4, 2 ), 16 );
			}
			var c = colors.r +',' +colors.g +',' +colors.b;
			if( opacity )
				c += ',' + (Math.floor( opacity ) >= 10 ? opacity / 100: opacity );
			return c;
		}
		return colors;
	}
	
	function recalc_coords(coords, ratio) {
		var c='';
		if(typeof(coords) === 'string')
			coords = coords.split(',');
		if( coords.length < 3 )
			return c;
		for( var i=0, l=coords.length; i<l; i++ ) {
			x = coords[i];
			if( !(i%2) ) {
				if( x< 0 )
					x=0;
				else
					x = x>data.width?data.width:x;
			}
			
			x = x * ratio[i%2];
			c += x.round() +(i<l-1?',':'');
		}
		this.coords = c;
		return c;
	}
})(jQuery);
