//********************************
// M I S C  -  F U N C T I O N S 
// author: Gursch Markus
// July 2008
/////////////////////////////////*

var fullScreenBool = false;
/**
 * deletes the text in the searchbox if it gets the focus
 */
function onSearchBoxClick()
{
	if (document.searchForm.stichwort.value == "Suchbegriff eingeben...")
		document.searchForm.stichwort.value="";
}

function showStart(visible)
{
	if (visible == true) {
		toggle("unfold", "mapStart");
		toggle("unfold", "mapStartContainer");
	}
	else
		if (visible == false)
		{
			/*
			if (confirm("Sollen die Gemeinden ausgeblendet werden?"))
			{
				document.getElementById("cbKat87").checked = false;
				getMap().clearOverlays();
				categoryMarkersList[87] = new Array();
				markersArray = new Array();
				cluster.removeMarkers();
				cluster.refresh();
				changeExportLink();
			}*/
			toggle ("fold", "mapStart");
			toggle ("fold", "mapStartContainer");
		}
}

function clearMap()
{
	clearSearch();
	clearRoute();
	clearTraffic(getMap());
	categoryMarkersList = null;
	categoryMarkersList = new Array();
	markersArray = null;
	markersArray = new Array();
	
	cluster.removeMarkers();
	cluster.refresh();
	
	changeExportLink();
	
	loadTree(httpObject, hostFiller + "/xml/xml.php", "treeDiv", "-10");
}

function clearSearch()
{
	if (cityMarker)
		getMap().removeOverlay(cityMarker);
		
	document.getElementById("printValues").setAttribute("value", "");		
	document.getElementById("searchList").innerHTML = '<img src="' + hostFiller + '/images/filler.JPG" />';
	document.getElementById("searchList").style.backgroundColor = "#fde8b9";
	
	searchArr = null;
	searhAr = [];
	searchArrActive = null;
	searchArrActive = [];
	cluster.removeMarkers();
	cluster.addMarkers(markersArray);
	cluster.refresh();
	
	generateTheUrl();
}

/**
 * enter key event at internet explorer
 */ 
function evalKeyForSubmit(event, frm) 
{  
   if (event && event.keyCode == 13) // ENTER
      onSearchFormClick();
   else  
      return true;  
}  

/**
 * shows the oeamtc traffic infos
 */
function insertTraffic(map)
{
	var kml = new GGeoXml("http://www.oeamtc.at/verkehrsservice/output/google/oeamtc_verkehrsservice.kmz");
	//map.clearOverlays();
    map.addOverlay(kml) 
}

/**
 * deletes all oeamtc traffic info
 */
function clearTraffic(map)
{
	map.clearOverlays();
	cluster.removeMarkers();
	cluster.addMarkers(markersArray);
	cluster.addMarkers(searchArr);
	cluster.refresh();
}


/**
 * shows the category tree
 */
function showTree()
{
	toggle("unfold", "mainUL");
	toggle("fold", "directionDIV");
}

/**
 * shows the div with the direction results in it
 */
function showDirectionResult()
{
	toggle("unfold","directionDIV");
	toggle("fold", "mainUL"); 
}

/**
 * is called in the onload method of the index page
 */
function setupPages()
{
	toggle("fold", "mapStart");
	toggle("fold", "mapStartContainer");
	toggle("fold", "menuDIV");
	// toggle("fold", "mapLoad");
	toggle("fold", "mapLoadContainer");
	//toggle("fold", "searchList");
	toggle("fold", "fullscreenMenu");
	// toggle("fold", "catStart");
	toggle("fold", "catStartContainer");
	toggle("fold", "exportCardContainer");
	toggle("fold", "wheaterDIV");
	
	map.setCenter(new GLatLng(46.9052, 15.8381));
	map.savePosition();
	map.setZoom(10);
	draginit();
	setFullScreenLink();
}

function exportIt(type)
{
	if (document.exportForm.values.value.length == 0 && document.exportForm.track.value.length == 0 && document.exportForm.trail.value.length == 0)
	{
		alert ("Zum Exportieren sollten Punkte auf der Karte eingezeichnet sein");
		return;
	}
	toggle("fold", "exportCardContainer");
	if (type == "kml")
		document.exportForm.type.value = "kml";
	else if (type == "gpx")
		document.exportForm.type.value = "gpx";
	document.exportForm.submit();


}

/**
 * deletes all childs from the element
 */
function clearChilds(element)
{
	if ( element.hasChildNodes() )
	{
	    while ( element.childNodes.length >= 1 )
	    {
	        element.removeChild( element.firstChild );       
	    } 
	}
}

