var canvascheck = document.createElement('canvas');
var isIE = window.navigator.systemLanguage?1:0;
var isVM = document.namespaces?1:0;
var isCV = canvascheck.getContext?1:0;
var isJG = 0, jg = new Array();

/**
 * Devuelve el valor de una clase de atributo 
 * @param classes - Array que contiene los atributos definidos y su valor
 * @param string - Nombre del atributo el valor del cual queremos obtener
 * @return valor del atributo
 */
function getClassValue(classes,string){
	var temp = 0; var pos = string.length;
	for (var j=0;j<classes.length;j++) {
		if (classes[j].indexOf(string) == 0) {
			temp = Math.min(classes[j].substring(pos),100);
			break;
		}
	}
	return Math.max(0,temp);
}

/**
 * Devuelve el valor de un atributo color si este está presente, en otro caso devuelve el valor por defecto.
 * @param classes - Array que contiene los atributos definidos y su valor
 * @param string - Nombre del atributo color, los posibles valores son: 'icolor', 'iborder'. 
 * @param color - Color por defecto
 * @return valor del atributo color en formato hexadecimal (sin la '#') o rba
 */
function getClassRGBColor(classes,string,color){
	var temp, val = color, pos = string.length;
	for (var j=0;j<classes.length;j++) {
		if (classes[j].indexOf(string) == 0) {
			temp = classes[j].substring(pos);
			val = temp.toLowerCase();
			break;
		}
	}
	if(!val.match(/^[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]$/i)) {val = color||'000000'; }
	if(!isCV) {return val; }else {
		function hex2dec(hex){return(Math.max(0,Math.min(parseInt(hex,16),255)));}
		var cr=hex2dec(val.substr(0,2)),cg=hex2dec(val.substr(2,2)),cb=hex2dec(val.substr(4,2));
		return cr+','+cg+','+cb;
	}
}

/**
 * Transforma el valor de un color en formato icolorXXXXXX al formato XXXXXX (hexadecimal) o rgb (dependiendo del navegador)
 * @param val - valor del color en formato icolorXXXXXX
 * @param color - valor del color por defecto en formato XXXXXX (hexadecimal) o rgb
 * @return valor del color en formato XXXXXX (hexadecimal) o rgb
 */
