/*----------------------------------------------------------
*/

  //var log = new Logging();
  //log.open();
  var naviciAjaxApi = null;
 var searchWithNameSuggestionList;
  var categories;
  var printMenu=null; 
  var isBlur=false;
 var isFullScreen = false;
  
  var lmo_Id = null;  
  var routeLayerOnId = null;
  
  var measureDistTool = null;
  var isMeasureOn = false;
  var isPointLayersDisabled = false;
  var isRouteLayersDisabled = false;
  
  var savePrintFunction = null;
  var savePrintStyle = null;
  var printEnabled = true;
  var browser = util.currentBrowser;  

  //Max size for ie6 when margins are 5.
/*
  var a4_width_portrait = 690;
  var a4_height_portrait = 930;
  var a4_width_landscape = 1020;
  var a4_height_landscape = 580;
  
  var a3_width_portrait = 1000;
  var a3_height_portrait = 1350;
var a3_width_landscape = 1440;
  var a3_height_landscape = 890;
 */
  
  var a4_width_portrait = 680;
  var a4_height_portrait = 900;
  var a4_width_landscape = 1000;
  var a4_height_landscape = 580;


  var a3_width_portrait = 1000;
  var a3_height_portrait = 1370;
  var a3_width_landscape = 1470;
  var a3_height_landscape = 905;

