// ***************** INIT *****************
// Глобальный хэши и переменные для хранения координат и состояний выделения областей
var globalCoords = {};
var globalHref = {};
var areaShowState = {};
var globalIdHash = {
	'mId' : null,
	'nId' : null,
	'sId' : null,
	'cId' : null,
	'hId' : null
}
var curPrefix = null;

// Инициализация всех компонентов
function initImageMap(prefix, mId, nId, sId, cId, hId) {
	if (!mId || !nId || !sId || !cId || !hId) {
		// Один из компонент системы не указан
		return;
	}
	curPrefix = prefix;
	globalIdHash.mId = mId + prefix;
	globalIdHash.nId = nId + prefix;
	globalIdHash.sId = sId + prefix;
	globalIdHash.cId = cId + prefix;
	globalIdHash.hId = hId + prefix;
	var map = gebi(globalIdHash.mId);
	var nullimage = gebi(globalIdHash.nId);
	var selfmap = gebi(globalIdHash.sId);
	var canvas = gebi(globalIdHash.cId);
	var hoverCanvas = gebi(globalIdHash.hId);
	if (!map || !nullimage || !selfmap || !canvas || !hoverCanvas) return;
	var area, i;
	if (typeof globalCoords[prefix] == "undefined") {
		globalCoords[prefix] = [];
		areaShowState[prefix] = [];
		globalHref[prefix] = [];
		for (i = 0; i < map.childNodes.length; i++) {
			area = map.childNodes[i];
			if (area.nodeType != 1) continue;
			if (area.nodeName.toLowerCase() != "area") continue;
			area.onclick = selectRegion;
			area.onmousemove = showTooltip;
			if (isIE) area.onmouseover = showHoverCanvas;
			if (isIE) area.onmouseout = hideHoverCanvas;
			area.id = area.alt + "_" + i;
			area.alt = "";
			areaShowState[prefix][i] = 0;
			globalCoords[prefix][i] = area.coords;
			globalHref[prefix][i] = area.href;
		}
	}
	document.onmousemove = hideTooltip;
	hoverCanvas.style.top = nullimage.style.top = canvas.style.top = absPosition(selfmap).y + "px";
	hoverCanvas.style.left = nullimage.style.left = canvas.style.left = absPosition(selfmap).x + "px";
}

// ***************** FUNCTIONS *****************
// Парсим строку с координатами в двумерный массив
function parseCoords(str) {
	var coords = [];
	var buferArray = str.split(",");
	var j = 0;
	for (var i = 0; i < buferArray.length; i++) {
		if (i % 2 == 0) {
			coords[j] = [];
			coords[j][0] = buferArray[i];
		} else {
			coords[j][1] = buferArray[i];
			j++;
		}
	}
	return coords;
}
// Тултипы :: показать всплывающую подсказку над областью
function showTooltip(evt) {
	evt = evt || window.event;
	cancelBubbling(evt);
	var tooltipDiv;
	if (!gebi("tooltipDivId")) {
		tooltipDiv = document.createElement("div");
		tooltipDiv.id = "tooltipDivId";
		document.body.appendChild(tooltipDiv);
	}
	tooltipDiv = gebi("tooltipDivId");
	tooltipDiv.innerHTML = this.id.substring(0, this.id.indexOf("_"));
	tooltipDiv.style.top = (defPosition(evt).y + 20) + "px";
	tooltipDiv.style.left = (defPosition(evt).x) + "px";
	tooltipDiv.style.display = "block";
}
// Тултипы :: скрыть всплывающую подсказку над областью
function hideTooltip() {
	if (gebi("tooltipDivId")) gebi("tooltipDivId").style.display = "none";
}
// Ховеры :: показать ховер
function showHoverCanvas() {
	var ctx = gebi(globalIdHash.hId).getContext('2d');
	var coords = this.coords;
	if (typeof coords == "undefined") return;
	coords = parseCoords(coords);
	ctx.clearRect(0, 0, 521, 517);
	ctx.beginPath();
	for (j = 0; j < coords.length; j++) {
		if (j == 0) ctx.moveTo(coords[j][0], coords[j][1]);
		else ctx.lineTo(coords[j][0], coords[j][1]);
	}
	ctx.fillStyle = "rgba(256,256,256,0.5)";
	ctx.fill();
}
// Ховеры :: скрыть ховер
function hideHoverCanvas() {
	var ctx = gebi(globalIdHash.hId).getContext('2d');
	ctx.clearRect(0, 0, 521, 517);
}
// Выбрать регион при клике
function selectRegion() {
	try {
		if (this.nodeName.toLowerCase() != "area") return false;
		var id = this.href.substring(this.href.lastIndexOf("#") + 1, this.href.length);
		gebi("loc" + id).checked = !gebi("loc" + id).checked;
		if (curPrefix == "2") clickOkrug(gebi("loc" + id));
		checkOkrugState();
		if (gebi("loc" + id).checked) scrollToRegion(id);
	} catch(e) {}
	return false;
}
// Отрисовать выбранные регионы в канвас
function drawPolygons() {
	var ctx = gebi(globalIdHash.cId).getContext('2d');
	var coords;
	var i, j;
	ctx.clearRect(0, 0, 521, 517);
	for (i = 0; i < areaShowState[curPrefix].length; i++) {
		if (!areaShowState[curPrefix][i]) continue;
		if (typeof globalCoords[curPrefix][i] == "undefined") continue;
		coords = [];
		coords = parseCoords(globalCoords[curPrefix][i]);
		ctx.beginPath();
		for (j = 0; j < coords.length; j++) {
			if (j == 0) ctx.moveTo(coords[j][0], coords[j][1]);
			else ctx.lineTo(coords[j][0], coords[j][1]);
		}
		ctx.fillStyle = "rgba(128,128,128,0.5)";
	    ctx.fill();
	}
} 

