
// parameters
// ext=minx,miny,maxx,maxy : current map extent
// iext=minx,miny,maxx,maxy : inital extent, e.g. from a search started
// sext=minx,miny,maxx,maxy : search extent
// place : place used in PlaceFinder
// splace : place used to do search
// iplace : place used for inital extent
//

// image width
var loadingWidth = 112;
var loadingHeight = 30;
var locatorWidth = 0;
var locatorHeight = 0;
var mapWidth = 0;
var mapHeight = 0;

// map extents
var minx = null;
var miny = null;
var maxx = null;
var maxy = null;
var newMinx = null;
var newMiny = null;
var newMaxx = null;
var newMaxy = null;

// measuring points
var startPointX = null;
var startPointY = null;
var endPointX = null;
var endPointY = null;
var lastStartPointX = null;
var lastStartPointY = null;
var lastEndPointX = null;
var lastEndPointY = null;

// locator map extents
var locatorExtents = new Array();
world = new Array();
world[0] = -180;
world[1] = -111.6;
world[2] = 180;
world[3] = 111.6;
world[4] = "world";
locatorExtents[0] = world;
us = new Array();
us[0] = -127;
us[1] = 18.4;
us[2] = -67;
us[3] = 55.6;
us[4] = "us";
locatorExtents[1] = us;
eu = new Array();
eu[0] = -20;
eu[1] = 29.2;
eu[2] = 60;
eu[3] = 78.8;
eu[4] = "eu";
locatorExtents[2] = eu;
mars = new Array();
mars[0] = -180;
mars[1] = -111.6;
mars[2] = 180;
mars[3] = 111.6;
mars[4] = "mars";
locatorExtents[3] = mars;
var marsPos = 3;

// various
var currentUrl = "";
var size = "s"; // "l"
var marker = "";
var themeId = "";
var marsThemeId = "";
var censusThemeIds = "";
var poiHotSpot = new Array();
var topTen = "";
var mapName = "";
var executeMapRefresh = false;
var orderUrl = "";
var pictureGCSExtent = "";
var state = "";

function clearSettings() {
	startPointX = null;
	startPointY = null;
	endPointX = null;
	endPointY = null;
	mapX = null;
	mapY = null;
	executeMapRefresh = false;

	hideLayer("theZoomBox");
	hideLayer("measureStart");
	hideLayer("measureEnd");
	hideLayer("errorLayer");
	positionLayer("theMap",0,0,"theMapPositionImg");
	clipLayer("theMap",0,0,mapWidth,mapHeight);
	hideLayer("theLoadingImg");
}

//////////////////////////
// map methods
//////////////////////////

// to display a better method name to the user in the status line
function call(pos) {
	if (executeMapRefresh)
		refreshMapNoPageReload();
	else
		openPOILink(poiHotSpot[pos][4],poiHotSpot[pos][5]);
}

// so the switch from one tab to the next is smooth
function callPage(theUrl) {
	top.document.location = theUrl;
}

// refresh map
function refreshMap() {

	refreshUrl = theAppPath + "/viewandcustomize.html?task=getMap" + getRefreshUrl();
	showLayer("theLoadingImg");
	top.document.location = refreshUrl;
}

// refresh map without a page reload
function refreshMapNoPageReload() {

	refreshUrl = theAppPath + "/viewandcustomizepage.html?task=getMap&reload=false" + getRefreshUrl();
	showLayer("theLoadingImg");
	top.HiddenFrame.document.location = refreshUrl;
}

// get URL for a zoom / pan action
function getRefreshUrl() {

	var refreshUrl = "&themeId=" + themeId + "&size=" + size;

	mlayers = getToc(document.mapLayers.mlayer);
	if (mlayers.length > 0)
		refreshUrl += "&maplayers=" + escape(mlayers);
	players = getToc(document.themeFrm.player);
	if (players.length > 0)
		refreshUrl += "&poilayers=" + escape(players);

	refreshUrl += "&state=" + state
			+ addParameterToUrl(currentUrl,"topten")
			+ addParameterToUrl(currentUrl,"place")
			+ addParameterToUrl(currentUrl,"pstart")
			+ addParameterToUrl(currentUrl,"splace")
			+ addParameterToUrl(currentUrl,"start")
			+ addParameterToUrl(currentUrl,"iplace")
			+ addParameterToUrl(currentUrl,"sext")
			+ addParameterToUrl(currentUrl,"iext");

	if (newMinx == null || newMiny == null || newMaxx == null || newMaxy == null)
		refreshUrl += "&ext=" + roundIt(minx)+","+roundIt(miny)+","+roundIt(maxx)+","+roundIt(maxy);
	else
		refreshUrl += "&ext=" + roundIt(newMinx)+","+roundIt(newMiny)+","+roundIt(newMaxx)+","+roundIt(newMaxy);

	// add measuring points
	if (state == "measure"
		&& startPointX != null && startPointY != null
		&& endPointX != null && endPointY != null) {
		refreshUrl += '&startX=' + roundIt(startPointX) + '&startY=' + roundIt(startPointY)
				   + '&endX=' + roundIt(endPointX) + '&endY=' + roundIt(endPointY);
	}

	// add marker und text on map
	// marker=x::y::text~~x::y::text~~...
	if (state == "marker" && mapX != null && mapY != null) {
		markerText = document.mapTools.mText.value;
		if (markerText == "") markerText = " ";
		while (markerText.indexOf("~~") > -1)
			markerText = markerText.replace("~~","~ ~");
		// ^ get encoded and is therefore ok in the cookie; ^ is a delmiter in the cookie
		// * cause problems in the cookie
		while (markerText.indexOf("*") > -1)
			markerText = markerText.replace("*"," ");
		// :: gets encoded and is therefore ok in the cookie, but Java decodes it before parsing
		while (markerText.indexOf("::") > -1)
			markerText = markerText.replace("::",": :");
		if (marker != "")
			marker += "~~";
		marker += roundIt(mapX)+"::"+roundIt(mapY)+"::"+escape(markerText);
	}
	if (marker != "")
		refreshUrl += "&marker="+marker;

	return refreshUrl;
}