if(util.isIE && browser.version < 7){

  var a4_height_portrait = 830;
  var a4_width_portrait = 600;
  var a4_width_landscape = 925;
  var a4_height_landscape = 500;

  var a3_width_portrait = 925;
  var a3_height_portrait = 1305;
  var a3_width_landscape = 1395;
  var a3_height_landscape = 835;

}


  function main(language){
  	AjaxMapsConfig.LANGUAGE = language;
	var poiTitle = null;
  
  	
  
	switch(language){
		case "se":
			//Remove default values and add new ones.
			AjaxMapsConfig.PRINT_MENU_FORMATS.pop();
			AjaxMapsConfig.PRINT_MENU_FORMATS.pop();
			AjaxMapsConfig.PRINT_MENU_FORMATS.push({type: "Portrait", width: a4_width_portrait, height: a4_height_portrait, label: "Vertikal", printCss: "A4Portrait"});
			AjaxMapsConfig.PRINT_MENU_FORMATS.push({type: "Landscape", width: a4_width_landscape, height: a4_height_landscape, label: "Horisontal", printCss: "A4Landscape"});
			AjaxMapsConfig.PRINT_MENU_BUTTON = "Skriv ut";
			AjaxMapsConfig.PRINT_MENU_BUTTON_CLOSE = "Stäng";
			AjaxMapsConfig.PRINT_MENU_BUTTON_PRINT = "Skriv ut";
			AjaxMapsConfig.PRINT_MENU_PAPER_ORIENTATION = "Placering av utskrift";
			AjaxMapsConfig.PRINT_MENU_PAPER_SIZE = "Pappersformat";
			AjaxMapsConfig.PRINT_MENU_META_ELECT ="Skriv ut uppgifter om platserna?";
			AjaxMapsConfig.PRINT_MENU_YES ="Ja";
			AjaxMapsConfig.PRINT_MENU_NO ="Nej";
			AjaxMapsConfig.PRINT_MENU_INDEX_ELECT ="Skriv ut indexkarta?";
			AjaxMapsConfig.PRINT_MENU_LEGEND_ELECT ="Skriv ut teckenförklaringen?";
			AjaxMapsConfig.PRINT_MENU_HEADERINPUT ="Sätt rubrik på utskriften";
			AjaxMapsConfig.PRINT_MENU_HEADERINPUT_DEFAULT ="";
			AjaxMapsConfig.POI_POPUP_LINK_NAME ="Info";			
			poiTitle = "Info";
			CoordTxtE ="o ";
			CoordTxtN ="n ";			
			break;
		case "fi":
			//Remove default values and add new ones.
			AjaxMapsConfig.PRINT_MENU_FORMATS.pop();
			AjaxMapsConfig.PRINT_MENU_FORMATS.pop();
			AjaxMapsConfig.PRINT_MENU_FORMATS.push({type: "Portrait", width: a4_width_portrait, height: a4_height_portrait, label: "Pysty", printCss: "A4Portrait"});
			AjaxMapsConfig.PRINT_MENU_FORMATS.push({type: "Landscape", width: a4_width_landscape, height: a4_height_landscape, label: "Vaaka", printCss: "A4Landscape"});
			AjaxMapsConfig.PRINT_MENU_BUTTON = "Tulosta";
			AjaxMapsConfig.PRINT_MENU_BUTTON_CLOSE = "Sulje";
			AjaxMapsConfig.PRINT_MENU_BUTTON_PRINT = "Tulosta";
			AjaxMapsConfig.PRINT_MENU_PAPER_ORIENTATION = "Tulosteen asettelu";
			AjaxMapsConfig.PRINT_MENU_PAPER_SIZE = "Paperin koko";
			AjaxMapsConfig.PRINT_MENU_META_ELECT ="Tulostetaanko kohteiden tiedot?";
			AjaxMapsConfig.PRINT_MENU_YES ="Kyllä";
			AjaxMapsConfig.PRINT_MENU_NO ="Ei";
			AjaxMapsConfig.PRINT_MENU_INDEX_ELECT ="Tulosta indeksikartta?";
			AjaxMapsConfig.PRINT_MENU_LEGEND_ELECT ="Tulosta merkkien selitteet?";
			AjaxMapsConfig.PRINT_MENU_HEADERINPUT ="Kirjoita tulosteen otsikko";
			AjaxMapsConfig.PRINT_MENU_HEADERINPUT_DEFAULT ="";
			AjaxMapsConfig.POI_POPUP_LINK_NAME ="Tietoa kohteesta";
			poiTitle = "Kohteen tiedot";
			CoordTxtE ="i ";
			CoordTxtN ="p ";
			break;
		case "en":
			//Remove default values and add new ones.
			AjaxMapsConfig.PRINT_MENU_FORMATS.pop();
			AjaxMapsConfig.PRINT_MENU_FORMATS.pop();
			AjaxMapsConfig.PRINT_MENU_FORMATS.push({type: "Portrait", width: a4_width_portrait, height: a4_height_portrait, label: "Portrait", printCss: "A4Portrait"});
			AjaxMapsConfig.PRINT_MENU_FORMATS.push({type: "Landscape", width: a4_width_landscape, height: a4_height_landscape, label: "Landscape", printCss: "A4Landscape"});
			AjaxMapsConfig.PRINT_MENU_BUTTON = "Print";
			AjaxMapsConfig.PRINT_MENU_BUTTON_CLOSE = "Close";
			AjaxMapsConfig.PRINT_MENU_BUTTON_PRINT = "Print";
			AjaxMapsConfig.PRINT_MENU_PAPER_ORIENTATION = "Paper orientation";
			AjaxMapsConfig.PRINT_MENU_PAPER_SIZE = "Paper size";
			AjaxMapsConfig.PRINT_MENU_META_ELECT ="Print destination info?";
			AjaxMapsConfig.PRINT_MENU_YES ="Yes";
			AjaxMapsConfig.PRINT_MENU_NO ="No";
			AjaxMapsConfig.PRINT_MENU_INDEX_ELECT ="Print index map?";
			AjaxMapsConfig.PRINT_MENU_LEGEND_ELECT ="Print map legends?";
			AjaxMapsConfig.PRINT_MENU_HEADERINPUT ="Print header";			
			AjaxMapsConfig.PRINT_MENU_HEADERINPUT_DEFAULT ="";
			AjaxMapsConfig.POI_POPUP_LINK_NAME ="Destination info";
			poiTitle = "Destination info";
			CoordTxtE ="e ";
			CoordTxtN ="n ";
			break;
			}		
	
    var start = util.objectXY(util.attach(AjaxMapsConfig.MAP_AREA));
	var width = util.getWindowWidth() - start.x - AjaxMapsConfig.MAP_MARGIN_RIGHT;
	var height = util.getWindowHeight() - start.y - AjaxMapsConfig.MAP_MARGIN_BOTTOM;
	
	if(width > AjaxMapsConfig.MAP_WIDTH){
		AjaxMapsConfig.MAP_WIDTH = util.getWindowWidth() - start.x - AjaxMapsConfig.MAP_MARGIN_RIGHT;
	}
	
	if(height > AjaxMapsConfig.MAP_HEIGHT){
		AjaxMapsConfig.MAP_HEIGHT = util.getWindowHeight() - start.y - AjaxMapsConfig.MAP_MARGIN_BOTTOM;
	}

	naviciAjaxApi = new NaviciAjaxApi();
    naviciAjaxApi.start(AjaxMapsConfig);
	var poiPopFormatter = new PoiPopupFormatterMetsa();
    naviciAjaxApi.setPoiPopupFormatter(poiPopFormatter);
	
	measureDistTool = new MeasureDistTool(naviciAjaxApi);
	measureDistTool.setColor(AjaxMapsConfig.measureLineColor);
	measureDistTool.setStroke(AjaxMapsConfig.measureLineStroke);
	
	
    var map = naviciAjaxApi.getMap();
    addPrintOptions(naviciAjaxApi);
    poi = new PoiHandling(naviciAjaxApi,poiTitle);
    positionInfo(map);
	printMenu = naviciAjaxApi.getMapPrintMenu();
	printMenu.setPrintCallback(showPrintXML);
	

	changeSelectedLevel();
   	setCategories();

 //   var search = searchObject(0, "search", null, "", "", naviciAjaxApi);
   

    searchWithNameSuggestionList = new SelectionList(util.attach('suggestionList'),
						   'SuggestionListEnabled',
						   'SuggestionListDisabled',
						   'SuggestionListInvisible',
						   new SelectionList.parameters(1000,
										999,
										0,
										SelectionList.STATE_ENABLED));


    var searchWithNameFrame = new SearchFrame(util.attach("nameSearchAreaList"),
				   searchWithNameSuggestionList);
    //searchWithNameFrame.addRouteLocationChangeCBF(centerToLocation);


    var rightArea = util.attach("page_right_area");
    var mapArea = util.attach("MapArea");
    var height = map.getHeight() + "px";
	var right_height = (map.getHeight()+26) + "px";
	var width = map.getWidth() + "px";
	rightArea.style.height = right_height;
	rightArea.style.width = width;
	mapArea.style.height = height;
	mapArea.style.width = width;    
	var mapLayerList = new MapLayerList();    
    mapLayerList.start(AjaxMapsConfig.MAP_AREA,map);	

	
	
	//Set function that will be called after zoom level is changed. 
	var map = naviciAjaxApi.getMap();
	map.addZoomChangeCallback(changeSelectedLevel); 
	map.addZoomChangeCallback(togglePointLayers); 
	map.addZoomChangeCallback(toggleRouteLayers); 
	map.addZoomChangeCallback(togglePrintButton);
	togglePrintButton();

	var active_surface = map.getActiveSurface();
	active_surface.style.width = AjaxMapsConfig.MAP_WIDTH + "px";
	active_surface.style.height = AjaxMapsConfig.MAP_HEIGHT + "px";
	active_surface.style.backgroundPosition = "center";
	

    function mouseOver(mapInfo){
    	//log.print("notice","test", mapInfo.mouseCoordX);
    	alert(mapInfo.mouseCoordX);
		naviciAjaxApi.setMouseOverCallback(mouseOver,400);	
    }
    
  	
     function centerToLocation(location){
		var x = location.getX();
		var y = location.getY();
	if(x != null && y != null){
	   naviciAjaxApi.setMapCenter(x,y);
	}
    }
  	
    function printMap(){
		//getMapPrintXML(width, height, type, zoom, x, y, parameters)
	    document.mapPrintForm.printXML.value = naviciAjaxApi.getMapPrintXML();
	    document.mapPrintForm.submit();
	}
}

	function addButtons2MapSurface(buttonBarId){
		
		var mapArea = util.attach("MapArea");
		mapArea.appendChild(util.attach(buttonBarId));
	}
  
  
  /*
  *	Shows the coordinates of the mouse on the map
  */
  function positionInfo(map){
  	var mousePosition = util.attach("mousePosition");
  	var posTimerId = setTimeout(setPosition,250);
  	function setPosition(){
  		clearTimeout(posTimerId);
  		var mapInfos = map.getInfo();
  		
  		var wgsType = document.coordSearchForm.wgs_type.value;
  		
  		var x = Math.round(mapInfos.mouseCoordX);
  		var y = Math.round(mapInfos.mouseCoordY);
  		var coords = KKJToWGS(x,y);
		var wgs_x = Number(coords[0]).toFixed(5);
		var wgs_y = Number(coords[1]).toFixed(5);
		
		switch(wgsType){

			case "deg":
				var wgs_lon = wgs_x;			
				var wgs_lat = wgs_y;
			break;

			case "min":
				wgs_x_deg = Math.floor(wgs_x);
				wgs_y_deg = Math.floor(wgs_y);
		
				wgs_x_min = Number((wgs_x - wgs_x_deg) * 60).toFixed(4);
				wgs_y_min = Number((wgs_y - wgs_y_deg) * 60).toFixed(4);
				
				var wgs_lon = wgs_x_deg + "° " + wgs_x_min + "'";				
				var wgs_lat = wgs_y_deg + "° " + wgs_y_min + "'";
				
				
			break;


			case "sec":
				wgs_x_deg = Math.floor(wgs_x);
				wgs_y_deg = Math.floor(wgs_y);
		
				wgs_x_min = Number((wgs_x - wgs_x_deg) * 60).toFixed(4);
				wgs_y_min = Number((wgs_y - wgs_y_deg) * 60).toFixed(4);
				
				wgs_x_sec = Number((wgs_x_min - Math.floor(wgs_x_min))*60).toFixed(4);
				wgs_y_sec = Number((wgs_y_min - Math.floor(wgs_y_min))*60).toFixed(4);
				
				var wgs_lon = wgs_x_deg + "° " + Math.floor(wgs_x_min) + "' " + wgs_x_sec + "\"";
				var wgs_lat = wgs_y_deg + "° " + Math.floor(wgs_y_min) + "' "+ wgs_y_sec + "\"";;
				
			break;
	}
		
		
		
		
		

		
		
  		mousePosition.innerHTML = "YKJ: " + CoordTxtN + y + " m , " + CoordTxtE + x + " m&nbsp;&nbsp; WGS84: lat " + wgs_lat + " lon " + wgs_lon;
  		posTimerId = setTimeout(setPosition,250);
  	}
  }
  
  function setMapEnvelope(x,y,minx,maxx,miny,maxy,maxzoom){    
	 

  	if(minx == null || minx == "" || minx == undefined){		
		naviciAjaxApi.setMapCenter(x,y);
		return;
	}

	var map = naviciAjaxApi.getMap();
	var height = map.getHeight();
    var width = map.getWidth();
	var scale = 0;
	var xmin = 0;
	var xmax = 0;
	var ymin = 0;
	var ymax = 0;

	for(var i = AjaxMapsConfig.MAP_MIN_ZOOM; i <= AjaxMapsConfig.MAP_MAX_ZOOM; i++){
	
		scale = AjaxMapsConfig.scales[i];
		ymax = y + (((height)/2)*scale);
		ymin = y - (((height)/2)*scale);
		xmax = x + (((width)/2)*scale);
		xmin = x - (((width)/2)*scale);

		if((ymax >= maxy) && (xmax >= maxx)  && (ymin <= miny) && (xmin <= minx)){
				//Correct level found
				var level = i;
				if(maxzoom !=null && level > maxzoom ){
					naviciAjaxApi.setMapZoom(maxzoom);
				}
				else{
					naviciAjaxApi.setMapZoom(level);
				}
				
				naviciAjaxApi.setMapCenter(x,y);
				return;
		}
	
	
	}	
	
	naviciAjaxApi.setMapCenter(x,y);
	naviciAjaxApi.setMapZoom(AjaxMapsConfig.MAP_MAX_ZOOM);
	
  }
  
  function setView(x,y,level){
  	naviciAjaxApi.setMapZoom(level);
	naviciAjaxApi.setMapCenter(x,y);
  }
  