/**
 * sets the load div or not
 */
function setLoad(visible)
{
	if (visible == true)
	{
		toggle("unfold", "mapLoadContainer");
		// toggle("unfold", "loader");
	}
	else
	{
		toggle("fold", "mapLoadContainer");
		// toggle("fold", "loader");
	}
}

/**
 * displays the searchList div on the screen with show effect
 */
 
function showSearchList()
{
	$("#searchList").show("slow");
	document.getElementById("searchImg").src = hostFiller + "/images/icons/arrow_down.png";
	
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		document.getElementById("searchLink").removeAttributeNode(document.getElementById("searchLink").getAttributeNode("href"));
		document.getElementById("searchLink").onclick = hideSearchList;
	}
	else
	{
		document.getElementById("searchLink").setAttribute("onclick", "javascript: hideSearchList();");
	}	
}
/**
 * hides the searchList div on the screen with hide effect
 */
function hideSearchList()
{
	$("#searchList").hide("slow");
	document.getElementById("searchImg").src = hostFiller + "/images/icons/arrow_right.png";
	
	if (navigator.appName == "Microsoft Internet Explorer")
	{
		document.getElementById("searchLink").removeAttributeNode(document.getElementById("searchLink").getAttributeNode("href"));
		document.getElementById("searchLink").onclick = showSearchList;
	}
	else
	{
		document.getElementById("searchLink").setAttribute("onclick", "javascript: showSearchList(); ");
	}
}

/**
 * exports the whole map with poi's to kml
 */
 
 function changeExportLink()
 {
 	var arrM = [];
 	for(marker in markersArray)
 	{
 		if (markersArray[marker] != null)
 			arrM.push(markersArray[marker].tooltip);
 	}
 	document.getElementById("values").setAttribute("value", arrM);
 	
 	for(marker in searchArrActive)
 	{
 		if (searchArrActive[marker] != null)
 			arrM.push(searchArrActive[marker].tooltip);
 	}
 	document.getElementById("printValues").setAttribute("value", arrM);
 	document.getElementById("values").setAttribute("value", arrM);
 }
 
 function updateExportTrailTrack(id, trackOrCycle)
 {
 	if (trackOrCycle == 1)
 	{
 		document.exportForm.track.value = id;
 		document.exportForm.trail.value = "";
 	}
 	else if (trackOrCycle == 2)
 	{
 		document.exportForm.track.value = "";
 		document.exportForm.trail.value = id;
  }
  
}
/**
 * craetes the layer on the map with the fullscreen link
 */ 
function setFullScreenLink()
{
	var contextmenu = document.createElement("div");
	contextmenu.setAttribute("id", "fullscreenDiv");
    contextmenu.style.background = "#ffffff";
    contextmenu.style.border = "1px solid #8888FF";
    contextmenu.style.fontSize = "8pt";
    contextmenu.innerHTML = '<a href="javascript:void(0);" onclick="toFullScreen(); return false;" >Fullscreen</a>';
    getMap().getContainer().appendChild(contextmenu);

    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(getMap().getSize().width - 65,30));  
    pos.apply(contextmenu);
    
}
 
/**
 * changes the map to fullscreen mode
 */ 
function toFullScreen()
{
	fullScreenBool = true;
	//toggle("unfold", "fullscreenMenu");
	var mapDIV = document.getElementById("map_canvas");
	mapDIV.style.position = 'absolute';
	mapDIV.style.width = screen.availWidth - 20; 
	mapDIV.style.height = screen.availHeight-190;
	mapDIV.style.top = "0px";
	mapDIV.style.left = "0px";
	
	getMap().checkResize();
	
	var contextmenu = document.getElementById("fullscreenDiv");
  contextmenu.innerHTML = '<a href="javascript:void(0);" onclick="toSmallScreen(); return false;" >Beenden</a>';

  var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(getMap().getSize().width - 65,30));  
  pos.apply(contextmenu);
  
  
  var eleDiv = document.getElementById("elevationDIV");
  if (eleDiv)
  {
  	if (document.getElementById("elevation"));
  		getMap().getContainer().removeChild(document.getElementById("elevation"));
  	setElevationLink();
  	
  	var line = document.getElementById("line");
  	if (line)
  	{
  		//line.style.top = screen.availHeight - 195 + "px";
  		//line.style.left = screen.availWidth - 100;
  		line.style.zIndex = 2000;
  	}
  	//eleDiv.style.left = screen.availWidth-100; //"600px";
  	//eleDiv.style.top = screen.availHeight-50;
  }
  toggle("fold", "footer");
  
}