// get layer list
function getToc(thisObj) {
	// layerName::[T|F]~~...
	var toc = "";
	if (thisObj != null) {
		if (thisObj.length) {
			for (i=0; i<thisObj.length; i++) {
                var appendSep = true;
				if (thisObj[i].type == "hidden") {
					val = thisObj[i].value;
					name = val.substring(0,val.indexOf("||"));
					toc += name + "::";
					vis = val.substring(val.indexOf("||")+2,val.length);
					if (vis == "on")
						toc += "T";
					else
						toc += "F";
				} else if (thisObj[i].checked == true) {
					toc += thisObj[i].value + "::";
					toc += "T";
                } else if (thisObj.type == "select-one" || thisObj.type == "select-multiple") {
                    if (thisObj.options[i].value.length) {
                        toc += thisObj.options[i].value + "::";
                        if (thisObj.options[i].selected)
                            toc += "T";
                        else
                            toc += "F";
                    } else {
                        appendSep = false;
                    }
				} else {
					toc += thisObj[i].value + "::";
					toc += "F";
				}
				if (appendSep && i < thisObj.length-1)
				   toc += "~~";
			}
		} else {
			if (thisObj.type == "hidden") {
				val = thisObj.value;
				name = val.substring(0,val.indexOf("||"));
				toc += name + "::";
				vis = val.substring(val.indexOf("||")+2,val.length);
				if (vis == "on")
					toc += "T";
				else
					toc += "F";
			} else if (thisObj.checked == true) {
				toc += thisObj.value + "::";
				toc += "T";
			} else {
				toc += thisObj.value + "::";
				toc += "F";
			}
		}
	}
	return toc;
}

// user wants to measure a distane
function customMapClick(mapX,mapY) {
	if (state == "measure") {
		if (startPointX == null && startPointY == null) {
			startPointX = mapX;
			startPointY = mapY;
			document.getElementById("messageArea").innerHTML = MEASURE_END;
			// display start marker
	   	    positionLayer("measureStart",currentX-(document.getElementById("measureStartImg").width/2),currentY-(document.getElementById("measureStartImg").height/2),"theMapPositionImg");
			showLayer("measureStart");
		} else if (endPointX == null && endPointY == null) {
			endPointX = mapX;
			endPointY = mapY;
			document.getElementById("messageArea").innerHTML = HOWTO_MEASURE;
	   	    positionLayer("measureEnd",currentX-(document.getElementById("measureEndImg").width/2),currentY-(document.getElementById("measureEndImg").height/2),"theMapPositionImg");
			showLayer("measureEnd");
			refreshMapNoPageReload();
		}
	} else if (state == "marker") {
		refreshMapNoPageReload();
	}
}