function changeCoordSys(xTxtKKJ,yTxtKKJ){


	var coordSysX = util.attach("coordSysX");
	var coordSysY = util.attach("coordSysY");	
	var coordType;
	
	 for (var i=0; i < document.coordSearchForm.coord_type.length; i++)
   {
   if (document.coordSearchForm.coord_type[i].checked)
      {
      coordType = document.coordSearchForm.coord_type[i].value;
      }
   }	
	


	var type = document.coordSearchForm.wgs_type.value;
	
	var coordTable = util.attach("coordInput");
	coordTable.style.display = "none";
	
	coordTable = util.attach("coordInputWgsD");
	coordTable.style.display = "none";
	
	coordTable = util.attach("coordInputWgsDM");
	coordTable.style.display = "none";
	
	coordTable = util.attach("coordInputWgsDMS");
	coordTable.style.display = "none";
	
		if(coordType == "kkj"){
	
		coordTable = util.attach("coordInput");
			coordTable.style.display = "block";
		document.getElementById("coord_x").maxLength="7";
		document.getElementById("coord_y").maxLength="7";  
		//document.getElementById("coord_y").length="100"; 
		coordSysX.innerHTML = xTxtKKJ;		
		coordSysY.innerHTML = yTxtKKJ;
		document.getElementById("coord_x").value="";
		document.getElementById("coord_y").value="";	
	
	}
	
	else if(coordType == "wgs84"){
	
	
	switch(type){
		case "deg":
			coordTable = util.attach("coordInputWgsD");
			coordTable.style.display = "block";
		break;
		case "min":
			coordTable = util.attach("coordInputWgsDM");
			coordTable.style.display = "block";
		break;
		case "sec":
			coordTable = util.attach("coordInputWgsDMS");
			coordTable.style.display = "block";
		break;
	}
}
}

  function centerMap(alertTxt){  	
	
	var coordType;
	var wgsType = document.coordSearchForm.wgs_type.value;
	var coordTypeRadioButtons = document.coordSearchForm.coord_type;

	    if(coordTypeRadioButtons){
			for (var i=0; i < document.coordSearchForm.coord_type.length; i++)
			{
				if (document.coordSearchForm.coord_type[i].checked)
				{
					coordType = document.coordSearchForm.coord_type[i].value;
				}
   			}	
        }else{
          //alert("coord type not set");
          return null;       
		   }
	
	
	

	
	if(coordType == "kkj"){
			x = (util.attach("coord_x").value).replace(',','.');
			y = (util.attach("coord_y").value).replace(',','.');
	
	}else{
	
		
				
		switch(wgsType){

			case "deg":
			
				x = (util.attach("lon_d").value).replace(',','.');
				y = (util.attach("lat_d").value).replace(',','.');
				if(x == null || x == "" || y == null || y == ""){
					return null;
				}
				
				
				x=parseFloat(x);
				y=parseFloat(y);
				var coords = WGSToKKJ(x,y);
			break;

			case "min":
				x = util.attach("lon").value;
				y = util.attach("lat").value;
				if(x == null || x == "" || y == null || y == ""){
					return null;
				}
				
				x=parseFloat(x);
				y=parseFloat(y);
				


				x_min = (util.attach("lon_min").value).replace(',','.');
				y_min = (util.attach("lat_min").value).replace(',','.');
				
				if(x_min == null || x_min == "" || isNaN(x_min)){
					x_min = 0;
				}
				
				if(y_min == null || y_min == "" || isNaN(y_min)){
					y_min = 0;
				}
				
				x_min=parseFloat(x_min) / 60;
				y_min=parseFloat(y_min) / 60; 
				
				
				x = x + x_min;
				y = y + y_min;
				
			break;


			case "sec":
				x = util.attach("lon_s").value;
				y = util.attach("lat_s").value;
				if(x == null || x == "" || y == null || y == ""){
					return null;
				}
				
				x=parseFloat(x);
				y=parseFloat(y);
				


				x_min = (util.attach("lon_min_s").value).replace(',','.');
				y_min = (util.attach("lat_min_s").value).replace(',','.');
				
				if(x_min == null || x_min == "" || isNaN(x_min)){
					x_min = 0;
				}
				
				if(y_min == null || y_min == "" || isNaN(y_min)){
					y_min = 0;
				}
				
				x_min=parseFloat(x_min) / 60;
				y_min=parseFloat(y_min) / 60; 
				
				
				
				x_sec = (util.attach("lon_sec").value).replace(',','.');
				y_sec = (util.attach("lat_sec").value).replace(',','.');
				
				if(x_sec == null || x_sec == "" || isNaN(x_sec)){
					x_sec = 0;
				}
				
				if(y_sec == null || y_sec == "" || isNaN(y_sec)){
					y_sec = 0;
				}
				
				x_sec=parseFloat(x_sec) / 3600;
				y_sec=parseFloat(y_sec) / 3600;
				
				
				x = x + x_min + x_sec;
				y = y + y_min + y_sec;
				
			break;
	}
	
	
		var coords = WGSToKKJ(x,y);
		x = coords[0];
		y = coords[1];
				
	}			
	
	
	if(x == null || x == "" || y == null || y == ""){
		return null;
	}
	
	if(isNaN(x)){
		this.changeTxtColor("coord_x","red");
		if(isNaN(y)){
			this.changeTxtColor("coord_y","red");
		}
		return null;		
		}
	
	if(isNaN(y)){
		this.changeTxtColor("coord_y","red");
		return null;
	}
			
	
	
	//Check that coords are inside the limits.
		if(x < AjaxMapsConfig.MAP_MIN_X || x > AjaxMapsConfig.MAP_MAX_X ||
		y < AjaxMapsConfig.MAP_MIN_Y || y > AjaxMapsConfig.MAP_MAX_Y){
			alert(alertTxt);
			return null;	}	



  	    naviciAjaxApi.setMapCenter(x,y);
		
	window.scrollTo(0, 0);
  }


