

var currentLuogo;
var mapLeftSaved = 125;
var mapTopSaved = 75;
var savedPopupBgcolor = "ffffff";
var savedCallingObjId = "";
var savedParentId;

/**
* We need to preload our images for smoothness and also to be sure that the
* coordinates are found properly.
*/
var preLargeMapImage;
var preSmallMapImage;

var arrowPath = "/gifimages/maps/arrow_green_longBig.gif";
var animatedArrowPath = "/gifimages/maps/arrow_animated_greenBig.gif";
var shadowPath = "/gifimages/maps/shadow.png";

/**
* Called in EmailAndPrintLinks.jsp to show the Map of the current luogo
*/



function showMap(luogo, mapDocPath, callingObjId, popupBgcolor, largeMapPath, smallMapPath, leftPos, topPos, parentId){
	
	savedCallingObjId = callingObjId;
	savedPopupBgcolor = popupBgcolor;
	savedParentId = parentId;

	var largeMapImage = new Image();
	var smallMapImage = new Image();
	largeMapImage.src = largeMapPath;
	smallMapImage.src = smallMapPath;
	var posLeft = $(callingObjId).getPosition().x;
	var posTop = $(callingObjId).getPosition().y;
	
	//if the calling prog sends 0, we work show the map below the calling link, more or less centered
	if(leftPos == 0 && topPos == 0){
		mapLeftSaved = $(callingObjId).getPosition().x - 300;
		mapTopSaved = $(callingObjId).getPosition().y + 20;
	}else{
		mapLeftSaved = leftPos;
		mapTopSaved = topPos;	
	}

	//currentLuogo = unescape(luogo);
	currentLuogo = luogo;
	startMapRequest(luogo, mapDocPath);
	return false;
}

function preloadMapImages(largeMapPath, smallMapPath){
	var preArrowImage = new Asset.image(arrowPath);
	var preArrowImage2 = new Asset.image(animatedArrowPath);
	//var preShadowImg = new Asset.image(shadowPath);
	var preLargeMapImage = new Asset.image(largeMapPath);
	var preSmallMapImage = new Asset.image(smallMapPath);
}//end function()

var xmlHttpMap;

function startMapRequest(luogo, mapDocPath){
    xmlHttpMap = createXMLHttpRequest();
    xmlHttpMap.onreadystatechange = handleStateChangeMap;
    
    var URL = mapDocPath + "?luogo=" + luogo;
    URL += "&tm=" + new Date().getTime();
    
    xmlHttpMap.open("GET", URL, true);
    xmlHttpMap.send(null);
}//end function

function handleStateChangeMap(){
    if(xmlHttpMap.readyState == 4){
        if(xmlHttpMap.status == 200){
        	doMapAndArrow(xmlHttpMap.responseText);

        	if($defined($(savedParentId))){
        		var myFx = new Fx.Scroll(window,{
        			duration: 'long'
         		});
        		myFx.toElement(savedParentId);
        	}else{
//        		window.scrollTo(0, $('mapDiv').offsetTop - 70);
        		var myFx = new Fx.Scroll(window,{
        			duration: 'long',
        			offset: {
        				x: 0,
        				y: -70
        			}
         		});
        		myFx.toElement($('mapDiv'));
        	}//end if			
			
 		}//end if
    }//end if
}//end function

function doMapAndArrow(theHtml){
	var hideIt = true;
	var mapDiv = placeMap(theHtml);
	//var shadowDiv = resizeShadow();
	var shadowDiv = null;
	var arrowDiv = placeArrow(currentLuogo, hideIt);
	doOpeningShow(mapDiv, shadowDiv, arrowDiv);
}//end function

function doOpeningShow(mapDiv, shadowDiv, arrowDiv){
				var openingDuration = 500;

				var shower = new Element('div', {
					id: 'shower',
					styles: {
						borderStyle: 'solid',			
						borderColor: '#cccccc',			
						borderWidth: '1px',
						backgroundColor: savedPopupBgcolor,
						width: '0px',			
						height: '0px',			
						zIndex: 2,			
						position: 'absolute',
						left: $(savedCallingObjId).getPosition().x,
						top: $(savedCallingObjId).getPosition().y
					}
				});

				shower.inject($(savedCallingObjId), 'after');


				var myEffect = new Fx.Morph(shower,{
					duration: openingDuration
				});
	
				//unfortunately VIT has a strange css layout, and this
				//compensates for 'mainTable' offsets
				var myOffsetLeft = shower.offsetParent.offsetLeft;
				var myOffsetTop = shower.offsetParent.offsetTop;
	
				myEffect.start({
					height: mapDiv.clientHeight,
					width: mapDiv.clientWidth,
					left: mapLeftSaved - myOffsetLeft,
					top: mapTopSaved - myOffsetTop
				}).chain(function(){
					mapDiv.style.visibility = "visible";
					//shadowDiv.style.visibility = "visible";
					arrowDiv.style.visibility = "visible";
					shower.destroy();
				});
				
				var myDrag = new Drag.Move($('mapDiv'));
				
		       	$('luogoSelect').addEvents({
	        		mouseover: function(){
	       				myDrag.detach();
	        		},
	        		click: function(){
		       			myDrag.detach();
	        		},
	        		mouseout: function(){
		       			myDrag.attach();
	        		}
	        	});

				
}