// tool buttons
function setState(mode) {
	if (state == mode)
		return;
	state = mode;
	if (mode == "zoomBox") {
		document.mapTools.tool.checked = false;
		setZoomBoxEvents();
		hideLayer("measureStart");
		hideLayer("measureEnd");
		document.getElementById("messageArea").innerHTML = HOWTO_ZOOMBOX;
		document.getElementById("rubberbandTool").src = "images/maptool_rubberband_on.gif";
		document.getElementById("zoominTool").src = "images/maptool_zoomin_off.gif";
		document.getElementById("zoomoutTool").src = "images/maptool_zoomout_off.gif";
		document.getElementById("panTool").src = "images/maptool_pan_off.gif";
		if (document.getElementById("rulerTool"))
			document.getElementById("rulerTool").src = "images/maptool_ruler_off.gif";
	} else if (mode == "zoomIn") {
		document.mapTools.tool.checked = false;
		setZoomInEvents();
		hideLayer("measureStart");
		hideLayer("measureEnd");
		document.getElementById("messageArea").innerHTML = HOWTO_ZOOMIN;
		document.getElementById("rubberbandTool").src = "images/maptool_rubberband_off.gif";
		document.getElementById("zoominTool").src = "images/maptool_zoomin_on.gif";
		document.getElementById("zoomoutTool").src = "images/maptool_zoomout_off.gif";
		document.getElementById("panTool").src = "images/maptool_pan_off.gif";
		if (document.getElementById("rulerTool"))
			document.getElementById("rulerTool").src = "images/maptool_ruler_off.gif";
	} else if (mode == "zoomOut") {
		document.mapTools.tool.checked = false;
		setZoomOutEvents();
		hideLayer("measureStart");
		hideLayer("measureEnd");
		document.getElementById("messageArea").innerHTML = HOWTO_ZOOMOUT;
		document.getElementById("rubberbandTool").src = "images/maptool_rubberband_off.gif";
		document.getElementById("zoominTool").src = "images/maptool_zoomin_off.gif";
		document.getElementById("zoomoutTool").src = "images/maptool_zoomout_on.gif";
		document.getElementById("panTool").src = "images/maptool_pan_off.gif";
		if (document.getElementById("rulerTool"))
			document.getElementById("rulerTool").src = "images/maptool_ruler_off.gif";
	} else if (mode == "pan") {
		document.mapTools.tool.checked = false;
		setPanEvents();
		hideLayer("measureStart");
		hideLayer("measureEnd");
		document.getElementById("messageArea").innerHTML = HOWTO_PAN;
		document.getElementById("rubberbandTool").src = "images/maptool_rubberband_off.gif";
		document.getElementById("zoominTool").src = "images/maptool_zoomin_off.gif";
		document.getElementById("zoomoutTool").src = "images/maptool_zoomout_off.gif";
		document.getElementById("panTool").src = "images/maptool_pan_on.gif";
		if (document.getElementById("rulerTool"))
			document.getElementById("rulerTool").src = "images/maptool_ruler_off.gif";
	} else if (mode == "measure") {
		startPointX = null;
		startPointY = null;
		endPointX = null;
		endPointY = null;
		document.mapTools.tool.checked = false;
		setCustomMapClickEvents();
		document.getElementById("messageArea").innerHTML = HOWTO_MEASURE;
		document.getElementById("rubberbandTool").src = "images/maptool_rubberband_off.gif";
		document.getElementById("zoominTool").src = "images/maptool_zoomin_off.gif";
		document.getElementById("zoomoutTool").src = "images/maptool_zoomout_off.gif";
		document.getElementById("panTool").src = "images/maptool_pan_off.gif";
		if (document.getElementById("rulerTool"))
			document.getElementById("rulerTool").src = "images/maptool_ruler_on.gif";
		else {
			hideLayer("measureStart");
			hideLayer("measureEnd");
			document.getElementById("messageArea").innerHTML = HOWTO_ZOOMBOX;
			document.getElementById("rubberbandTool").src = "images/maptool_rubberband_on.gif";
		}
	} else if (mode == "marker") {
		document.getElementById("messageArea").innerHTML = HOWTO_MARKER;
		document.mapTools.tool.checked = true;
		setCustomMapClickEvents();
		hideLayer("measureStart");
		hideLayer("measureEnd");
		document.getElementById("rubberbandTool").src = "images/maptool_rubberband_off.gif";
		document.getElementById("zoominTool").src = "images/maptool_zoomin_off.gif";
		document.getElementById("zoomoutTool").src = "images/maptool_zoomout_off.gif";
		document.getElementById("panTool").src = "images/maptool_pan_off.gif";
		if (document.getElementById("rulerTool"))
			document.getElementById("rulerTool").src = "images/maptool_ruler_off.gif";
	}
}

// zoom action
function zoom(percent,fullWidth) {

	centerX = (minx+maxx)/2.0;
	centerY = (miny+maxy)/2.0;
	width = fullWidth * percent;
	widthhalf = width/2.0;
	widthquart = width/4.0;
	newMinx = centerX - widthhalf;
	newMaxx = centerX + widthhalf;
	// server takes care of proper aspect ratio
	newMiny = centerY - widthquart;
	newMaxy = centerY + widthquart;
	refreshMapNoPageReload();
}

// pan action
function pan(xPercent,yPercent) {

	// move %
	valueX = xPercent/100;
	valueY = yPercent/100;

	var width = Math.abs(maxx-minx);
	var height = Math.abs(maxy-miny);

	newMinx = minx + valueX*width;
	newMiny = miny + valueY*height;
	newMaxx = maxx + valueX*width;
	newMaxy = maxy + valueY*height;

	refreshMapNoPageReload();
}

// delete text from map
function clearMarker() {
	marker = "";
	refreshMapNoPageReload();
}

//////////////////////////
// save methods
//////////////////////////

