var dragInProgress = 0;
var dragDiv;
var loadDiv;
var markDiv;
var origX, origY;
var ie = ((document.all)? true : false);
var lastX;
var lastY;
var mainImage;
var newWidth, newHeight;
var evt;
var sLeft;
var sRight;
var sTop;
var sBottom;
var tableWidth;
var tableHeight;
var tableLeft,tableTop;
var sl,st;
var timerStart;
var optScale = 1;
var currentExtents = new Object();
var clickStatus = 0;

function reload(args) {
	timerStart = new Date();
	tableWidth = mainImage.clientWidth / optScale;
	tableHeight = mainImage.clientHeight / optScale;
//	tableWidth = tableHeight = 100;
	tableLeft = recursiveOffsetX(mainImage);
	tableTop = recursiveOffsetY(mainImage);

    loadDiv.style.left = (-tableLeft+(tableWidth - loadDiv.clientWidth)/2) + 'px';
    loadDiv.style.top = (-tableTop+(tableHeight - loadDiv.clientHeight)/2) + 'px'; 
	loadDiv.style.visibility = "visible";

	loadExtents();

	var ran_number= Math.floor(Math.random()*10000000);
	var newUrl = 'viewmap_img.php?rand=' + ran_number + '&xSize=' + tableWidth + '&ySize=' + tableHeight + '&' + args;
	//mainImage.style.backgroundImage = 'url(' + newUrl + ')';
	//refImage.src='tmp/ref_' + ran_number + '.gif';
	//mainImage.src='viewmap_img.php?rand=' + ran_number + '&' + args;
	mainImage.src = newUrl;
	//alert(mainImage.src);
//	alert(newUrl);
	return;
}

function loadExtents() {
	currentExtents['minx'] = readCookie('minx');
	currentExtents['maxx'] = readCookie('maxx');
	currentExtents['miny'] = readCookie('miny');
	currentExtents['maxy'] = readCookie('maxy');
}

function loadingFinished() {
	if (loadDiv)
	{
		loadDiv.style.visibility = "hidden";
	}
	var timeToLoad = new Date() - timerStart;
	var debugInfo = document.getElementById('mapDebugInfo');
	if (debugInfo)
	{
		debugInfo.innerHTML = timeToLoad;
		//debugInfo.innerHTML += "<br>" + recreateLink();
	}
	updateDiv('linkDiv',getLinkTo());
	updateDiv('saveDiv',getSave());
	return;
}

function reloadRand() {
	var randGroup = Math.floor(20041 * Math.random());
	var randZoom = Math.floor(10000 * Math.random()) + 3000;
	reload('viewobject=groups,group_id,' + randGroup + ',main_name_shaped&zoom=area&zoomscale=' + randZoom);
	setTimeout("reloadRand();", 60000);
}

function initializeLoad(){
    dragDiv = document.createElement("div");
    document.body.appendChild(dragDiv);                        
    dragDiv.style.visibility = "hidden";
    dragDiv.style.position = "absolute";
    dragDiv.style.border = "1px solid red";
    dragDiv.style.width = "0px";
    dragDiv.style.height = "0px";
    dragDiv.style.zIndex = 3;
    dragDiv.style.left = "20px";
    dragDiv.style.top = "20px";      
    dragDiv.innerHTML = "<img src='images/transpix.gif'>";
    dragDiv.style.filter = "alpha(opacity=50)";
    dragDiv.style.opacity = 0.5;
    dragDiv.style.background = "#ffffff";

	loadDiv = document.createElement("div");
	document.body.appendChild(loadDiv);
    loadDiv.style.visibility = "hidden";
    loadDiv.style.position = "absolute";
    loadDiv.style.border = "3px solid red";
	loadDiv.style.background = "white";
    loadDiv.style.zIndex = 3;
    loadDiv.style.left = "20px";
    loadDiv.style.top = "20px";      
    loadDiv.innerHTML = "<font size = 10>&nbsp;جاري التحميل...&nbsp;</font>";
    loadDiv.style.filter = "alpha(opacity=90)";
    loadDiv.style.opacity = 0.9;


	mainImage = document.getElementById('mapImage');
	addEventListener(mainImage, "mousedown", mouseDown);

	reloadRand();
	return;
}

function initialize(){
    dragDiv = document.createElement("div");
    document.body.appendChild(dragDiv);                        
    dragDiv.style.visibility = "hidden";
    dragDiv.style.position = "absolute";
    dragDiv.style.border = "1px solid red";
    dragDiv.style.width = "0px";
    dragDiv.style.height = "0px";
    dragDiv.style.zIndex = 3;
    dragDiv.style.left = "20px";
    dragDiv.style.top = "20px";      
    dragDiv.innerHTML = "<img src='images/transpix.gif'>";
    dragDiv.style.filter = "alpha(opacity=50)";
    dragDiv.style.opacity = 0.5;
    dragDiv.style.background = "#ffffff";

	loadDiv = document.createElement("div");
	document.body.appendChild(loadDiv);
    loadDiv.style.visibility = "hidden";
    loadDiv.style.position = "absolute";
    loadDiv.style.border = "3px solid red";
	loadDiv.style.background = "white";
    loadDiv.style.zIndex = 3;
    loadDiv.style.left = "20px";
    loadDiv.style.top = "20px";      
    loadDiv.innerHTML = "<font size = 10>&nbsp;جاري التحميل...&nbsp;</font>";
    loadDiv.style.filter = "alpha(opacity=90)";
    loadDiv.style.opacity = 0.9;
	
	mainImage = document.getElementById('mapImage');
	addEventListener(mainImage, "mousedown", mouseDown);
	reload('');
	return;
}