/* Set a text to front of the coordinate input boxs. 
 * Text depends on which is the selected coordinate system. 
 */  
function coordTxt(xTxtKKJ,yTxtKKJ){
	
	
	var coordSysX = util.attach("coordSysX");
	var coordSysY = util.attach("coordSysY");	
	var coordType;
	
	 for (var i=0; i < document.coordSearchForm.coord_type.length; i++)
   {
   if (document.coordSearchForm.coord_type[i].checked)
      {
      coordType = document.coordSearchForm.coord_type[i].value;
      }
   }	
	
	if(coordType == "kkj"){
	
	


	
		document.getElementById("coord_x").maxLength="7";
		document.getElementById("coord_y").maxLength="7";  
		//document.getElementById("coord_y").length="100"; 
		coordSysX.innerHTML = xTxtKKJ;		
		coordSysY.innerHTML = yTxtKKJ;
		document.getElementById("coord_x").value="";
		document.getElementById("coord_y").value="";	
	
	}
	
	else if(coordType == "wgs84"){
	
	
				
	document.getElementById("coord_x").maxLength="9";
	document.getElementById("coord_y").maxLength="9";  
	coordSysX.innerHTML = "lon";		
	coordSysY.innerHTML = "lat";
	document.getElementById("coord_x").value="";
	document.getElementById("coord_y").value="";
	

	}
	
	else{
		//alert("Coordsys not selected");
		return;
	}

  }
  
  
 function changeTxtColor(elem,color){ 	
	var elem = util.attach(elem);
	elem.style.color=color;	
	}
	