// ask the user for the name of the map to be saved
function saveMap() {
	theUrl = theAppPath + "/saveview.html?task=getSaveMap&mapname=" +escape(mapName) + getParameters2();
	top.document.location.href = theUrl;
}

// save a map in a cookie
function saveMapAs(mapName) {
	// &maplayers=Major Cities::F~~Administrative Boundaries::T~~...
	// &poilayers=Flags & Facts::F
	// marker=x::y::text~~x::y::text~~...
	// Cookie format old: map name|path&id&size&left&bottom&right&top^
	// Cookie format: map name||themId|minx,miny,maxx,maxy|size|maplayers|poiLayers|marker^
	var saveString = mapName;
	saveString += "||"+ getValue(currentUrl,"themeId");
	saveString += "|"+ getValue(currentUrl,"ext");
	saveString += "|"+ getValue(currentUrl,"size");
	saveString += "|"+ getValue(currentUrl,"maplayers");
	saveString += "|"+ getValue(currentUrl,"poilayers");
	saveString += "|"+ getValue(currentUrl,"marker");

	// cookie limit is 4KB (4096 is too long)
	if ((getCookieSize() + saveString.length) >= 4000)
		alert(COOKIE_TOO_BIG);
	else
		storeInCookie(saveString);
}

function buildUrlFromSavedMap(savedMapString) {
	// format: themeId|minx,miny,maxx,maxy|size|maplayers|poiLayers|marker^
	//savedMap = splitString(savedMapString,'|'); doesn't seem to work right...
	savedMap = new Array();
	count = 0;
	pos1 = 0;
	pos2 = savedMapString.indexOf("|");
	while (pos2 > -1 && count <= 4) {
		savedMap[count] = savedMapString.substring(pos1,pos2);
		pos1 = pos2+1;
		pos2 = savedMapString.indexOf("|",pos1);
		count++;
	}
	savedMap[5] = savedMapString.substring(pos1,savedMapString.length);
	theUrl = theAppPath + "/viewandcustomize.html?task=getMap"
		 + add("themeId",savedMap[0])
		 + add("ext",savedMap[1])
		 + add("size",savedMap[2])
		 + add("maplayers",savedMap[3])
		 + add("poilayers",savedMap[4])
		 + add("marker",savedMap[5]);
	return theUrl;
}

function deleteSavedMaps(obj) {
	hasOne = false;
	for (i = obj.length-1; i >= 0; i--) {
		if (obj[i].type == "checkbox") {
			if (obj[i].checked) {
				//savedMaps.splice(i,1);  IE on Mac doesn't support that
				tmpArray = new Array();
				count = 0;
				for (k = 0; k < savedMaps.length; k++) {
					if (k != i) {
						tmpArray[count] = savedMaps[k];
						count++;
					}
				}
				savedMaps = tmpArray;
				hasOne = true;
			}
		}
	}
	if (hasOne) {
		cookieText = "";
		for (i = 0; i < savedMaps.length; i++) {
			if (cookieText != "")
				cookieText += "^";
			cookieText += savedMaps[i];
		}
		SetCookie('0',cookieText);
	}
	return hasOne;
}

//////////////////////////
// theme selection lists
//////////////////////////

function selectTheme(index) {
    var id = document.themeFrm.player.options[index].value;
    if (!isPictureMap(themeId)) {
        document.getElementById("titleText").innerHTML = getThemeTitle(index);
        document.getElementById("themeText").innerHTML = getThemeText(id);
    }
    
    if (id) {
        if (isPictureMap(themeId)) {
            viewPoiTheme(id);
        } else {
            refreshMapNoPageReload();
        }
    }
}

function selectThemeFromErrorPage(id) {
    if (id) {
        viewPoiTheme(id);
    }
}

function getThemeTitle(index) {
    if (index == 0)
        return mapName;
    else
        return document.themeFrm.player.options[index].text;
}