function addStar(x,y) {
	x -= 10;
	y -= 10;
	var star = document.createElement("img");
	document.body.appendChild(star);
	star.src = 'http://www.khareeta.net/images/redstar.gif';
    star.style.position = "absolute";
    star.style.border = "0px";
	star.style.background = "white";
    star.style.zIndex = 3;
    star.style.left = x + 'px';
    star.style.top = y + 'px'; 
}

function mouseDown(evt) {
	if(ie) evt = event;
	calcXY(0,evt);
	origX = lastX;
	origY = lastY;
	if (clickStatus == 1)
	{
		addStar(origX,origY);
		return -1;
	}
	dragInProgress = 1;
	dragDiv.style.visibility = "visible";
    dragDiv.style.left = lastX+"px";
    dragDiv.style.top = lastY+"px";
    dragDiv.style.width = "1px";
    dragDiv.style.height = "1px";
    addEventListener(document, "mousemove", mouseMove);
    addEventListener(document, "mouseup", mouseUp);
	return -1;
}

function mouseUp() {
    removeEventListener(document, "mousemove", mouseMove);  
    removeEventListener(document, "mouseup", mouseUp);
	dragInProgress = 0;
	dragDiv.style.visibility = "hidden";
	if (Math.abs(lastX - origX) < 5)
	{
		alert('Draw a bigger rectangle');
		return;
	}

//	alert((sLeft + tableLeft)+","+(sRight + tableLeft)+"\n"+(sTop + tableTop)+","+(sBottom + tableTop));
	reload('zoom=box&zrRight='+ (sRight + tableLeft) / optScale +
	'&zrLeft='+ (sLeft + tableLeft) / optScale +
	'&zrTop='+ (sTop + tableTop) / optScale +
	'&zrBottom='+ (sBottom + tableTop) / optScale);
//	alert(mainImage.offsetTop);
	return;
}

function mouseMove(evt) {
	if(!evt) evt = event;
	var aspect = tableHeight / tableWidth;
	if (dragInProgress)
	{
		calcXY(0,evt);
		newWidth = Math.abs(lastX - origX);
		newHeight = Math.abs(lastY - origY);
		//newDim = Math.max(newWidth,newHeight/aspect);
		newWidth = newHeight = Math.max(newWidth,newHeight/aspect);
		dragDiv.style.width = newWidth+"px";
		dragDiv.style.height = newHeight*aspect+"px";
		if (origX < lastX) {
			dragDiv.style.left = origX + "px";
			sLeft = origX;
			sRight = origX + newWidth;
		}
		else {
			dragDiv.style.left = (origX - newWidth) + "px";
			sLeft = origX - newWidth;
			sRight = origX;
		}
		if (origY < lastY)
		{
			dragDiv.style.top = origY + "px";
			sTop = origY;
			sBottom = origY + newHeight * aspect;
		}
		else {
			dragDiv.style.top = (origY - newHeight*aspect) + "px";
			sTop = origY - (newHeight*aspect)
			sBottom = origY;
		}
	}
}

function calcXY(ind,ev){
    if (ie){
	// Internet Explorer
	if (document.documentElement.scrollTop){
	    sl = document.documentElement.scrollLeft;
	    st = document.documentElement.scrollTop;
	}else{
	    sl = document.body.scrollLeft;
	    st = document.body.scrollTop;
	}
	lastX = ev.clientX-17-2;
	lastY = ev.clientY+st-2;
    }else{	    
	// Mozilla
	lastX = ev.pageX;
	lastY = ev.pageY;
    }
	return;
}

function addEventListener(o, type, handler) {
    if(ie){
	o.attachEvent("on" + type, handler);
    }else{
        o.addEventListener(type, handler, false);
    }
}

function removeEventListener(o, type, handler) {
    if(ie){
	o.detachEvent("on" + type, handler);
    }else{
        o.removeEventListener(type, handler, false);
    }
}

function recursiveOffsetX(object) {
	var offset = 0;
	offset -= object.offsetLeft - document.body.scrollLeft;
	while (object.offsetParent)
	{
		object = object.offsetParent;
		offset -= object.offsetLeft;
	}
	return offset;
}

function recursiveOffsetY(object) {
	var offset = 0;
	offset -= object.offsetTop;
	while (object.offsetParent)
	{
		object = object.offsetParent;
		offset -= object.offsetTop;
	}
	return offset;
}

function recreateLink() {
	var cookies = document.cookie;
	var ca = cookies.split('; ');
	var args = 'recreate=1';
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		args += '&' + ca[i];
	}
	return args;
}

function updateDiv(divName, value) {
	var divToUpdate = document.getElementById(divName);
	if (divToUpdate)
	{
		divToUpdate.innerHTML = value;
	}
}

function getLinkTo() {
	var args = recreateLink();
	args += '&xSize=' + tableWidth + '&ySize=' + tableHeight;
	return "<a href = 'get_link.php?" + args + "' target='_blank'>ارسل هذه الخريطة الي صديق</a>";
}

function getSave() {
	var args = recreateLink();
	args += '&xSize=' + tableWidth + '&ySize=' + tableHeight;
	return "<a href = 'viewmap_img.php?" + args + "' target='_blank'>حمل</a>";
}

function chooseIntersection(isection,search) {
	var intersectionName = isection.options[isection.selectedIndex].value;
	reload('intersection=' + intersectionName + '&viewobject=' + search + '&zoom=viewobject');
	return false;
}

function chooseLandmark(landmark,search) {
	var landmarkName = landmark.options[landmark.selectedIndex].value;
	reload('landmark=' + landmarkName + '&viewobject=' + search + '&zoom=viewobject');
	return false;
}

//#########################
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