/**
* Now that we have the map we can size the shadow as well
*/
function resizeShadow(){
	var shadowDiv = document.getElementById("mapShadowDiv");
	var shadowImg = document.getElementById("mapShadowImg");
	var mapDiv = document.getElementById("mapDiv");
	shadowDiv.style.position = "absolute";
	shadowDiv.style.border = "0";
	shadowDiv.style.top = parseInt(mapDiv.style.top) + 15 + "px";
	shadowDiv.style.left = parseInt(mapDiv.style.left) + 15 + "px";
	shadowImg.style.height = mapDiv.offsetHeight + "px";
	shadowImg.style.width = mapDiv.offsetWidth + "px";
	shadowDiv.style.visibility = "hidden";
	return shadowDiv;
}

/**
* Prepares the shadow div
*/
function placeShadow(){
	var shadowDiv = document.createElement("div");
	shadowDiv.id = "mapShadowDiv";
	var shadowImg = document.createElement("img");
	shadowImg.src = shadowPath;
	shadowImg.id = "mapShadowImg";
	document.body.appendChild(shadowDiv);
	shadowDiv.appendChild(shadowImg);
}

var arrowInfoXmlHttp;
var timeoutId;

function placeArrow(luogo, hideIt){
	//removeArrow();
	if($defined($('arrowDiv'))){
		$('arrowDiv').destroy();
	}
	selectLuogoInList(unescape(luogo));
//	var arrowDiv = getArrowDivAndAnimatedImage();
	var arrowDiv = getArrowDiv();
	//find the map by its id which was assigned in /maps/Map.jsp
	var mapObj = document.getElementById("theMap");
	var mapOffsetLeft = calculateOffset(mapObj, "offsetLeft");
	var mapOffsetTop = calculateOffset(mapObj, "offsetTop");
	
	arrowInfoXmlHttp = createXMLHttpRequest();
    arrowInfoXmlHttp.onreadystatechange = handleStateChangeArrowInfo;
    arrowInfoXmlHttp.open('GET', '/maps/Luogo.jsp?luogo=' + luogo + '&time=' + new Date().getMilliseconds(), true);
    arrowInfoXmlHttp.send(null);
	
	arrowDiv.style.position = 'absolute';
//	//arrowDiv.style.left = mapOffsetLeft + "px";
//	//arrowDiv.style.top = mapOffsetTop + "px";
	arrowDiv.style.left = '0px';
	arrowDiv.style.top = '0px';
	if(hideIt){
		arrowDiv.style.visibility = "hidden";
	}

    
   /* 
    arrowDiv.setStyles({
    	position: 'absolute',
     	left: '0px',
    	top: '0px'
    });
	if(hideIt){
		arrowDiv.setStyle('visibility','hidden');
	}
    */

    
	//IE didn't accept inject
	$('theMapTd').appendChild(arrowDiv);
	
	
//	timeoutId = setTimeout("freezeArrow()", 15900);
	
	return arrowDiv;
	
}//end function

	function clearTimeouts(){
		var timeoutArray = window.timeoutArray;
		if(timeoutArray == null){
			return;
		}
		for(var i = 0; i < timeoutArray.length; i = i + 1){
			if(timeoutArray[i] != null){
				timeoutArray[i] = clearTimeout(timeoutArray[i]);
			}
		}//end for
		window.timeoutArray = null;
	}

	function blinkArrow(){
		
		clearTimeouts();
		
		var interval = 500;
		var repeats = 16;
		
		//save the timeouts so that we can clear them if necessary
		window.timeoutArray = [];
		
		for(var i = 0; i < repeats; i = i + 1){		
			timeoutArray[i] = setTimeout(function(){
				toggleArrowDiv($('arrowDiv'));			
			}, (i + 1) * interval);
		}//end for
		//last time, do a check to make sure it's visible at the moment, if not make it so
		timeoutArray[i + 1] = setTimeout(function(){
			if($('arrowDiv').getStyle('visibility') == 'hidden'){
				$('arrowDiv').setStyle('visibility','visible');
			}			
		},(i + 1) * interval)
		
	}//end blinkArrow()
	
	/**
	 * Toggles arrowDiv visibility
	 * @param arrowDiv
	 */
	function toggleArrowDiv(arrowDiv){
		if(arrowDiv == null){
			return;
		}
		if(arrowDiv.getStyle('visibility') == 'visible'){
			arrowDiv.setStyle('visibility','hidden');
		}else{
			arrowDiv.setStyle('visibility','visible');	
		}
	}