function reDirect(url){
	window.open(url,null,'width=850,height=750,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
}

function selectLinkReDirect(selectElm){		
	var url = selectElm.options[selectElm.selectedIndex].value;
	if(url!=null && url != ''){
		window.open(url,null,'width=850,height=750,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes');
	}
}

function toggleBlurMap(buttonId,blurMapTxt,showMaptxt){
	var blurButton = util.attach(buttonId); 
	var layerManager = naviciAjaxApi.getLayerManager();
	var mapLayers = layerManager.getLayer("Map");	
	var mapImages = mapLayers.getImages();
	
	if(!isBlur){	
		for (var i=0;i< mapImages.length;i++){
			mapImages[i].style.opacity = "0.2";			
			mapImages[i].style.filter="alpha(opacity='20')";				
			}
	blurButton.innerHTML = showMaptxt;
	 isBlur=true;
		}
	else {
		for (var i=0;i< mapImages.length;i++){
			mapImages[i].style.opacity = "1.0";			
			mapImages[i].style.filter="alpha(opacity='100')";	
		
		}
	blurButton.innerHTML = blurMapTxt;
	isBlur=false;
	}
}





function toggleFullScreen(buttonId,blurMapTxt,showMaptxt){
	var button = util.attach(buttonId);
	var map = naviciAjaxApi.getMap();
	var left_area = util.attach("page_left_cell");
	var right_area = util.attach("page_right_area");
	var header = util.attach("header");
	var header_img = util.attach("header_image");
	var footer = util.attach("footer");
	var map_area = util.attach("MapArea");
	var active_surface = map.getActiveSurface();

	if(!isFullScreen){	
		button.innerHTML = showMaptxt;
		isFullScreen = true;
		left_area.style.display = "none";
		header.style.display = "none";
		header_img.style.display = "none";
		footer.style.display = "none";

		var start = util.objectXY(util.attach(AjaxMapsConfig.MAP_AREA));
		var width = util.getWindowWidth() - AjaxMapsConfig.MAP_MARGIN_RIGHT;
		var height = util.getWindowHeight() - 30;
		right_area.style.width = "100%";
		right_area.style.height = "100%";

		map_area.style.width = width + "px";
		map_area.style.height = height + "px";

		map.setSize(width, height, null, null);

		active_surface.style.width = width + "px";
		active_surface.style.height = height + "px";
		active_surface.style.backgroundPosition = "center";


		}
	else {
		button.innerHTML = blurMapTxt;
		left_area.style.display = "block";
		header.style.display = "block";
		header_img.style.display = "block";
		footer.style.display = "block";
		
		var width = AjaxMapsConfig.MAP_WIDTH;
		var height = AjaxMapsConfig.MAP_HEIGHT;
		
		map_area.style.width = width + "px";
		map_area.style.height = height + "px";

		
		map.setSize(width, height, null, null);
		isFullScreen=false;
		active_surface.style.width = width + "px";
		active_surface.style.height = height + "px";
		active_surface.style.backgroundPosition = "center";
		
		
	}
}








	
  
function changeMapLevel(srcElement){
 
   var level = null; 
	
	level = srcElement.options[srcElement.selectedIndex].value;
	
   if(level != null){
	naviciAjaxApi.setMapZoom(level);	
   }

}

/* Change zoom level to the scale-drop-down-menu 
 *  
 */
function changeSelectedLevel(){
	var scaleMenu = util.attach("zoomLevel");
	var mapInfo = naviciAjaxApi.getMapInfos();
	
	/*var tempText = scaleMenu.options[parseInt(mapInfo.zoom)-1].text;
	var tempValue = scaleMenu.options[parseInt(mapInfo.zoom)-1].value;
	scaleMenu[parseInt(mapInfo.zoom)-1] = new Option(tempText,tempValue,false,true);*/
	scaleMenu.selectedIndex = (parseInt(mapInfo.zoom)-1);
//	naviciAjaxApi.addZoomChangeCallback(changeSelectedLevel); 
}


/**
 * 
 */
function openInfo(infoId, e){	
	
	var infoDiv = util.attach(infoId);		
	
   //Get Postion of the mouse(for align infodiv element)	
   var docX, docY;
   if(e)
   {
   	 
      if( typeof( e.pageX ) == 'number' )
      {
         docX = e.pageX;
         docY = e.pageY;
      }
      else
      {
         docX = e.clientX;
         docY = e.clientY;
      }
   }
   else
   {

      e = window.event;
      docX = e.clientX;
      docY = e.clientY;
      if( document.documentElement
        && ( document.documentElement.scrollTop
            || document.documentElement.scrollLeft ) )
      {
         docX += document.documentElement.scrollLeft;
         docY += document.documentElement.scrollTop;
      } 
      else if( document.body
         && ( document.body.scrollTop
             || document.body.scrollLeft ) )
      {
         docX += document.body.scrollLeft;
         docY += document.body.scrollTop;
      }
   }
   
   //Check if infodiv is right side of the page
	var pageWidth=0;	
	
	if( document.documentElement
        &&  document.documentElement.scrollWidth   )
      {
         pageWidth = document.documentElement.scrollWidth;        
      } 
      else if( document.body
         &&  document.body.scrollWidth)
      {
	  	         pageWidth+= document.body.scrollWidth;         
      }
  
   if(docX > (pageWidth / 2)){  	  	
   	infoDiv.style.left =  (docX-725) +"px";	
   }
   else{
   	 infoDiv.style.left =  docX+"px";
   }
  
   infoDiv.style.top = docY+"px";
   infoDiv.style.display = "block"; 	
	
}


function closeInfo(infoId){
	var elem = util.attach(infoId);		
	elem.style.display = "none";
}

function showPopUp(e,txt){
	
	var infoDiv = util.attach('popUpDiv');
	infoDiv.innerHTML = txt;
	
	
   //Get Postion of the mouse(for align infodiv element)	
   var docX, docY;
   if(e)
   {
   	 
      if( typeof( e.pageX ) == 'number' )
      {
         docX = e.pageX;
         docY = e.pageY;
      }
      else
      {
         docX = e.clientX;
         docY = e.clientY;
      }
   }
   else
   {

      e = window.event;
      docX = e.clientX;
      docY = e.clientY;
      if( document.documentElement
        && ( document.documentElement.scrollTop
            || document.documentElement.scrollLeft ) )
      {
         docX += document.documentElement.scrollLeft;
         docY += document.documentElement.scrollTop;
      } 
      else if( document.body
         && ( document.body.scrollTop
             || document.body.scrollLeft ) )
      {
         docX += document.body.scrollLeft;
         docY += document.body.scrollTop;
      }
   }
   
   //Check if infodiv is right side of the page
	var pageWidth=0;	
	
	if( document.documentElement
        &&  document.documentElement.scrollWidth   )
      {
         pageWidth = document.documentElement.scrollWidth;        
      } 
      else if( document.body
         &&  document.body.scrollWidth)
      {
	  	         pageWidth+= document.body.scrollWidth;         
      }  
  	
   if(docX > (pageWidth / 2)){  	  	
   	infoDiv.style.left =  (docX-160)+"px";	
   }
   else{
   	 infoDiv.style.left =  docX+"px";
   }  
   infoDiv.style.top = docY+"px";
   infoDiv.style.display = "block"; 	
   
   setTimeout("hidePopUp()",1000);
   

}

function hidePopUp(){		
		var elem = util.attach('popUpDiv');		
		elem.style.display = "none";		
	}





function addPrintOptions(naviciAjaxApi){

      var papers = Array();

      //If adding new papertype, remember add this also to the getPrintSettingFunction(). 

      papers.push({label: "A4"});  
	  
	  papers.push({label: "A3"}); 
      

     defaultIndex = 0;
	  
	 var printMenu = naviciAjaxApi.getMapPrintMenu();
	
	 var printPar = printMenu.getPrintParameters();
     

      var printObject = naviciAjaxApi.getMapPrintMenu();

      var userDiv = printObject.getUserDiv();

      
	var dialog = printObject.getDialog();
	dialog.insertBefore(document.createTextNode(AjaxMapsConfig.PRINT_MENU_PAPER_ORIENTATION),dialog.firstChild);

      userDiv.className = "print_papersize";

      userDiv.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_PAPER_SIZE));

      var div = document.createElement("div");

      for(var i=0;i < papers.length; i++){

            var input = null;

            if(util.isIE){ //Bug in IE: If radio Buttons created in the correct way, they do not work!

                  if(i==defaultIndex){    

                        input = document.createElement('<input type="radio" name="papersize" checked="checked" />');

                  }else{

                        input = document.createElement('<input type="radio" name="papersize"  />');

                  }

            }else{

                  input = document.createElement("input");

                  input.type= "radio";

                  input.name= "papersize";

                  input.checked = i==defaultIndex;
            }

            input.onclick = getPrintSettingFunction(papers[i].label);

            div.appendChild(input);

            div.appendChild(document.createTextNode(papers[i].label));

      }

      userDiv.appendChild(div);
	  
	  //New form for for selecting printoptions etc.
	  if(util.isIE){  
	 	var printOptionsForm= document.createElement('<form name="printOptions">');
	  }
	  else{
		  var printOptionsForm = document.createElement("form");	
		  printOptionsForm.name="printOptions";		 
	  }
	  
	  
	  //Create div and radiobuttons for electing that will metadata of the areas also be prited. 
 	 printOptionsForm.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_META_ELECT));
     var divMeta = document.createElement("div");	 
	 var inputMeta = null; 
	 
	 if(util.isIE){ //Bug in IE: If radio Buttons created in the correct way, they do not work!                 

                        inputMeta = document.createElement('<input type="radio" name="mapMetaElect" value="true" checked="checked" />');
						divMeta.appendChild(inputMeta);
						divMeta.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_YES));
						inputMeta = document.createElement('<input type="radio" name="mapMetaElect" value="false"/>');
						divMeta.appendChild(inputMeta);
						divMeta.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_NO));
     }
	 else{
					//Bug in safari: Must use setAttribute(), can't use DOM specified elem.type etc. 
                  inputMeta = document.createElement("input");
                  inputMeta.setAttribute("type","radio");
                  inputMeta.setAttribute("name","mapMetaElect");
				  inputMeta.setAttribute("value","true");
				  inputMeta.checked = true;
				  divMeta.appendChild(inputMeta);
				  divMeta.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_YES));
				  
				  inputMeta = document.createElement("input");
                  inputMeta.setAttribute("type","radio");
                  inputMeta.setAttribute("name","mapMetaElect");
				  inputMeta.setAttribute("value","false");
				  inputMeta.checked = false;
				  divMeta.appendChild(inputMeta);
				  divMeta.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_NO));
	}	
	printOptionsForm.appendChild(divMeta);
	
	
	  //Create div and radiobuttons for electing that will indexmap also be prited. 
 	 printOptionsForm.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_INDEX_ELECT));
     var divIndex = document.createElement("div");	 
	 var inputIndex = null; 
	 
	 if(util.isIE){ //Bug in IE: If radio Buttons created in the correct way, they do not work!                 

                        inputIndex = document.createElement('<input type="radio" name="mapIndexElect" value="true" checked="checked" />');
						divIndex.appendChild(inputIndex);
						divIndex.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_YES));
						inputIndex = document.createElement('<input type="radio" name="mapIndexElect" value="false" />');
						divIndex.appendChild(inputIndex);
						divIndex.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_NO));
     }
	 else{

					//Bug in safari: Must use setAttribute(), can't use DOM specified elem.type etc. 
				  inputIndex = document.createElement("input");
                  inputIndex.setAttribute("type","radio");
                  inputIndex.setAttribute("name","mapIndexElect");
				  inputIndex.setAttribute("value","true");                  
				  inputIndex.checked = true;
				  divIndex.appendChild(inputIndex);
				  divIndex.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_YES));
				  
				  inputIndex = document.createElement("input");
                  inputIndex.setAttribute("type","radio");
                  inputIndex.setAttribute("name","mapIndexElect");
				  inputIndex.setAttribute("value","false");         
				  inputIndex.checked = false;
				  divIndex.appendChild(inputIndex);
				  divIndex.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_NO));
	}	
	printOptionsForm.appendChild(divIndex);
	
	
	 printOptionsForm.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_LEGEND_ELECT));
     var divLegend = document.createElement("div");	 
	 var inputLegend = null; 
	
	if(util.isIE){ //Bug in IE: If radio Buttons created in the correct way, they do not work!                 

                        inputLegend = document.createElement('<input type="radio" name="legendElect" value="true"/>');
						divLegend.appendChild(inputLegend);
						divLegend.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_YES));
						inputLegend = document.createElement('<input type="radio" name="legendElect" value="false"  checked="checked"/>');
						divLegend.appendChild(inputLegend );
						divLegend.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_NO));
     }
	 else{

					//Bug in safari: Must use setAttribute(), can't use DOM specified elem.type etc. 
				  inputLegend = document.createElement("input");
                  inputLegend.setAttribute("type","radio");
                  inputLegend.setAttribute("name","legendElect");
				  inputLegend.setAttribute("value","true");                  
				  inputLegend.checked = false;
				  divLegend.appendChild(inputLegend);
				  divLegend.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_YES));
				  
				  inputLegend= document.createElement("input");
                  inputLegend.setAttribute("type","radio");
                  inputLegend.setAttribute("name","legendElect");
				  inputLegend.setAttribute("value","false");         
				  inputLegend.checked = true;
				  divLegend.appendChild(inputLegend);
				  divLegend.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_NO));
	}	
	printOptionsForm.appendChild(divLegend);
	
	
	
	
	
	//Create inputfield for user defined header.
	 printOptionsForm.appendChild(document.createTextNode(AjaxMapsConfig.PRINT_MENU_HEADERINPUT));
	 printOptionsForm.appendChild(document.createElement("br"));
	
	 if(util.isIE){ 	
		var headerInput =  document.createElement('<input type="text" name="headerInput" id="printHeader" value="'+AjaxMapsConfig.PRINT_MENU_HEADERINPUT_DEFAULT+'" onfocus="javascript:selectTxtFieldContent(printHeader)"/>');
		
	}
	else{
		//Bug in safari: Must use setAttribute(), can't use DOM specified elem.type etc. 
		var headerInput = document.createElement("input");
		headerInput.setAttribute("type","text");
		headerInput.setAttribute("name","headerInput");
		headerInput.setAttribute("id","printHeader");
		headerInput.setAttribute("onfocus","javascript:selectTxtFieldContent(printHeader)");
		headerInput.value=AjaxMapsConfig.PRINT_MENU_HEADERINPUT_DEFAULT;
	}
	headerInput.onfocus=function (){this.focus();this.select();}
	printOptionsForm.appendChild(headerInput);
	
	userDiv.appendChild(printOptionsForm);
	

      function getPrintSettingFunction(label){

            return function(){

					if (label=='A3'){
	                  printObject.setFormatSize("Portrait",a3_width_portrait, a3_height_portrait);
	
	                  printObject.setFormatSize("Landscape", a3_width_landscape,a3_height_landscape);
				  }
				  else //default a4
				  {
	                  printObject.setFormatSize("Portrait",a4_width_portrait, a4_height_portrait);
	
	                  printObject.setFormatSize("Landscape", a4_width_landscape,a4_height_landscape);
				  }

            }

      }

}




 function toggleChildVisibility(srcElement,className){

    var parent = srcElement.parentNode;


    for(var i = 0; i<20; i++){
	if(parent.tagName != "DIV"){
	   parent = parent.parentNode;
   	}else if(parent.className== className){
	   break;
	}
    }	
	if(parent.tagName == "DIV" && parent.className== className){
	  var child = parent.firstChild;
	  var childDivs = new Array();
	  if(child != null){
 		childDivs.push(child);
		var sibling = child.nextSibling;
		while(sibling != null){
			childDivs.push(sibling);
			sibling = sibling.nextSibling;
		}
	  }

	     for(var i in childDivs){
		var div = childDivs[i];
		if(div.className == className){
			if(div.style.display == "none"){
				div.style.display = "block";
				srcElement.className = "toggleButtonMinus"
			}else{
				div.style.display = "none";
				srcElement.className = "toggleButtonPlus"
			}
		}
      	   }
    }
		
 }
 
 function addShape(name,color,pattern,lmo_name){
		
//	alert("adding shape name:" + name + ", color:" + color + ",lmo_name:" + lmo_name);
	
		if(name == null || name == ""){
			return null;			
		}
		
		if(lmo_name != null && lmo_name != ""){
			if(lmo_Id != null){
				removeShape(lmo_Id);
			}
		}
		var xml ='<shape_layer ';
		if(lmo_name != null && lmo_name != "")				
			xml += 'name="'+encodeURIComponent(name)+'_s" ';
		else
			xml += 'name="'+encodeURIComponent(name)+'" ';		
		if(color != null && color != "")
			xml += 'color="'+encodeURIComponent(color)+'" ';
		if(pattern != null && pattern != "")
			xml += 'pattern="'+encodeURIComponent(pattern)+'" ';
		if(lmo_name != null && lmo_name != "")
			xml += 'lmo_name="'+encodeURIComponent(lmo_name)+'" ';	
		xml += ' />';
		var id =(naviciAjaxApi.addDynamicLayerObject(xml));		
		
		if(lmo_name != null && lmo_name != ""){
			lmo_Id = id;
			naviciAjaxApi.redrawDynamicLayer();
		}				
		
		return id;			
	} 
	
 function addRouteShape(name,color,width,minx,maxx,miny,maxy){
			
		if(name == null || name == ""){
			return null;			
		}
		
		if(routeLayerOnId != null)
			removeShape(routeLayerOnId);			
	
		var xml ='<shape ';			
		xml += 'name="'+encodeURIComponent(AjaxMapsConfig.ROUTE_SHAPE_PATH +name)+'" ';		
		xml += 'color="'+encodeURIComponent(color)+'" ';		
		xml += 'width="'+encodeURIComponent(width)+'" ';	
		xml += 'minx="'+encodeURIComponent(minx)+'" ';
		xml += 'maxx="'+encodeURIComponent(maxx)+'" ';
		xml += 'miny="'+encodeURIComponent(miny)+'" ';
		xml += 'maxy="'+encodeURIComponent(maxy)+'" ';	
		xml += '/>';		
		
		routeLayerOnId = (naviciAjaxApi.addDynamicLayerObject(xml));	
				
		naviciAjaxApi.redrawDynamicLayer();	
		
		
		
	}
	