/**
 * reduces the full screen to normal size
 */
function toSmallScreen()
{
	toggle("unfold", "footer");
	var mapDIV = document.getElementById("map_canvas");
	var rightDIV = document.getElementById("mainRight");
	
	if (!navigator.appName == "Microsoft Internet Explorer")
		mapDIV.style.position = 'relative';

	mapDIV.style.width = rightDIV.offsetWidth;
	mapDIV.style.top = null;
	mapDIV.style.left = null;
	mapDIV.style.height = "482px";
		
	getMap().checkResize();
		
	var contextmenu = document.getElementById("fullscreenDiv");
  contextmenu.innerHTML = '<a href="javascript:void(0);" onclick="toFullScreen(); return false;" >Fullscreen</a>';

  var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(getMap().getSize().width - 65,30));  
  pos.apply(contextmenu);
  
  var div = document.getElementById("mainRight");
  var foot = document.getElementById("footer");  
	foot.style.position = "absolute";
	
	foot.style.top = "575px";
	foot.style.width = mapDIV.style.width;
	
	var eleDiv = document.getElementById("elevationDIV");
  if (eleDiv)
  {
  	if (document.getElementById("elevation"))
  		getMap().getContainer().removeChild(document.getElementById("elevation"));
  	setElevationLink();
  	
  	//eleDiv.style.left = screen.availWidth-100; //"600px";
  	//eleDiv.style.top = screen.availHeight-50;
  }
  fullScreenBool = false;
}

/**
 * creates the div with textfield for the url to this map
 * paramters in the url:
 * lat
 * lng
 * zoom
 */
function urlToMap()
{
		
	var map = document.getElementById("urlToMap");
	if (map)
		return;
	var urlDiv = document.createElement("div");
	urlDiv.setAttribute("id", "urlToMap");
	urlDiv.setAttribute("style", "position:absolute;top:0px;left:0px;height:80px;width:350px;background:#ff0000");
	
	if (navigator.appName != "Microsoft Internet Explorer")
		urlDiv.setAttribute("onmousedown", "dragstart(this)");
	
  urlDiv.style.background="#ffffff";
  urlDiv.style.padding = "3px";
  urlDiv.style.border="1px solid #8888FF";
  
  var innerHtml = "";
  innerHtml += "Link in E-Mail oder Instant Message einf&uuml;gen <br /><br /><a href='javascript:void(0);' onclick='closeUrlToMap()'>schlie&szlig;en</a><br /><br /><input type='text' size='60' id='urlText' onclick='selectText()' value='" + generateTheUrl() + "' />";
  
  urlDiv.innerHTML = innerHtml;
  getMap().getContainer().appendChild(urlDiv);

  var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(getMap().getSize().width /2 - 150,getMap().getSize().height /2));  
  pos.apply(urlDiv);
  
  GEvent.addListener(getMap(), "click", function() {
		closeUrlToMap();
	});
	GEvent.addListener(getMap(), "movestart", function() {
  		closeUrlToMap();
	});
}

/** 
 * generates the url to the actual site
 */
function generateTheUrl()
{
	
	var url = "http://www.karte.vulkanland.at/index.php?lng=" + getMap().getCenter().lng() + "&lat=" + getMap().getCenter().lat() + "&zoom=" + getMap().getZoom();
	
	var searchValue = document.searchForm.stichwort.value;
	if (searchValue != "")
		url += "&q=" + searchValue;
	
	if (actTrailID != 0)
		url += "&trailID=" + actTrailInstID;
		
	var cats = checkedCategories();
	if (cats != "")	
		url += "&cats=" + cats;
		
	var mapType = getMap().getCurrentMapType();
	url += "&maptype=" + mapType.getUrlArg();
	return url;
}


/** 
 * checks all checked categories and returns a delemittered string
 */
function checkedCategories()
{
	var cats = new Array();
	 var all = document.getElementById("treeDiv").getElementsByTagName('*');
	 var elements = new Array();
	 for (var e = 0; e < all.length; e++)
	 {
	
	    if (all[e].type == "checkbox" && all[e].checked == true)
	 	{
	 	
	 		var name = all[e].getAttribute("id");
	 		//alert(name.substring(5, name.length));
	 		cats.push(name.substring(5, name.length));
	 	}
	 }	
	 
	 return cats;
}
/**
 * selects the text in the input field by click
 */
function selectText()
{
	var obj = document.getElementById("urlText");
	obj.select();
}