///**
//* replaces the animated arrow with a normal one
//*/
//function freezeArrow(){
//	var arrowImg = document.getElementById("arrowImg");
//	if($defined(arrowImg)){
//		arrowImg.src = arrowPath;
//		if(timeoutId){
//			clearTimeout(timeoutId);
//		}//end if
//	}
//}


function handleStateChangeArrowInfo(){
    if(arrowInfoXmlHttp.readyState == 4){
        if(arrowInfoXmlHttp.status == 200){
        	doArrowInfo(arrowInfoXmlHttp.responseText);
        	blinkArrow();
		}//end if
    }//end if
}//end function

function doArrowInfo(responseText){
	var coordsHolder = JSON.decode(responseText);
	var arrowDivObj = document.getElementById("arrowDiv");
	arrowDivObj.style.position = "absolute";
	//arrowLeftAllow is in /javascript/CoordsHolder.js
	//We've added a border to the map in its style and this has moved the arrow, so we have to allow for it!
	var mapDiv = document.getElementById("mapDiv"); 
	var borderWidth = parseInt(mapDiv.style.borderTopWidth);
	var arrowImg = document.getElementById("arrowImg");

//	arrowDivObj.style.left = (arrowDivObj.offsetLeft + coordsHolder.xCoord - calculateArrowLeftAllow(arrowImg)) + "px";
//	arrowDivObj.style.top = (arrowDivObj.offsetTop + coordsHolder.yCoord - calculateArrowTopAllow(arrowImg)) + "px";
	arrowDivObj.style.left = (coordsHolder.xCoord + 1) + "px";
	arrowDivObj.style.top = (coordsHolder.yCoord - 3) + "px";
	arrowDivObj.style.visibility = "hidden";
}//end function


/**
* Gets the animated arrow and places it in a div
*/
//function getArrowDivAndAnimatedImage(){
//	var arrowDiv = document.createElement("div");
//	arrowDiv.style.visibility = "hidden";
//	arrowDiv.id = "arrowDiv";
//	var arrowImg = document.createElement("img");
//	arrowImg.src = animatedArrowPath;
//	arrowImg.id = "arrowImg";
//	arrowDiv.appendChild(arrowImg);
//	return arrowDiv;
//}

/**
* Gets the  arrow and places it in a div
*/
function getArrowDiv(){
	var arrowDiv = document.createElement("div");
	arrowDiv.style.visibility = "hidden";
	arrowDiv.id = "arrowDiv";
	var arrowImg = document.createElement("img");
	arrowImg.src = arrowPath;
	arrowImg.id = "arrowImg";
	arrowDiv.appendChild(arrowImg);
	return arrowDiv;
}
/**
* Sets the selectedIndex to the position of the current luogo
* in the html select object
*/
function selectLuogoInList(luogo){
	//remove the '+' characters left in the luogo from the encoding
	luogo = replaceString(luogo,"+"," ");
	var luogoSelectObj = document.getElementById("luogoSelect");
	if($defined(luogoSelectObj)){
		for(var i = 0; i < luogoSelectObj.options.length; i = i + 1){
			if(luogoSelectObj.options[i].value == luogo){
				luogoSelectObj.selectedIndex = i;
			}//end if
		}//end for
	}//end if
}//end function()

function showSelectedPlace(){
	var luogoSelectObj = document.getElementById("luogoSelect");
	var selectedLuogo = luogoSelectObj.options[luogoSelectObj.selectedIndex].value;
	if(luogoSelectObj.selectedIndex == 0){
		return;
	}//end if
	var hideIt = true;
	placeArrow(selectedLuogo, hideIt);
}

function placeMap(theHtml){
	removeMapAndShadow();	
	//placeShadow();
	
	var mapDiv = document.createElement("div");
	mapDiv.id = "mapDiv";
	mapDiv.style.visibility = "hidden";
	mapDiv.innerHTML = theHtml;
	mapDiv.style.backgroundColor = "#FFFFFF";
	mapDiv.style.borderStyle = "solid";
	mapDiv.style.borderWidth = "1px";
	mapDiv.style.borderColor = "#666666";
	mapDiv.style.marginTop = "1px";
	mapDiv.style.position = "absolute";
	mapDiv.style.top = mapTopSaved + "px";
	mapDiv.style.left = mapLeftSaved + "px";	
	document.body.appendChild(mapDiv);
	return mapDiv;
}

function removeArrow(){
	removeChildFromDocBody("arrowDiv");
	if(timeoutId){
		clearTimeout(timeoutId);
	}//end if
	
}//end function()

/**
* If they press the link more than once we need to remove
* any existing map
*/
function removeMapAndShadow(){
	removeChildFromDocBody("mapDiv");
	//removeChildFromDocBody("mapShadowDiv");
}//end function

function closeMap(){
	removeArrow();
	removeMapAndShadow();
}

/**
* closes the Timeaway version, changing the button first
* NOT USED, actually, because it looks a bit strange, better to close the map immediately
*/
function closeTMap(){
	$('closeButton').src = "/images/inputs/close_small_hi.gif";
	var myTimer = closeMap.delay(100);
}