function removeShape(id){		
		return naviciAjaxApi.deleteDynamicLayerObject(id);
	}
	
	
	
 function insertMarkToCheckBox(elemName,layerName){
  		if(layerName == null || layerName == ""){
			return null;
		}
		
	
		if(AjaxMapsConfig.SPECIAL_LAYERS[layerName]!=null){		
			for(var i = 0; i < AjaxMapsConfig.SPECIAL_LAYERS[layerName].length; i++){
				var ml_checkBox = util.attach('ml_'+AjaxMapsConfig.SPECIAL_LAYERS[layerName][i]);
					if(ml_checkBox.checked != true){
						ml_checkBox.checked = true;										
						toggleLayerSelection(ml_checkBox,'MapLayerMenuListItem');
					}
			}			
 		} 
  	var mapLayerList = util.attach(elemName).childNodes;
	
		
		
	
	function insertMark(elem,layerName){
		
		if(elem.name == "layer_name" && elem.value==layerName){	
		if(elem.previousSibling != null && elem.previousSibling.type== "checkbox"){
						elem.previousSibling.checked=true;
						toggleLayerSelection(elem.previousSibling,"MapLayerMenuListItem");
		}
		
		}
		var children = elem.childNodes;
		for(var k=0; k< children.length;k++){
			insertMark(children[k],layerName);
			}
	}
	if(mapLayerList != null){	
		for(var i = 0; i < mapLayerList.length; i++){
			insertMark(mapLayerList[i],layerName);
		}
	}	
	
  }
	
	
	