function getThemeText(id) {
    // default value
    var value = "Select a theme&#151;such as animals or religions&#151;from the pull-down menu above, then zoom in and out to find and click the icons on the map for photos, cultural profiles, audio clips, and much more.";
    
    if (id == "animal")
        value = "Explore the wild side of the planet, from polar bears in the Arctic to hippos in Zambia. Zoom in and out to find and click the icons on the map for photos, profiles, and more.";
    else if (id == "countryprofile")
        value = "Get the facts on every country, state, and province, from population statistics to flags and beyond. Zoom in and out to find and click the icons on the map.";
    else if (id == "food")
        value = "<b>Available for Asia only</b><br><br>Rice and bread form the culinary backdrop for a continent rich in fruits, spices, and tradition. Zoom in and out to find and click the icons on the map for photos, profiles, and more.";
    else if (id == "history")
        value = "<b>Available for Asia only</b><br><br>Asia has been the site of some of the most important events in history&#151;from the first civilizations in Mesopotamia to the collapse of the Soviet Union. Zoom in and out to find and click the icons on the map for photos, profiles, and more.";
    else if (id == "language")
        value = "<b>Available for Asia only</b><br><br>The best indicator of the health of the world's cultures may be the state of its languages. A few languages are growing. Many more are fading. Zoom in and out to find and click the icons on the map for photos, profiles, and more.";
    else if (id == "naturalworld")
        value = "<b>Available for Asia only</b><br><br>Rich in natural resources, Asia has the highest point on Earth (Mount Everest) and the lowest (the Dead Sea)&#151;plus rain forests, deserts, and everything in between. Zoom in and out to find and click the icons on the map for photos, profiles, and more.";
    else if (id == "xpeditions")
        value = "Need a map for a school report, handout, or presentation? Use these easy-print, black-and-white maps from our Xpeditions Atlas. Zoom in and out to find and click the icons on the map.";
    else if (id == "peoples")
        value = "<b>Available for Asia only</b><br><br>From Japan to Georgia, Mongolia to Malaysia, Asia is home to more ethnic groups than any other major region. Zoom in and out to find and click the icons on the map for photos, profiles, and more.";
    else if (id == "religion")
        value = "<b>Available for Asia only</b><br><br>The three most popular religions&#151;Christianity, Buddhism, and Islam&#151;all began in Asia, as did many more. Zoom in and out to find and click the icons on the map for photos, profiles, and more.";
    else if (id == "photos")
        value = "See the world like National Geographic photographers do&#151;travel the globe, snapshot by snapshot. Find and click the photo icons on the map.";
    else if (id == "newslayer")
        value = "Put the news into (geographic) perspective. Keep current on archaeology, animals, the environment, and more. Zoom in and out to find and click the news icons on the map.";
	else if (id == "sound")
        value = "National Geographic asked teachers and students to record the sounds of their communities in connection with the 2004-2005 <a href=http://www.nationalgeographic.com/geographyaction>Geography Action!</a> theme, <i>Culture: The Sound of Place.</i>  Click icons on the map to read classroom-contributed profiles and discover what they heard. ";

    return value;
}

//////////////////////////
// various methods
//////////////////////////

// make large or small map
function resizeMap() {
	if (size == "s")
		size = "l";
	else
		size = "s";
	refreshMap(true);
}

function eMailMap() {
	top.document.location.href = getEMailUrl2(mapName);
}

function openPOILink(poiUrl, poiType) {
    if (poiUrl.indexOf("http") != -1)
	    window.open(poiUrl);
    else
        window.open(poiUrl + "?" + getParameters2());
}

// call print page
function printMap() {
	refreshUrl = theAppPath + "/print.html?task=getMap&print=true"
			+ "&mapname=" + escape(mapName)
			+ addParameterToUrl(currentUrl,"themeId")
			+ addParameterToUrl(currentUrl,"maplayers")
			+ addParameterToUrl(currentUrl,"poilayers")
			+ addParameterToUrl(currentUrl,"ext");

	if (lastStartPointX != null && lastStartPointY != null
		&& lastEndPointX != null && lastEndPointY != null) {
		refreshUrl += '&startX=' + roundIt(lastStartPointX) + '&startY=' + roundIt(lastStartPointY)
					+ '&endX=' + roundIt(lastEndPointX) + '&endY=' + roundIt(lastEndPointY);
	}

	refreshUrl += addParameterToUrl(currentUrl,"marker");

	window.open(refreshUrl,"MapMachinePrint","toolbar=1,location=1,directories=1,menubar=1,status=1,scrollbars=yes,resizable=1,width=685,height=550"+popupPosition());
}

function getOrderUrl() {
	newOrderUrl = orderUrl;
	if (newOrderUrl.indexOf("#MINX#") > -1) {
		// insert extent values
		newOrderUrl = newOrderUrl.replace("#MINX#",minx);
		newOrderUrl = newOrderUrl.replace("#MINY#",miny);
		newOrderUrl = newOrderUrl.replace("#MAXX#",maxx);
		newOrderUrl = newOrderUrl.replace("#MAXY#",maxy);
	}
	if (newOrderUrl.indexOf("#CX#") > -1) {
		newOrderUrl = newOrderUrl.replace("#CX#",((minx+maxx)/2.0));
		newOrderUrl = newOrderUrl.replace("#CY#",((miny+maxy)/2.0));
	}
	if (newOrderUrl.indexOf("#LEVEL-M-") > -1) {
		// has levels in meters per pixel
		start = newOrderUrl.indexOf("#LEVEL-M-");
		end = newOrderUrl.indexOf("#",start+1);
		levels = newOrderUrl.substring(start+9,end).split(",");
		level = 1; // most zoomed out
		degPerPixel = (maxx-minx)/mapWidth;
		for (i = 0; i < levels.length; i++) {
			if ((levels[i] * 0.000008993220293) >= degPerPixel) {
				level = levels.length-i;
				break;
			}
		}
		newOrderUrl = newOrderUrl.substring(0,start) + level + newOrderUrl.substring(end+1,newOrderUrl.length);
	}
	return newOrderUrl;
}