/**
 * removes the div from the map
 */
function closeUrlToMap()
{
	var child = document.getElementById("urlToMap");
	if (child)
		getMap().getContainer().removeChild(child);
}

function eraseSearch()
{
	if (confirm("Suchergebnisse wirklich entfernen?"))
	{
		clearSearch();
		//hideSearchList();
		document.getElementById('stichwort').value = '';
	}
}

/**
 * gup => get url parameter
 * usage: gup("lat") - returns 2 in http://www.lustigeurl.com/?lat=2
 */
function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

/** 
 * clears the route on the map
 */
function clearRoute()
{
	if (gdir)
		if (confirm("Sind Sie sicher, dass Sie diese Route entfernen wollen?"))
		{
			if (gdir)
				gdir.clear();
			var clear = document.getElementById("routeClose");
			if (clear)
				getMap().getContainer().removeChild(clear);
				
			gdir = null;
			toggle("fold", "menuDIV");
			document.getElementById("treeDiv").style.height = "293px";
			document.printForm.direction.value = "";
			showTree();
		}
}

/**
 * generates a random value 0...1000
 */
function randomValue()
{
   var rand = Math.round(Math.random() * 1000) +1;
   return rand;
}

/**
 *  true - vulkanland betrieb
 *  false - no vulkanland betrieb
 */
function isVulkanlandBetrieb(details)
{
	if (isEmpf(details["katID1"]))
		return true;
	if (isEmpf(details["katID2"]))
		return true;
	if (isEmpf(details["katID3"]))
		return true;
	if (isEmpf(details["katID4"]))
		return true;
	if (isEmpf(details["katID5"]))
		return true;
	
	return false;
}
/**
 * checks categories for empfehlung or vulkanland betriebe
 */
function isEmpf(katID)
{
	if (katID == 103 || katID == 31 || katID == 32 || katID == 33 || katID == 34)
		return true;
}
function changeFont(pt)
{
	var body = document.getElementById("mainBody");
	body.style.fontSize = pt + "pt";
}
function printCard()
{
	//document.printForm.submit();
	//var newWin = window.open("print.php","Drucken","width=900,height=500");
	
	document.printForm.printZoom.value   = getMap().getZoom();
	document.printForm.printLat.value = getMap().getCenter().lat();
	document.printForm.printLng.value = getMap().getCenter().lng();
	document.printForm.submit();
	
}

/**
 * returns the name of the picture
 */
function getPictureName(details, id, nr)
{
		var ret = "http://www.vulkanland.at/upload/pics";
		ret += "/" + getProduktFolder(details) + "/produkte/";
		for(i = id.length; i < 11; i++)
		{
			ret += "0";
		}
		ret += id;
		ret += "." + nr + ".tn.jpg";
		return ret;
}

function getProduktFolder(details)
{
	var katID1 = details["katID1"];
	var katID2 = details["katID2"];
	var katID3 = details["katID3"];
	var katID4 = details["katID4"];
	var katID5 = details["katID5"];
	
	if ( katID1 == 31 || katID2 == 31 || katID3 == 31 || katID4 == 31  || katID5 == 31)
		return "kulinarik";
	if ( katID1 == 32 || katID2 == 32 || katID3 == 32 || katID4 == 32  || katID5 == 32)
		return "handwerksregion";
	if ( katID1 == 33 || katID2 == 33 || katID3 == 33 || katID4 == 33  || katID5 == 33)
		return "lebenskraft";
	if ( katID1 == 34 || katID2 == 34 || katID3 == 34 || katID4 == 34  || katID5 == 34)
		return "markenpartner";	
}

function loadCategorySymbol(cat)
{
	var httpObject = getHTTPObject();
	httpObject.open("GET",hostFiller + "/xml/getCategory.php?catID=" + cat, true);
	httpObject.setRequestHeader("If-Modified-Since","Sat, 1 Jan 2000 00:00:00 GMT");
	
	d = new Date();
	t = d.getTime();
	thetimestring=t.toString(16);
	
	httpObject.send(thetimestring);
	
	// event listener for readystatechanged
    httpObject.onreadystatechange = function() {
    
    // readyState 4 => open
    // status 200 => everything is ok
	if (httpObject.readyState == 4) {
		//alert(httpObject.status);
  		if (httpObject.status == "200") {
	  			// read the xml
			  	var xml = httpObject.responseXML;
				var inst = xml.getElementsByTagName("category");
		
				catSymbolArray[cat] = inst[0].getElementsByTagName("symbol")[0].lastChild.nodeValue;
			}
 		}
	}
}