function performRGBColor(val,color){
	if(!val.match(/^#[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]$/i)) {val = color||'#000000'; }
	if(!isCV) {return val.substr(1,6); }else {
		function hex2dec(hex){return(Math.max(0,Math.min(parseInt(hex,16),255)));}
		var cr=hex2dec(val.substr(1,2)),cg=hex2dec(val.substr(3,2)),cb=hex2dec(val.substr(5,2));
		return cr+','+cg+','+cb;
	}
}	

/**
 * Determina si una propiedad está presente o no, p.e: si 'noborder' está presente no se dibuja un borde.
 * @param classes - Array que contiene los atributos definidos y su valor
 * @param string - Nombre del atributo o propiedad a buscar
 * @return 1 si la propiedad NO está presente, 0 en otro caso
 */
function getClassAttribute(classes,string){
	var temp = 0; var pos = string.length;
	for (var j=0;j<classes.length;j++) {
		if (classes[j].indexOf(string) == 0) {
			temp = 1; break;
		}
	}
	return temp;
}

/**
 * Obtiene los atributos definidos y su valor.
 * @param classes - Array que contiene los nuevos atributos definidos y su valor, o su valor actualizado
 * @param attribs - Array que contiene los atributos antiguos
 * @return array con todos los atributos definidos y su valor actualizado
 */
function getAttributes(classes,attribs) {
    var u = classes.split(" ");
    attribs.op = (classes.indexOf('iopacity') != -1) ? getClassValue(u,"iopacity")/100 : attribs.op;
    attribs.bd = (classes.indexOf('iborder') != -1) ? getClassRGBColor(u,"iborder",attribs.bd) : attribs.bd;
    attribs.co = (classes.indexOf('icolor') != -1) ? getClassRGBColor(u,"icolor",attribs.co) : attribs.co;
    attribs.nb = (classes.indexOf('noborder') != -1) ? getClassAttribute(u,"noborder") : attribs.nb;
    return attribs;
}

/** 
 * Retorna las coordenadas x,y donde escribir el nombre de una ICTS en el mapa. 
 * @param object - área (provincia) del mapa donde está ubicada la ICTS
 * @param position - Si en el área hay más de una ICTS, hay que indicar en que posición respecto al área
 * se escribirá el nombre de la ICTS. Los valores posibles son: 0 - Norte, 1 - Este, 2 - Sur y 3 - Oeste.
 * @param radius - Radio del punto (círculo) a continuación del cual se escribirá el nombre
 * @return par de coordenadas x,y donde se escribirá el nombre de la ICTS
 * */
function getInfoCoordinates(object,position,radius) {
    var x = new Array(), y = new Array();
    var i = 0, j = 0;
    for(j=0;j<object.length;j+=2) {
        x[i] = parseInt(object[j]);
        y[i] = parseInt(object[j+1]); i++;
    }
    var xMax = x[0], xMin = x[0];
    var yMax = y[0], yMin = y[0];
    for (j=0;j<x.length;j++) {
        yMin = Math.min(yMin,y[j]);
        yMax = Math.max(yMax,y[j]);
        xMin = Math.min(xMin,x[j]);
        xMax = Math.max(xMax,x[j]);
    }
    var p = {x:0, y:0}
    switch(position) {
         case 0 : p.y = yMin + radius*10; p.x = xMin + ((xMax - xMin) / 2); break;   // Norte
         case 1 : p.y = yMax + radius; p.x = xMin + ((xMax - xMin) / 2); break;   // Sur
         case 2 : p.y = yMin + ((yMax - yMin) / 2); p.x = xMax + radius*4; break;   // Este
         case 3 : p.y = yMin + ((yMax - yMin) / 2); p.x = xMin - radius*4; break;   // Oeste
    }
    return p;
}

/**
 * Dibuja una área (provincia) en el mapa de España.
 * @param object - Elemento <area> del <map> que queremos dibujar en el mapa. Contiene las coordenadas de la provincia a dibujar.
 * @param image - Imagen asociada al mapa
 * @param canvas - Elemento contenedor del mapa
 * @param props - Atributos de color, borde, opacidad, etc., de la provincia a dibujar 
 * @return código VML que define el contenido a dibujar, solamente válido para el navegador IE Explorer
 */
function drawArea(object,image,canvas,props) {
    var v = object.coords.split(","), j = 0, t = '';
    if (isVM) {
        var  p= '';
        if(object.shape.toLowerCase()=='rect') {
            t += '<v:rect unselectable="on" strokeweight="1" filled="t" stroked="'+(props.nb<1?"t":"f")+'" strokecolor="#'+props.bd+'" style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+parseInt(v[0])+'px;top:'+parseInt(v[1])+'px;width:'+parseInt(v[2]-v[0])+'px;height:'+parseInt(v[3]-v[1])+'px;"><v:fill color="#'+props.co+'" opacity="'+props.op+'" /></v:rect>';
	    }else if(object.shape.toLowerCase()=='circle') {
		    t += '<v:oval unselectable="on" strokeweight="1" filled="t" stroked="'+(props.nb<1?"t":"f")+'" strokecolor="#'+props.bd+'" style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+parseInt(v[0]-v[2])+'px;top:'+parseInt(v[1]-v[2])+'px;width:'+(parseInt(v[2])*2)+'px;height:'+(parseInt(v[2])*2)+'px;"><v:fill color="#'+props.co+'" opacity="'+props.op+'" /></v:oval>';
		}else {
		    for(j=2;j<v.length;j+=2) {p += parseInt(v[j])+','+parseInt(v[j+1])+',';}
		    t += '<v:shape unselectable="on" strokeweight="1" filled="t" stroked="'+(props.nb<1?"t":"f")+'" strokecolor="#'+props.bd+'" coordorigin="0,0" coordsize="'+canvas.width+','+canvas.height+'" path="m '+parseInt(v[0])+','+parseInt(v[1])+' l '+p+' 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:fill color="#'+props.co+'" opacity="'+props.op+'" /></v:shape>';
		}
    } else if (isCV) {
        var context = canvas.getContext("2d");
        context.lineWidth = 1;
        context.beginPath();
		if(object.shape.toLowerCase()=='rect') {
		    context.rect(0.5+parseInt(v[0]),0.5+parseInt(v[1]),parseInt(v[2]-v[0]),parseInt(v[3]-v[1])); context.closePath();
		}else if(object.shape.toLowerCase()=='circle') {
		    context.arc(0.5+parseInt(v[0]),0.5+parseInt(v[1]),parseInt(v[2]),0,(Math.PI/180)*360,false); context.closePath();
		}else {
		    context.moveTo(parseInt(v[0]),parseInt(v[1])); for(j=2;j<v.length;j+=2) {context.lineTo(parseInt(v[j]),parseInt(v[j+1]));} context.closePath();
		}
		context.fillStyle = 'rgba('+props.co+','+props.op+')';
		context.strokeStyle = 'rgba('+props.bd+',1)';
		context.fill();
        if(props.nb<1) {context.stroke();}
    } else {
        jg[image.jg].setColor("#"+props.co);
		if(object.shape.toLowerCase()=='rect') {
            jg[image.jg].fillRect(parseInt(v[0]),parseInt(v[1]),parseInt(v[2]-v[0])+1,parseInt(v[3]-v[1])+1);
		}else if(object.shape.toLowerCase()=='circle') {
		    jg[image.jg].fillEllipse(parseInt(v[0]-v[2]),parseInt(v[1]-v[2]),parseInt(v[2])*2+1,parseInt(v[2])*2+1);
		}else {
            var x = new Array(), y = new Array(), i = 0;
            for(j=0;j<v.length;j+=2) {
                x[i] = parseInt(v[j]);
                y[i] = parseInt(v[j+1]); i++;
            } jg[image.jg].fillPolygon(x,y);
		} jg[image.jg].paint();
    }
    return t;
}

/**
 * Dibuja un botón en el mapa de España.
 * @param object - Elemento <area> del <map> que queremos dibujar en el mapa. Contiene las coordenadas del bot�n a dibujar.
 * @param imgage - Imagen asociada al mapa.
 * @param canvas - Elemento contenedor del mapa.
 * @param props - Atributos de color, borde, opacidad, etc., del botón a dibujar
 * @return código VML que define el contenido a dibujar, solamente válido para el navegador IE Explorer
 */
function drawButton(object,image,canvas,props) {
    var v = object.coords.split(","), t = '';
    if (isVM) {
    	t += '<v:oval unselectable="on" strokeweight="2px" filled="f" stroked="t" strokecolor="#'+props.bd+'" style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+parseInt(v[0]-v[2])+'px;top:'+parseInt(v[1]-v[2])+'px;width:'+(parseInt(v[2])*2)+'px;height:'+(parseInt(v[2])*2)+'px;"></v:oval>';
        t += '<v:line unselectable="on" strokeweight="2px" filled="f" stroked="t" strokecolor="#'+props.bd+'" from="'+parseInt(v[0])+'px,'+(parseInt(v[1])-parseInt(v[2])/2)+'px" to="'+parseInt(v[0])+'px,'+(parseInt(v[1])+parseInt(v[2])/2)+'px"/>';
        t += '<v:line unselectable="on" strokeweight="2px" filled="f" stroked="t" strokecolor="#'+props.bd+'" from="'+(parseInt(v[0])-parseInt(v[2])/2)+'px,'+parseInt(v[1])+'px" to="'+(parseInt(v[0])+parseInt(v[2])/2)+'px,'+parseInt(v[1])+'px"/>';
    } else if (isCV) {
        var context = canvas.getContext("2d");
        context.lineWidth = 2;
        context.strokeStyle = 'rgba('+props.bd+',1)';
        context.beginPath();
        context.arc(0.5+parseInt(v[0]),0.5+parseInt(v[1]),parseInt(v[2]),0,(Math.PI/180)*360,false);
        context.moveTo(parseInt(v[0])+0.5,parseInt(v[1])-parseInt(v[2])/2);
        context.lineTo(parseInt(v[0])+0.5,parseInt(v[1])+parseInt(v[2])/2+1);
        context.moveTo(parseInt(v[0])-parseInt(v[2])/2,parseInt(v[1])+0.5);
        context.lineTo(parseInt(v[0])+parseInt(v[2])/2+1,parseInt(v[1])+0.5);
        context.stroke();
        context.closePath();

    } else {
        jg[image.jg].setStroke("#"+props.bd);
        jg[image.jg].drawEllipse(parseInt(v[0]-v[2]),parseInt(v[1]-v[2]),parseInt(v[2])*2,parseInt(v[2])*2);
      	jg[image.jg].fillRect(parseInt(v[0]),(parseInt(v[1])-parseInt(v[2])/2),parseInt(v[0]),(parseInt(v[1])+parseInt(v[2])/2));
      	jg[image.jg].fillRect((parseInt(v[0])-parseInt(v[2])/2),parseInt(v[1]),(parseInt(v[0])+parseInt(v[2])/2),parseInt(v[1]));
        jg[image.jg].paint();
    }
    return t;
}

/**
 * Dibuja un punto (círculo) y el nombre de una ICTS junto a la provincia a la que pertenece, en el mapa de España.
 * @param object - Elemento <area> del <map> de la provincia dibujada en el mapa
 * @param image - Imagen asociada al mapa
 * @param canvas - Elemento contenedor del mapa
 * @param titulo - Nombre de la ICTS
 * @param position - Si hay más de una ICTS situada en la misma provincia (area), hay que indicar en que posición respecto a la misma
 * se escribirá el nombre de la ICTS. Los valores posibles son: 0 - Norte, 1 - Este, 2 - Sur y 3 - Oeste.
 * @param props - Atributos de color, borde, opacidad, etc., del punto y el texto a dibujar 
 * @return código VML que define el contenido a dibujar, solamente válido para el navegador IE Explorer
 */
function drawText(object,image,canvas,titulo,position,props) {
	var v = object.coords.split(","), j = 0, ra = 2, p, t = '';
    p = getInfoCoordinates(v,position,ra);
    if (isVM) { // Internet Explorer
        t += '<v:oval unselectable="on" strokeweight="1" filled="t" stroked="'+(props.nb<1?"t":"f")+'" strokecolor="#'+props.bd+'" style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+(p.x-ra)+'px;top:'+(p.y-ra)+'px;width:'+(ra*2)+'px;height:'+(ra*2)+'px;"><v:fill color="#'+props.co+'" opacity="'+props.op+'" /></v:oval>';
        t += '<v:oval unselectable="on" strokeweight="1" filled="f" stroked="t" strokecolor="#'+props.bd+'" style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+(p.x-(ra*2))+'px;top:'+(p.y-(ra*2))+'px;width:'+(ra*4)+'px;height:'+(ra*4)+'px;"></v:oval>';
        t += '<v:oval unselectable="on" strokeweight="1" filled="f" stroked="t" strokecolor="#'+props.bd+'" style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:'+(p.x-(ra*3))+'px;top:'+(p.y-(ra*3))+'px;width:'+(ra*6)+'px;height:'+(ra*6)+'px;"></v:oval>';
        t += '<v:path unselectable="on" stroked="f" filled="f" style="position:absolute;left:'+(p.x+(ra*4))+'px;top:'+(p.y-(ra*5))+'px;"><v:textbox><div style="color:#000000;font-family:Verdana;font-size:12px;font-weight:bold;">'+titulo+'</div></v:textbox></v:path>';
    } else if (isCV) { // Firefox
        var context = canvas.getContext("2d");
        context.lineWidth = 1;
        context.beginPath();
        context.arc(p.x,p.y,ra,0,(Math.PI/180)*360,false);
        context.fillStyle = 'rgba('+props.co+','+props.op+')';
        context.strokeStyle = 'rgba('+props.co+','+props.op+')';
        context.fill();
        if(props.nb<1) {context.stroke();}
        context.closePath();
        context.beginPath();
        context.arc(p.x,p.y,ra*2.2,0,(Math.PI/180)*360,false);
        context.stroke();
        context.closePath();
        context.beginPath();
        context.arc(p.x,p.y,ra*3.5,0,(Math.PI/180)*360,false);
        context.stroke();
        context.closePath();
        context.beginPath();
        context.fillStyle = '#000000';
        context.strokeStyle = '#000000';
        if (typeof context.fillText == 'function') {
        	context.font = "12px Verdana bold";
            context.fontWeight="bold";
            context.fillText(titulo,(p.x+(ra*5)),p.y);
        } else if (typeof context.strokeText == 'function') {
        	context.font = "12px Verdana bold";
            context.fontWeight="bold";
            context.strokeText(titulo,(p.x+(ra*5)),p.y);
    	} else if (typeof context.mozDrawText == 'function') {
	        context.translate(p.x-ra*10,(p.y-ra*5));
	        context.mozTextStyle = "12px Verdana bold";
	        context.mozDrawText(titulo);
	        context.translate(-(p.x-ra*10),-(p.y-ra*5));
        }
        context.closePath();
    } else {
        jg[image.jg].setColor("#"+props.co);
        jg[image.jg].setStroke("#"+props.bd);
        jg[image.jg].fillEllipse(p.x,p.y,ra*2,ra*2);
        jg[image.jg].drawEllipse((p.x-(ra*2)),(p.y-(ra*2)),ra*4,ra*4);
        jg[image.jg].drawEllipse((p.x-(ra*3)),(p.y-(ra*3)),ra*6,ra*6);
        jg[image.jg].setColor("#000000");
        jg[image.jg].setStroke("#000000");
        jg[image.jg].setFont("Verdana","12px","font-weight:bold;");
        jg[image.jg].drawString(titulo,(p.x+ra),(p.y-(ra*6)));
        jg[image.jg].paint();
    }
    return t;
}

/**
 * Dibuja una provincia en el mapa de España junto con las ICTS ubicadas en esa provincia.
 * @param area - Elemento <area> del <map> asociado a la provincia. Contiene las coordenadas de la provincia a dibujar.
 * @param image - Imagen asociada al mapa
 * @param canvas - Elemento contenedor del mapa
 * @param props - Atributos de color, borde, opacidad, etc., de la provincia a dibujar
 * @param nombres - Nombres de las ICTS situadas en la provincia
 * @return código VML que define el contenido a dibujar, solamente válido para el navegador IE Explorer
 */
function drawProvincia(area,image,canvas,props,nombres) {
	var rel, elems, obj, t = '';
	rel = area.getAttribute('rel');
	var atribs = {bd: props.bd, co: props.co, op: props.op, nb: props.nb, nf: props.nf};
	if (typeof(area.className) != 'undefined' && area.className != '') {
		atribs = getAttributes(area.className,atribs);
	} 
	if (rel != null) {
		elems = rel.split(',');
		for (var i=0; i<elems.length; i++) {
			obj = document.getElementById(elems[i]);
			t += drawArea(obj,image,canvas,atribs); 
		}
	} else {
		t += drawArea(area,image,canvas,atribs);
	}
	elems = nombres.split(',');
	for (i=0; i<elems.length; i++) {
	    if (i==4) {break;}
	    t += drawText(area,image,canvas,elems[i],i,props);
	}
	return t;
}

/**
 * Redibuja el mapa de España con una ICTS.
 * Dibuja en el mapa la provincia donde está situada la ICTS, el nombre de la ICTS y un botón (optativo).
 * @param image - Imagen asociada al mapa
 * @param provincia - Elemento <area> del <map> asociado a la provincia donde se ubica la ICTS. Contiene las coordenadas de la provincia a dibujar.
 * @param nombre - Nombre de la ICTS
 * @param boton (Optativo) - Elemento <area> del <map> asociado al botón. Contiene las coordenadas del botón a dibujar.
 */
function drawICTSMap(image,provincia,nombre,boton) {
    var t = '';
    var img = document.getElementById(image);
    var prov = document.getElementById(provincia);
    var cav = document.getElementById(img.canvasid);
    var props = {bd : performRGBColor(img.options['bordercolor'],'#0000ff'),
                 co : performRGBColor(img.options['areacolor'],'#000000'),
                 op : img.options['opacity']/100,
                 nb : img.options['noborder'],
                 nf : img.options['nofade']}

    props = getAttributes(prov.className,props);
    if (!(img && prov && cav)) {return;}
    if (isCV && props.nf<1) {
    	cav.fading = 0;
    	cav.style.opacity = 0;
    }
    if (!(isCV || isVM)) {
    	if(isIE) {
    		cav.style.filter = "Alpha(opacity="+(props.op*100)+")";
		} else {
			cav.style.opacity = props.op;
			cav.style.MozOpacity = props.op;
			cav.style.KhtmlOpacity = props.op;
	    }
    }
    t += drawProvincia(prov,img,cav,props,nombre);
    if (typeof(boton) != 'undefined') {
        var objBoton = document.getElementById(boton);
        props = {bd : performRGBColor(img.options['bordercolor'],'#0000ff'),
                 co : performRGBColor(img.options['areacolor'],'#000000'),
                 op : img.options['opacity']/100,
                 nb : img.options['noborder'],
                 nf : img.options['nofade']}
        props = getAttributes(objBoton.className,props);
        t += drawButton(objBoton,img,cav,props);
    }
    if (isVM) {cav.innerHTML = t;}
}

/**
 * Redibuja el mapa de España con un conjunto de ICTS.
 * Para cada ICTS, dibuja en el mapa la provincia donde está situada y el nombre.
 * Opcionalmente dibuja un botón en el mapa.
 * @param image - Imagen asociada al mapa
 * @param provincias - Elemento <area> del <map>, contiene la relación de provincias (otros <area>) a dibujar
 * @param nombres - Nombres de las ICTS
 * @param boton (Optativo) - Elemento <area> del <map> asociado al botón. Contiene las coordenadas del botón a dibujar.
 */
function drawRelICTSMap(image,provincias,nombres,boton) {
    var t = '';
    var img = document.getElementById(image);
	var obj = document.getElementById(provincias);
	var cav = document.getElementById(img.canvasid);
    var props = {bd : performRGBColor(img.options['bordercolor'],'#0000ff'),
                 co : performRGBColor(img.options['areacolor'],'#000000'),
                 op : img.options['opacity']/100,
                 nb : img.options['noborder'],
                 nf : img.options['nofade']}
    props = getAttributes(obj.className,props);
    if (!(img && obj && cav)) {return;}
    if (isCV && props.nf<1) {
    	cav.fading = 0;
    	cav.style.opacity = 0;
    }
    if (!(isCV || isVM)) {
    	if(isIE) {
    		cav.style.filter = "Alpha(opacity="+(props.op*100)+")";
		} else {
			cav.style.opacity = props.op;
			cav.style.MozOpacity = props.op;
			cav.style.KhtmlOpacity = props.op;
	    }
    }
    var rel = obj.getAttribute('rel'), elems = new Array();
    elems = rel.split(',');
    for (var i=0; i<elems.length; i++) {
    	obj = document.getElementById(elems[i]);
    	t += drawProvincia(obj,img,cav,props,nombres[obj.id]);
    }
    if (typeof(boton) != 'undefined') {
        var objBoton = document.getElementById(boton);
        props = {bd : performRGBColor(img.options['bordercolor'],'#0000ff'),
                 co : performRGBColor(img.options['areacolor'],'#000000'),
                 op : img.options['opacity']/100,
                 nb : img.options['noborder'],
                 nf : img.options['nofade']}
        props = getAttributes(objBoton.className,props);
        t += drawButton(objBoton,img,cav,props);
    }
    if (isVM) {cav.innerHTML = t;}
}

/**
 * Borra del mapa de España los elementos dibujados.
 * @param image - Imagen asociada al mapa
 */
function clearMap(image) {
	var img = document.getElementById(image);
	var cav = document.getElementById(img.canvasid);
	if (!(img && cav)) {return;}
	if (isVM) {
		cav.innerHTML = '';
	} else if (isJG) {
		jg[img.jg].clear();
	} else if (isCV) {
		var context = cav.getContext("2d");
		context.clearRect(0,0,cav.width,cav.height);
	}	
}

/**
 * Crea un objecto ICTSMap.
 * Con los métodos: add, modify, remove.
 */
var ICTSMap = {
	defaultRadius : 0,
	defaultOpacity : 33,
	defaultBordercolor : '#0000ff',
	defaultAreacolor : '#000000',
	defaultNoborder : false,
	defaultNofade : false,
	defaultImgsrc : '',
	defaultMapid : '',
	add: function(image, options) {
		var map, mapname = image.useMap.split("#");
		if(mapname[1]!=''&&mapname[1].length>=1) {map = document.getElementsByName(mapname[1])[0];}
		if(image.tagName.toUpperCase() == "IMG" && map) {
			var defopts = { "radius" : ICTSMap.defaultRadius,
							"opacity" : ICTSMap.defaultOpacity,
							"bordercolor" : ICTSMap.defaultBordercolor,
							"areacolor" : ICTSMap.defaultAreacolor,
							"noborder" : ICTSMap.defaultNoborder,
							"nofade" : ICTSMap.defaultNofade,
							"imgsrc" : ICTSMap.defaultImgsrc,
							"mapid" : ICTSMap.defaultMapid };
			if (options) {
				for (var i in defopts) {
					if (typeof(options[i])=='undefined') {
						options[i] = defopts[i]; 
					}
				}
			} else {options = defopts;}
			try {
				var object = image.parentNode;
				object.style.position = (object.style.position=='static'||object.style.position==''?'relative':object.style.position);
				object.style.height = image.height+'px';
				object.style.width = image.width+'px';
				object.style.padding = 0+'px';
				object.style.MozUserSelect = "none";
				object.style.KhtmlUserSelect = "none"; 
				object.unselectable = "on";
				var blind, bgrnd, canvas; image.jg = 0;
				if(isVM) {
					if(document.namespaces['v'] == null) {
						var stl = document.createStyleSheet();
						stl.addRule("v\\:*", "behavior: url(#default#VML);");
						document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
					}						 
					canvas = document.createElement(['<var style="zoom:1;overflow:hidden;display:block;width:'+image.width+'px;height:'+image.height+'px;padding:0;">'].join(''));
					bgrnd = document.createElement(['<var style="zoom:1;overflow:hidden;display:block;width:'+image.width+'px;height:'+image.height+'px;padding:0;">'].join(''));
					dummy = document.createElement(['<var style="zoom:1;overflow:hidden;display:block;width:'+image.width+'px;height:'+image.height+'px;padding:0;">'].join(''));// NEW
				} else if (isCV) {
					canvas = document.createElement('canvas');
					bgrnd = document.createElement('canvas');
				} else {
					canvas = document.createElement('div');
					bgrnd = document.createElement('img'); 
					bgrnd.src = image.src;
					if(typeof(window['jsGraphics']) !== 'undefined') {
						image.jg = parseInt(jg.length); 
						jg[image.jg] = new jsGraphics(canvas); isJG = 1;
					}
				}
	            canvas.id = image.id+'_canvas';
				canvas.style.height = image.height+'px';
				canvas.style.width = image.width+'px';
				canvas.height = image.height;
				canvas.width = image.width;
				canvas.left = 0; canvas.top = 0;
				canvas.style.position = 'absolute';
				canvas.style.left = 0+'px';
				canvas.style.top = 0+'px';
				canvas.fading = 0;
				image.className = '';
				image.style.cssText = '';
				image.left = 0; image.top = 0;
				image.style.position = 'absolute';
				image.style.height = image.height+'px';
				image.style.width = image.width+'px';
				image.style.left = 0+'px';
				image.style.top = 0+'px';
				image.style.MozUserSelect = "none";
				image.style.KhtmlUserSelect = "none"; 
				image.unselectable = "on";
				image.options = options;
				image.canvasid = image.id+'_canvas';
				image.dummyid = image.id+'_dummy'; // NEW
				image.bgrndid = image.id+'_image';
				image.blindid = map.name+'_blind';
				image.mapname = map.name;
				image.areas = map.innerHTML;
				image.active = false;
	            if(isIE) {
	            	image.style.filter = "Alpha(opacity=0)";
				} else {
					image.style.opacity = 0; image.style.MozOpacity = 0; image.style.KhtmlOpacity = 0;
				}
				bgrnd.id = image.bgrndid;
				bgrnd.left = 0; bgrnd.top = 0;
				bgrnd.style.position = 'absolute';
				bgrnd.style.height = image.height+'px';
				bgrnd.style.width = image.width+'px';
				bgrnd.style.left = 0+'px';
				bgrnd.style.top = 0+'px';
				bgrnd.height = image.height; 
				bgrnd.width = image.width;				
				blind = document.createElement('div');
				blind.id = image.blindid;
				blind.className = "blind_area";
				blind.left = 0; blind.top = 0;
				blind.style.position = 'absolute';
				blind.style.height = image.height+'px';
				blind.style.width = image.width+'px';
				blind.style.left = 0+'px';
				blind.style.top = 0+'px';
				blind.innerHTML = " ";
				object.insertBefore(canvas,image);
				object.insertBefore(bgrnd,canvas);
				object.insertBefore(blind,image);
				ICTSMap.modify(image, options);
			} catch (e) {}
		}
	},
	
	modify: function(image, options) {
		try {
			var radius = (typeof options['radius']=='number'?options['radius']:image.options['radius']); image.options['radius']=radius;
			var opacity = (typeof options['opacity']=='number'?options['opacity']:image.options['opacity']); image.options['opacity']=opacity;
			var bcolor = (typeof options['bordercolor']=='string'?options['bordercolor']:image.options['bordercolor']); image.options['bordercolor']=bcolor;
			var acolor = (typeof options['areacolor']=='string'?options['areacolor']:image.options['areacolor']); image.options['areacolor']=acolor;
			var noborder = (typeof options['noborder']=='boolean'?options['noborder']:image.options['noborder']); image.options['noborder']=noborder;
			var nofade = (typeof options['nofade']=='boolean'?options['nofade']:image.options['nofade']); image.options['nofade']=nofade;
			var imgsrc = (typeof options['imgsrc']=='string'?options['imgsrc']:image.options['imgsrc']); image.options['imgsrc']=imgsrc;
			var mapid = (typeof options['mapid']=='string'?options['mapid']:image.options['mapid']); image.options['mapid']=mapid;
			var context, func, ih = image.height, iw = image.width; 
			var radius = parseInt(Math.min(Math.min(iw/4,ih/4),radius));
			var opacity = opacity==0?0.33:opacity/100; 
			var bcolor = performRGBColor(bcolor,'#0000ff');
			var acolor = performRGBColor(acolor,'#000000');	
			var canvas = document.getElementById(image.canvasid);
			var dummy = document.getElementById(image.dummyid);
			var bgrnd = document.getElementById(image.bgrndid);
			var map = document.getElementsByName(image.mapname)[0];
			var opac = 100;
			function replace() {
				if(mapid!='') {
					var tmp = document.getElementById(mapid);
					if(tmp) {map.innerHTML = tmp.innerHTML;}
				}else {
					map.innerHTML = image.areas; 
				}
			}
			if(canvas && bgrnd && map) {
				if(isCV) {
					context = canvas.getContext("2d");
					context.clearRect(0,0,canvas.width,canvas.height);
				}else if(isVM) {
					canvas.innerHTML = '';
				}else {
					if(isIE) {
						canvas.style.filter = "Alpha(opacity="+(opacity*100)+")";
					}else { 
						canvas.style.opacity = opacity; canvas.style.MozOpacity = opacity; canvas.style.KhtmlOpacity = opacity;
					} 
					if(isJG) {jg[image.jg].clear();}
				}
				if(isCV) {
					if(imgsrc!='') {
						var img = new Image();
						img.onload = function() {
							context = bgrnd.getContext("2d");
							context.clearRect(0,0,bgrnd.width,bgrnd.height);
							context.save();
							if(radius>0) {
								roundedRect(context,0,0,bgrnd.width,bgrnd.height,radius);
								context.clip();
							}
							context.fillStyle = 'rgba(0,0,0,0)';
							context.fillRect(0,0,bgrnd.width,bgrnd.height);
							context.drawImage(img,0,0,bgrnd.width,bgrnd.height);
							context.restore();
							replace();
						}
						img.src = imgsrc;
					}else {	
						context = bgrnd.getContext("2d");
						context.clearRect(0,0,bgrnd.width,bgrnd.height);
						context.save();
						if(radius>0) {
							roundedRect(context,0,0,bgrnd.width,bgrnd.height,radius);
							context.clip();
						}
						context.fillStyle = 'rgba(0,0,0,0)';
						context.fillRect(0,0,bgrnd.width,bgrnd.height);
						context.drawImage(image,0,0,bgrnd.width,bgrnd.height);
						context.restore();
						replace();
					}
				} else if(isVM) {
					if(radius>0) {radius = getRadius(radius,bgrnd.width,bgrnd.height);}	
					bgrnd.innerHTML = '<v:roundrect arcsize="'+radius+'" strokeweight="0" filled="t" stroked="f" fillcolor="#ffffff" style="zoom:1;margin:0;padding:0;display:block;position:absolute;left:0px;top:0px;width:'+bgrnd.width+'px;height:'+bgrnd.height+'px;"><v:fill src="'+(imgsrc!=''?imgsrc:image.src)+'" type="frame" /></v:roundrect>';
					replace();
				} else {
					bgrnd.src = imgsrc!=''?imgsrc:image.src;
					replace();
				} image.active = true;
			}
		} catch (e) {}
	},
	
	remove : function(image) {
		var ele, object = image.parentNode;
		if(image.active) {
			if(isIE) { image.style.filter = "Alpha(opacity=100)";}else {image.style.opacity = 100; image.style.MozOpacity = 100; image.style.KhtmlOpacity = 100;}
			ele = document.getElementsByName(image.mapname)[0]; ele.innerHTML = image.areas; image.active = false; image.areas = ''; 	
			if(isVM||isIE) {image.onmousemove = image.movefunc;}else {image.setAttribute("onmousemove",image.movefunc);}
			ele = document.getElementById(image.canvasid); if(ele) {object.removeChild(ele);}
			ele = document.getElementById(image.blindid); if(ele) {object.removeChild(ele);}
			ele = document.getElementById(image.bgrndid); if(ele) {object.removeChild(ele);}
		}
	}
}