function openOrderPage() {
	window.open(getOrderUrl());
}

// display legend of map
function getLegend() {
	refreshUrl = theAppPath + "/viewandcustomizepage.html?task=getMap"
			+ addParameterToUrl(currentUrl,"themeId")
			+ addParameterToUrl(currentUrl,"ext")
			+ addParameterToUrl(currentUrl,"size")
			+ addParameterToUrl(currentUrl,"maplayers")
			+ addParameterToUrl(currentUrl,"poilayers")
			+ "&legend=true";

	window.open(refreshUrl,"MapMachineLegend","scrollbars,width=550,height=500"+popupPosition());
}

function getPLegend(fileName) {
    window.open(theAppPath+"/"+fileName,"MapMachineLegend","resizable,scrollbars,width=550,height=500"+popupPosition());
}

function openMapSource() {
	window.open(theAppPath+"/mapsource.html","MapMachineMapSource","scrollbars,width=550,height=350"+popupPosition());
}

function openGeneralOrderPage() {
	callPage(getGeneralOrderUrl());
}

//////////////////////////
// search methods
//////////////////////////

// &place=		used for making a PlaceFinder search (display on place_list.jsp)
// &splace=		used from PlaceFinder results and making a map search (display on map_list.jsp)
// &iplace=		used from map search results and made a map with it (display on map.jsp)

// do a gazetteer search
// !! a copy of this method is in basics.js called FindAPlace() !!
var searchPlaceName = "";
function findPlace(placeName) {
	place = document.search.searchText.value;
	while (place.substring(0,1) == " ")
		place = place.substring(1,place.length);
	while (place.substring(place.length-1,place.length) == " ")
		place = place.substring(0,place.length-1);
	document.search.searchText.value = place;
	if (place.length > 0) {
		refreshUrl = theAppPath + "/searchandbrowse.html?task=getSearchPlace"
			+ addParameterToUrl(currentUrl,"themeId")
			+ addParameterToUrl(currentUrl,"ext")
			+ addParameterToUrl(currentUrl,"sext")
			+ addParameterToUrl(currentUrl,"iext")
			+ addParameterToUrl(currentUrl,"size")
			+ addParameterToUrl(currentUrl,"maplayers")
			+ addParameterToUrl(currentUrl,"poilayers")
			+ addParameterToUrl(currentUrl,"topten")
			+ addParameterToUrl(currentUrl,"splace")
			+ addParameterToUrl(currentUrl,"start")
			+ addParameterToUrl(currentUrl,"iplace")
			+ "&place="+escape(place);

		value = "all";
		if (document.search.searchOptions) {
			for (i = 0; i < document.search.searchOptions.length; i++)  {
				if (document.search.searchOptions[i].checked) {
					value = document.search.searchOptions[i].value;
					break;
				}
			}
		}
		if (value == "this")
			refreshUrl += "&search=extent";

		refreshUrl += addParameterToUrl(currentUrl,"marker");
		top.document.location = refreshUrl;
	}
}

// user clicked on another page number on the place search results
// do the search again and return a different subset of the results
function placePage(start) {
	refreshUrl = theAppPath + "/searchandbrowse.html?task=getSearchPlace"
			+ addParameterToUrl(currentUrl,"themeId")
			+ addParameterToUrl(currentUrl,"ext")
			+ addParameterToUrl(currentUrl,"size")
			+ addParameterToUrl(currentUrl,"maplayers")
			+ addParameterToUrl(currentUrl,"poilayers")
			+ addParameterToUrl(currentUrl,"topten")
			+ addParameterToUrl(currentUrl,"search")
			+ addParameterToUrl(currentUrl,"sext")
			+ addParameterToUrl(currentUrl,"iext")
			+ addParameterToUrl(currentUrl,"place")
			+ addParameterToUrl(currentUrl,"splace")
			+ addParameterToUrl(currentUrl,"iplace");
	if (start > 0)
		refreshUrl += "&pstart=" + start;
	refreshUrl += addParameterToUrl(currentUrl,"marker");
	top.document.location = refreshUrl;
}

// find all the maps for a certain search extent
var placeArray = new Array();
function findMapsForPlace(iminx,iminy,imaxx,imaxy,pos) {
	placeName = placeArray[pos];
	refreshUrl = theAppPath + "/searchandbrowse.html?task=getSearchMap"
			+ addParameterToUrl(currentUrl,"themeId")
			+ addParameterToUrl(currentUrl,"ext")
			+ addParameterToUrl(currentUrl,"size")
			+ addParameterToUrl(currentUrl,"maplayers")
			+ addParameterToUrl(currentUrl,"poilayers")
			+ addParameterToUrl(currentUrl,"place")
			+ addParameterToUrl(currentUrl,"topten")
			+ addParameterToUrl(currentUrl,"iplace")
			+ addParameterToUrl(currentUrl,"iext")
			+ "&splace="+escape(placeName)
			+ "&sext=" + roundIt(iminx)+","+roundIt(iminy)+","+roundIt(imaxx)+","+roundIt(imaxy)
			+ addParameterToUrl(currentUrl,"marker");
	top.document.location = refreshUrl;
}