function toggleDivVisibility(divId){
		var menu = util.attach(divId);
		if(menu.style.display != "none"){
			menu.style.display = "none";
		}
		else{
			menu.style.display = "block";
		}		
	}


function setCategories(){
	var categoryFields = document.getElementsByName("search_category");
	categories = "";
	for(var i=0; i < categoryFields.length; i++){
		if(categoryFields[i].checked && categoryFields[i].value != null && categoryFields[i].value != ""){
			if(categories != ""){
				categories += '|';
			}			
			categories += categoryFields[i].value;			
		}
	}
		
}

function getNameSearchAttributes(){
	
	var mapInfo = naviciAjaxApi.getMapInfos();
	
	var topLeftX= mapInfo.centerX-(mapInfo.width*AjaxMapsConfig.scales[mapInfo.zoom])/2;
	var topLeftY= mapInfo.centerY+(mapInfo.height*AjaxMapsConfig.scales[mapInfo.zoom])/2;
	var bottomRightX = mapInfo.centerX+(mapInfo.width*AjaxMapsConfig.scales[mapInfo.zoom])/2;
	var bottomRightY = mapInfo.centerY-(mapInfo.height*AjaxMapsConfig.scales[mapInfo.zoom])/2;
	
	var restSelection = document.getElementsByName("ns_useCoordRestriction");
	var useRestriction = restSelection[0].checked;
	
	if(useRestriction){
	
		var rtn_array = new Array({"attributename":"category","attributevalue":categories}
							 ,{"attributename":"minx","attributevalue":topLeftX}
							 ,{"attributename":"maxx","attributevalue":bottomRightX}
							 ,{"attributename":"miny","attributevalue":bottomRightY}
							 ,{"attributename":"maxy","attributevalue":topLeftY});	
	}
	else{	
		var rtn_array = new Array({"attributename":"category","attributevalue":categories}
							 ,{"attributename":"minx","attributevalue":""}
							 ,{"attributename":"maxx","attributevalue":""}
							 ,{"attributename":"miny","attributevalue":""}
							 ,{"attributename":"maxy","attributevalue":""} );	
	}
	return rtn_array;	
}


function showPrintXML(){
	
	var mapInfo = naviciAjaxApi.getMapInfos();		
	
	var xmlForm = util.attach("printForm");		
	var xmlField = util.attach("printXML");	
	var mapMetaElect = util.attach("mapMetaElectInfo");
	var mapIndexElect = util.attach("mapIndexElectInfo");
	var printHeader = util.attach("printHeaderInfo");
	var printLanguage = util.attach("printLanguage");
	var mapLegendElect = util.attach("mapLegendElect");
	printLanguage.value = AjaxMapsConfig.LANGUAGE;
	
	
	var parameters = new Array();	 
	
	//Add info to the xml and to hidden field's some are defined in GUI. Hidden field's are for passing additional data (like language, headerTxt etc.) to printPage. 
	
	
	
	
	for (var i=0; i < document.printOptions.mapMetaElect.length; i++)
			{  
				if (document.printOptions.mapMetaElect[i].checked)
				{	
					parameters.push({"attributename":"printMapMeta","attributevalue":document.printOptions.mapMetaElect[i].value});
					mapMetaElect.value = document.printOptions.mapMetaElect[i].value;
				}
   			}
			
	for (var i=0; i < document.printOptions.legendElect.length; i++)
			{  
				if (document.printOptions.legendElect[i].checked)
				{	
					parameters.push({"attributename":"printMapLegend","attributevalue":document.printOptions.legendElect[i].value});
					mapLegendElect.value = document.printOptions.legendElect[i].value;
				}
   			}		
			
	
	//If map zoom level is too high, don't let user print indexmap.		
	if ((parseInt(mapInfo.zoom)) > AjaxMapsConfig.MAX_ZOOMINDEX_TO_PRINT_INDEXMAP){
					parameters.push({"attributename":"printMapIndex","attributevalue":"false"});
					mapIndexElect.value = "false";		
		}
	else{
		for (var i=0; i < document.printOptions.mapIndexElect.length; i++)
				{
					if (document.printOptions.mapIndexElect[i].checked)
					{					
						parameters.push({"attributename":"printMapIndex","attributevalue":document.printOptions.mapIndexElect[i].value});
						mapIndexElect.value = document.printOptions.mapIndexElect[i].value;					
					}
	   			}
		}
	
	parameters.push({"attributename":"language","attributevalue":printLanguage.value});			
 	
	printHeader.value = document.printOptions.headerInput.value;	
		
	printMenu.setPrintParameters(parameters);
	var xml = printMenu.getMapPrintXML();
	var indexMap = naviciAjaxApi.getIndexMap();
	
	var indexMapZoom = util.attach("indexMapZoom");
	indexMapZoom.value = indexMap.getZoom();
	var indexMapWidth = util.attach("indexMapWidth");
	indexMapWidth.value = indexMap.getWidth();
	var indexMapHeight = util.attach("indexMapHeight");
	indexMapHeight.value = indexMap.getHeight();
	var indexMapFrameHeight = util.attach("indexMapFrameHeight");	
	
	var printFormatInfo = printMenu.getPreviewInfo();	
	indexMapFrameHeight.value = printFormatInfo['frameHeight'];
	var indexMapFrameWidth = util.attach("indexMapFrameWidth");
	indexMapFrameWidth.value = printFormatInfo['frameWidth'];
	
	xmlField.value=xml;
	xmlForm.submit();	
}

function showDivAndSetPos(divId){
	var div = util.attach(divId);	
	
	var topPos = 0;
	var leftPos = 0;
	
	if( document.documentElement
        && ( document.documentElement.scrollTop
            || document.documentElement.scrollLeft ) )
      {
         leftPos += document.documentElement.scrollLeft;
         topPos += document.documentElement.scrollTop;
      } 
      else if( document.body
         && ( document.body.scrollTop
             || document.body.scrollLeft ) )
      {
         leftPos += document.body.scrollLeft;
         topPos += document.body.scrollTop;
      }
	
	
	div.style.top = (topPos+25)+"px";
	div.style.left = (leftPos+25)+"px";
	div.style.visibility="visible";
}

function hideDiv(divId){
	var div = util.attach(divId);
	div.style.visibility="hidden";
}

function unselectAllLayers(srcElement){
	
	if(lmo_Id != null){
			removeShape(lmo_Id);
	}
	
	if(routeLayerOnId != null){
			removeShape(routeLayerOnId);
			routeLayerOnId = null;
		}
		
	
	
	var mapLayerList = util.attach(srcElement).childNodes;				
	
	function insertMark(elem){		
		
		if(elem.previousSibling != null && elem.previousSibling.type== "checkbox"){
						elem.previousSibling.checked=false;
						toggleLayerSelection(elem.previousSibling,"MapLayerMenuListItem");
		}
		
		
		var children = elem.childNodes;
		for(var k=0; k< children.length;k++){
			insertMark(children[k]);
			}
	}
	
	for(var i = 0; i < mapLayerList.length; i++){
		insertMark(mapLayerList[i]);	
	}	
		
}