// find all the maps for a certain search extent
function findMapsForCurrentMap() {
	refreshUrl = theAppPath + "/searchandbrowse.html?task=getSearchMap"
			+ addParameterToUrl(currentUrl,"themeId")
			+ addParameterToUrl(currentUrl,"ext")
			+ addParameterToUrl(currentUrl,"size")
			+ addParameterToUrl(currentUrl,"maplayers")
			+ addParameterToUrl(currentUrl,"poilayers")
			+ addParameterToUrl(currentUrl,"topten")
			+ addParameterToUrl(currentUrl,"place")
			+ addParameterToUrl(currentUrl,"iplace")
			+ addParameterToUrl(currentUrl,"iext");
	if (isPictureMap(themeId))
		refreshUrl += "&sext=" + pictureGCSExtent;
	else if (themeId != marsThemeId)
		refreshUrl += "&sext=" + roundIt(minx)+","+roundIt(miny)+","+roundIt(maxx)+","+roundIt(maxy);
	refreshUrl += addParameterToUrl(currentUrl,"marker");
	top.document.location = refreshUrl;
}

// user clicked on another page number on the search results
// do the search again and return a different subset of the results
function page(start) {
	placeName = searchPlaceName;
	refreshUrl = theAppPath + "/searchandbrowse.html?task=getSearchMap"
			+ addParameterToUrl(currentUrl,"themeId")
			+ addParameterToUrl(currentUrl,"size")
			+ addParameterToUrl(currentUrl,"maplayers")
			+ addParameterToUrl(currentUrl,"poilayers")
			+ addParameterToUrl(currentUrl,"ext")
			+ addParameterToUrl(currentUrl,"topten")
			+ addParameterToUrl(currentUrl,"place")
			+ addParameterToUrl(currentUrl,"iplace")
			+ addParameterToUrl(currentUrl,"iext")
			+ "&splace=" + escape(placeName)
			+ addParameterToUrl(currentUrl,"sext");
	if (start > 0)
		refreshUrl += "&start=" + start;
	refreshUrl += addParameterToUrl(currentUrl,"marker");
	top.document.location = refreshUrl;
}

// open a map from a search result
function openMap(id) {
	placeName = searchPlaceName;
	var refreshUrl = theAppPath + "/viewandcustomize.html?task=getMap&themeId=" + id
			+ addParameterToUrl(currentUrl,"size")
			+ addParameterToUrl(currentUrl,"start")
			+ "&topten=" + topTen
			+ addParameterToUrl(currentUrl,"place")
			+ "&iplace=" + escape(placeName)
			+ addParameterToUrl(currentUrl,"sext")
			+ addParameterToUrl(currentUrl,"splace")
			+ "&iext=" + getValue(currentUrl,"sext");
	if (!isPictureMap(id)) {
		refreshUrl += "&ext=" + getValue(currentUrl,"sext");
	}
	top.document.location = refreshUrl;
}

//////////////////////////
// locator map methods
//////////////////////////

// draw extent box on locator map
function drawExtentBox() {

	pixelWidth = document.getElementById("theLocatorPositionImg").width;
	pixelHeight = document.getElementById("theLocatorPositionImg").height;

	if (themeId.substring(0,1) != 'p') {
		if (themeId == marsThemeId) {
			locatorMinX = locatorExtents[marsPos][0];
			locatorMinY = locatorExtents[marsPos][1];
			locatorMaxX = locatorExtents[marsPos][2];
			locatorMaxY = locatorExtents[marsPos][3];
			name = "mars";
		} else {
			locatorMinX = locatorExtents[0][0];
			locatorMinY = locatorExtents[0][1];
			locatorMaxX = locatorExtents[0][2];
			locatorMaxY = locatorExtents[0][3];
			name = "world";
			for (i = 1; i < locatorExtents.length-1; i++) {
				if (minx > locatorExtents[i][0] && maxx < locatorExtents[i][2]
					&& miny > locatorExtents[i][1] && maxy < locatorExtents[i][3]) {
					locatorMinX = locatorExtents[i][0];
					locatorMinY = locatorExtents[i][1];
					locatorMaxX = locatorExtents[i][2];
					locatorMaxY = locatorExtents[i][3];
					name = locatorExtents[i][4];
					break;
				}
			}
		}
		document.getElementById("theLocatorPositionImg").src = "images/locator_"+name+".gif";
	}

	areaMap = (maxx-minx)*(maxy-miny);
	areaFullMap = (locatorMaxX-locatorMinX)*(locatorMaxY-locatorMinY);

	if (areaMap < areaFullMap) {
		ratio = (Math.max(Math.min(minx,locatorMaxX),locatorMinX) - locatorMinX) / (locatorMaxX-locatorMinX);
		startX = Math.round(ratio * pixelWidth);
		ratio = (Math.max(Math.min(miny,locatorMaxY),locatorMinY) - locatorMinY) / (locatorMaxY-locatorMinY);
		startY = pixelHeight - Math.round(ratio * pixelHeight);
		ratio = (Math.max(Math.min(maxx,locatorMaxX),locatorMinX) - locatorMinX) / (locatorMaxX-locatorMinX);
		endX = Math.round(ratio * pixelWidth);
		ratio = (Math.max(Math.min(maxy,locatorMaxY),locatorMinY) - locatorMinY) / (locatorMaxY-locatorMinY);
		endY = pixelHeight - Math.round(ratio * pixelHeight);

		if (endX-startX < 4) {
			centerX = Math.round((endX+startX)/2);
			startX = centerX-2;
			endX = centerX+2;
		}
		if (startY-endY < 4) {
			centerY = Math.round((startY+endY)/2);
			endY = centerY-2;
			startY = centerY+2;
		}

		if (startX < 0) startX = 0;
		if (startX > pixelWidth) startX = pixelWidth;
		if (startY < 0) startY = 0;
		if (startY > pixelHeight) startY = pixelHeight;
		if (endX < 0) endX = 0;
		if (endX > pixelWidth) endX = pixelWidth;
		if (endY < 0) endY = 0;
		if (endY > pixelHeight) endY = pixelHeight;

	    showLayer("theLocatorMap");
		if (themeId.substring(0,1) == 'p') {
			if ((startX == 0 && endX == pixelWidth)
				|| (startY == pixelHeight && endY == 0)) {
	 		    hideLayer("extentBox");
			} else {
				clipBox("extentBox", startX, startY, endX, endY, "theLocatorPositionImg");
	 	    	showLayer("extentBox");
			}
		} else {
			if (startX > 0 || startY < pixelHeight || endX < pixelWidth || endY > 0) {
				clipBox("extentBox", startX, startY, endX, endY, "theLocatorPositionImg");
	 	    	showLayer("extentBox");
			} else {
	 		    hideLayer("extentBox");
			}
		}
	} else {
	    showLayer("theLocatorMap");
	    hideLayer("extentBox");
	}
}

//////////////////////////
// utility methods
//////////////////////////

function removeKey(string,key) {
	if (string.indexOf(key) != -1) {
		start =  string.indexOf(key);
		end =  string.indexOf("&",start+2);
		if (string.substring(start-1,start) == "&")
			start = start-1;
		if (end == -1)
			string = string.substring(0,start);
		else
			string = string.substring(0,start)+string.substring(end,string.length);
	} else if (key.substring(0,1) == "&") {
		key = key.substring(1,key.length);
		if (string.indexOf("?"+key) != -1) {
			start =  string.indexOf("?"+key)+1;
			end =  string.indexOf("&",start+2);
			if (end == -1)
				string = string.substring(0,start);
			else
				string = string.substring(0,start)+string.substring(end+1,string.length);
		}
	}
	return string;
}

function addParameterToUrl(str,search) {
	value = getValue(str,search);
	if (value != "")
		return ("&"+search+"="+value);
	return "";
}

function getValue(str,search) {
	var s = str.indexOf("&"+search+"=",0);
	if (s == -1)
		s = str.indexOf("?"+search+"=",0);
	if (s == -1) return "";
	var e = str.indexOf("&",s+2);
	if (e == -1) e = str.length;
	return str.substring(s+search.length+2,e);
}

function add(parameterName,value) {
	if (value != null && value != "")
		return "&"+parameterName+"="+value;
	return "";
}

function splitString(string,splitChar) {
	var array = new Array();
	pos = string.indexOf(splitChar);
	count = 0;
	while (pos >= 0) {
		array[count] = string.substring(0,pos);
		string = string.substring(pos+1,string.length);
		pos = string.indexOf(splitChar);
		count++;
	}
    // add last item
    if (count > 0 && string.length > 0) {
        array[count] = string;
    }
	return array;
}

function roundIt(value) {
	return Math.round(value*1000000)/1000000;
}

function isPictureMap(id) {
	if (id.substring(0,1) == "p")
		return true;
	return false;
}

function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function popupPosition() {
	position = "";
	if (navigator.appName.indexOf("Netscape")>=0)
		position = ",screeny="+(window.screenY+100)+",screenx="+window.screenX;
	else if (navigator.appName.indexOf("Microsoft Internet Explorer")>=0)
		position = ",top="+window.screenTop+",left="+window.screenLeft;
	return position;
}

function doNothing() {
}