function emptyField(fieldId){
	var txtField = util.attach(fieldId);
	txtField.value="";
	
	if(fieldId == "search_name"){
		searchWithNameSuggestionList.clear()
	}

}

function selectTxtFieldContent(fieldId){
	var txtField = util.attach(fieldId);
	txtField.focus();
	txtField.select();
}

function enterSubmit(e, alertTxt){
	var key;
	
	if(window.event){
		key = window.event.keyCode;
	} 
	else{
		key = e.which;
	}
	
	if(key ==13)
	{
		this.centerMap(alertTxt);
	}
		
}


function checkBoxWithId(mapLayerId){
	var checkBox = document.getElementsByName(mapLayerId);
	checkBox[0].checked = true;		
	toggleLayerSelection(checkBox[0],'MapLayerMenuListItem');
	
}

function toggleMeasure(buttonId,startTxt,stopTxt,distTxtDivId,distTxtDivArea,measureUndoDivId){	
	var measureButton = util.attach(buttonId);
	var distTxtDiv = util.attach(distTxtDivId);
	var distAreaDiv = util.attach(distTxtDivArea);
	var measureUndo = util.attach(measureUndoDivId);
	measureDistTool.setDistTxtDiv(distTxtDiv);	
	
	if(isMeasureOn){
		measureDistTool.stopMeasure();
		isMeasureOn = false;
		measureButton.innerHTML = startTxt;
		distTxtDiv.innerHTML='&nbsp;';
		distAreaDiv.style.visibility = "hidden";		
		measureUndo.style.visibility = "hidden";
		
		
	}
	else{		
		measureDistTool.startMeasure();
		distAreaDiv.style.visibility = "visible";		
		measureUndo.style.visibility = "visible";	
		distTxtDiv.innerHTML='--';		
		isMeasureOn = true;
		measureButton.innerHTML = stopTxt;
	}		
}

function undoLastMeasurePointing()
{
	measureDistTool.undoLastPoint();
} 

function togglePointLayers(){
	
	var mapInfo = naviciAjaxApi.getMapInfos();
	if(mapInfo.zoom > AjaxMapsConfig.MAX_ZOOMINDEX_TO_SHOW_POINT_OBJECTS && isPointLayersDisabled == false){
		var pointLayers = getpointLayerNames();
		for(var i = 0; i < pointLayers.length;i++){
			poi.setPoi(pointLayers[i][0],false,null);
		}
		isPointLayersDisabled = true;
		naviciAjaxApi.redrawDynamicLayer();
	}
	if(mapInfo.zoom <=  AjaxMapsConfig.MAX_ZOOMINDEX_TO_SHOW_POINT_OBJECTS && isPointLayersDisabled){
		var pointLayers = getpointLayerNames();
		for(var i = 0; i < pointLayers.length;i++){			
			poi.setPoi(pointLayers[i][0],true,new Array({'attributename':'type','attributevalue':'point'}));
		}
		isPointLayersDisabled = false;
		naviciAjaxApi.redrawDynamicLayer();
	}	
}

function toggleRouteLayers(){
	
	var mapInfo = naviciAjaxApi.getMapInfos();
	if(mapInfo.zoom > AjaxMapsConfig.MAX_ZOOMINDEX_TO_SHOW_LINE_OBJECTS && isRouteLayersDisabled == false){
		var routeLayers = getRouteLayerNames();
		for(var i = 0; i < routeLayers.length;i++){
			poi.setPoi(routeLayers[i][0],false,null);
		}
		isRouteLayersDisabled = true;
		naviciAjaxApi.redrawDynamicLayer();
	}
	if(mapInfo.zoom <=  AjaxMapsConfig.MAX_ZOOMINDEX_TO_SHOW_LINE_OBJECTS && isRouteLayersDisabled){
		var routeLayers = getRouteLayerNames();
		for(var i = 0; i < routeLayers.length;i++){			
			poi.setPoi(routeLayers[i][0],true,new Array({'attributename':'type','attributevalue':'line'}));
		}
		isRouteLayersDisabled = false;
		naviciAjaxApi.redrawDynamicLayer();
	}	
}

function setPointLayer(layer_name,type,order){	
	var mapInfo = naviciAjaxApi.getMapInfos();
	if(mapInfo.zoom > AjaxMapsConfig.MAX_ZOOMINDEX_TO_SHOW_POINT_OBJECTS){
		isPointLayersDisabled = true;
	}
	else{
		if(order != null && order != '')
			poi.setPoi(layer_name,true,new Array({'attributename':'type','attributevalue':type},{'attributename':'order','attributevalue':order}));		
		else
			poi.setPoi(layer_name,true,new Array({'attributename':'type','attributevalue':type}));		
	}
}

function setRouteLayer(layer_name,type,order){	
	var mapInfo = naviciAjaxApi.getMapInfos();
	if(mapInfo.zoom > AjaxMapsConfig.MAX_ZOOMINDEX_TO_SHOW_LINE_OBJECTS){
		isRouteLayersDisabled = true;
	}
	else{
		if(order != null && order != '')
			poi.setPoi(layer_name,true,new Array({'attributename':'type','attributevalue':type},{'attributename':'order','attributevalue':order}));		
		else
			poi.setPoi(layer_name,true,new Array({'attributename':'type','attributevalue':type}));		
	}
}

function toggleOverflow(id,height){

	var elem = util.attach(id);
	
	if(elem.scrollHeight > height){
		elem.className = id + "_scroll";
	}else{
		
		elem.className = "";
	
	}

}


function togglePrintButton(){
	var print = naviciAjaxApi.getMapPrintMenu();
	var div = print.getPrintButton();
	var mapInfo = naviciAjaxApi.getMapInfos();
	var printMenu = naviciAjaxApi.getMapPrintMenu();
		if(mapInfo.zoom > AjaxMapsConfig.MAX_ZOOMINDEX_TO_SHOW_PRINT_MAP){			
				if(printEnabled){
					 printEnabled = false;
					 print.hide(hide_callback1);				
				 }
				 else{
				 	 print.hide(hide_callback2);
				 }
				 
				
			}
		else{					
				div.style.color = savePrintStyle;
				div.onclick = savePrintFunction;
				printEnabled = true;
		}
		
	function hide_callback1(){		
		 savePrintFunction = div.onclick;				 
	 	 savePrintStyle = div.style.color;		
		 div.style.color="#aaaaaa";
		 div.onclick = null;					 
	}	
	function hide_callback2(){		
		 div.style.color="#aaaaaa";
		 div.onclick = null;					 
	}
}





var poi = null; //has to be global so that the html file can use it directly from html
  				  //The Variable is set in main with a new instance of the class below

function PoiHandling(naviciAjaxApi,title){


	naviciAjaxApi.startPoiManager(200,title,"Click");		//Navici Api should checkfor pois at the current mouse poition every 200 milliseconds
	
  	
  	this.setPoi = setPoi;				 	//Show the pois directly on the Map

  		
 
 	/*
  	* Show/Hide the pois directly on the Map
    */
  	function setPoi(category,visibility,paramArray){

		//alert(category);
  		naviciAjaxApi.setPoiVisibility(category, null, paramArray, visibility);
		//naviciAjaxApi.redrawDynamicLayer();
		
  	}
  	

  } 