// JavaScript Document
	
    var markers_html = "";
	var gmarkers = [];
    var a = 0;

       function megmutat(i) {
        GEvent.trigger(gmarkers[i], "click");
      }
	  
	  // == rebuilds the sidebar to match the markers currently displayed ==
      function makeSidebar(form) {
	    if (form == 'torol'){ document.getElementById("szukites").mezo.value = '';}
        var html = "";
        for (var i=0; i<gmarkers.length; i++) {
		ok = 'ok';
		for (var j=i-1; j>0; j--) {	
		  if ( gmarkers[i].myname == gmarkers[j].myname)
		  {
		  ok = 'nemok';
		  }  
		}
			  if ( gmarkers[i].whyhided == 'szukites')
			  {
			    gmarkers[i].show();
			  } 
			  if (!gmarkers[i].isHidden() && ok == 'ok' && gmarkers[i].myname.toLowerCase().search(document.getElementById("szukites").mezo.value.toLowerCase()) != -1)
			  {
				html += '<a href="javascript:megmutat(' + i + ')" onmouseover="mymouseover('+i+')" onmouseout="mymouseout()"><img src="http://budapest-view.info/ikonok/'+gmarkers[i].mypicture+'" style="border:none;">' + gmarkers[i].myname + '</a><br />';
				gmarkers[i].whyhided = '';
          	  }
			  else
			  {
			    if (document.getElementById("szukites").jelolok.checked && gmarkers[i].whyhided != 'kategoria')
				{
				  gmarkers[i].hide();
				  gmarkers[i].whyhided = 'szukites';
				}
			  }
		}
        document.getElementById("markers").innerHTML = html;
		if (form == 'form'){return false;}
      }
	  
	  // == a checkbox has been clicked ==
      function boxclick(box, category) {
        if (box.checked) {
          show(category);
        } else {
          hide(category);
        }
        // == rebuild the side bar
        makeSidebar();
      }
	  
	  // == shows all markers of a particular category, and ensures the checkbox is checked ==
      function show(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category && gmarkers[i].whyhided == 'kategoria') {
            gmarkers[i].show();
			gmarkers[i].whyhided = '';
          }
        }
		// == check the checkbox ==
        //document.getElementById( category +"box").checked = true;
      }

      // == hides all markers of a particular category, and ensures the checkbox is cleared ==
      function hide(category) {
        for (var i=0; i<gmarkers.length; i++) {
          if (gmarkers[i].mycategory == category) {
		    gmarkers[i].whyhided = 'kategoria';
            gmarkers[i].hide();
          }
        }
		// == clear the checkbox ==
        //document.getElementById( category +"box").checked = false;
        // == close the info window, in case its open on a marker that we just hid
        map.closeInfoWindow();
      }
	  
	  function createMarker(point,html,ikon, name, category, picture,visible) {
        var marker = new GMarker(point,ikon);
		marker.tooltip = '<div class="tooltip"><nobr>'+name+'</nobr></div>';
		maxWidth = 420;
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html,{maxWidth:maxWidth});
        });
		// save the info we need to use later for the side_bar
		gmarkers[a] = marker;
		gmarkers[a].mycategory = category;   
		gmarkers[a].mypicture = picture;                               
        gmarkers[a].myname = name;
		gmarkers[a].myvisible = visible;
        a++;

        map.addOverlay(marker);

        //  ======  The new marker "mouseover" and "mouseout" listeners  ======
        GEvent.addListener(marker,"mouseover", function() {
          showTooltip(marker);
        });        
        GEvent.addListener(marker,"mouseout", function() {
		tooltip.style.visibility="hidden"
        }); 
      }
	  
      function showTooltip(marker) {
	  	tooltip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var height=tooltip.clientHeight;
	var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height)); 
	pos.apply(tooltip);
	tooltip.style.visibility="visible";
      }
	  
	  // It launches the tooltip on the icon      
      function mymouseover(i) {	
	    gmarkers[i].show();
		showTooltip(gmarkers[i])
      }
      // ===== This function is invoked when the mouse leaves an entry in the side_bar =====
      // It hides the tooltip      
      function mymouseout() {
	tooltip.style.visibility="hidden";
      }
	  
	  function hidepoly()
	  {
		  map.removeOverlay(m[0]);
		  map.removeOverlay(m[1]);
		  map.removeOverlay(m[2]);
	  }
	  function showpoly()
	  {
		  map.addOverlay(m[0]);
		  map.addOverlay(m[1]);
		  map.addOverlay(m[2]);
	  }
	  function showAddress(address) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " nem található");
            } else {
              map.setCenter(point, 13);
              var marker = new GMarker(point);
			  marker.tooltip = '<div class="tooltip"><nobr>'+address+'</nobr></div>';
              map.addOverlay(marker);
              marker.openInfoWindowHtml(address);
			  GEvent.addListener(marker, "click", function() {
				marker.openInfoWindowHtml(address);
              });
			  GEvent.addListener(marker,"mouseover", function() {
				showTooltip(marker);
			  });        
			  GEvent.addListener(marker,"mouseout", function() {
				tooltip.style.visibility="hidden"
			  }); 
            }
          }
        );
      }
    }
	function geocod ()
	{
	    geocoder.getLatLng(
          document.getElementById('cim').address2.value,
          function(point) {
            if (point) {
              toAddress = point.y+', '+point.x;
            }
          }
        );
		document.getElementById('cim').plan.value = "kérlek várj - 1";
	}
	
	function getDirections(locale) {
      gomb = document.getElementById('cim').plan.value;
	  document.getElementById('cim').plan.value = "kérlek várj - 2";
	  if (geocoder) {
        geocoder.getLatLng(
          document.getElementById('cim').address.value,
          function(point) {
            if (point) {
              fromAddress = point.y+', '+point.x;
            }
          }
        );
        setTimeout("geocod();",1000);
      }
	  setTimeout("setDirections();",2000);
    }
	
	function setDirections() {
		gdir.load("from: " + fromAddress + " to: " + toAddress);
		/*gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": locale });*/
		document.getElementById('cim').plan.value = "kérlek várj - 0";
		document.getElementById('cim').plan.value = gomb;
		
		turnonLayer('route');
		turnoffLayer('markers');
		turnonLayer('choose');
	}
	
	function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
	}

	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}
	
      // === functions that perform the context menu options ===
      function newMarker() {
		contextmenu.style.visibility="hidden";
		var point = map.fromContainerPixelToLatLng(clickedPixel)
		var newmarker = new GMarker(point, {draggable: true}); 
		newmarker.enableDragging();
		var name = prompt("Írd be a jelölo nevét", "");
		if (name == false || name == null || name.length == 0) {
		 name = 'Új jelölo '+ ujjelolo;
		  ujjelolo++;
		}
		newmarker.tooltip = '<div class="tooltip"><nobr>'+name+'</nobr></div>';
        map.addOverlay(newmarker);
		buborek = '<b><div id="newmarker">'+name+'<br /><a href="add.php?mi=jelolo&latlng='+point.toString().substr(1,point.toString().length - 2)+'&name='+name+'">Jelölo elküldése</a><\/div><\/b>';
        newmarker.openInfoWindowHtml(buborek);
		GEvent.addListener(newmarker, "click", function() {
			newmarker.openInfoWindowHtml(buborek);
        });
		GEvent.addListener(newmarker,"mouseover", function() {
			showTooltip(newmarker);
		});        
		GEvent.addListener(newmarker,"mouseout", function() {
			tooltip.style.visibility="hidden"
		}); 
      }
	  function from() {
        // perform the requested operation
        var point = map.fromContainerPixelToLatLng(clickedPixel)
		document.getElementById('cim').address.value = point.y+','+point.x;
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      }
	  function frommarker(i) {
        // perform the requested operation
		point = gmarkers[i].getPoint();
		document.getElementById('cim').address.value = point.y+','+point.x;
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      } 
	  function to() {
        // perform the requested operation
        var point = map.fromContainerPixelToLatLng(clickedPixel)
		document.getElementById('cim').address2.value = point.y+','+point.x;
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      }
	  function tomarker(i) {
        // perform the requested operation
		point = gmarkers[i].getPoint();
		document.getElementById('cim').address2.value = point.y+','+point.x;
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      } 
	  function zoomIn() {
        // perform the requested operation
        map.zoomIn();
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      } 
      function zoomOut() {
        // perform the requested operation
        map.zoomOut();
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      }      
      function zoomInHere() {
        // perform the requested operation
        var point = map.fromContainerPixelToLatLng(clickedPixel)
        map.zoomIn(point,true);
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      }      
      function zoomOutHere() {
        // perform the requested operation
        var point = map.fromContainerPixelToLatLng(clickedPixel)
        map.setCenter(point,map.getZoom()-1); // There is no map.zoomOut() equivalent
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      }      
      function centreMapHere() {
        // perform the requested operation
        var point = map.fromContainerPixelToLatLng(clickedPixel)
        map.setCenter(point);
        // hide the context menu now that it has been used
        contextmenu.style.visibility="hidden";
      }
	  
	  
	  function unique(a) {
		  tmp = new Array(0);
		  for(i=0;i<a.length;i++){
			  if(!contains(tmp, a[i])){
				  tmp.length+=1;
				  tmp[tmp.length-1]=a[i];
			  }
		  }
	      return tmp;
	  }
	  
	function CustomGetTileUrl(a,b) {
		
		if (b==12 && a.x>=2262 && a.x<=2267 && a.y>=1430 && a.y<= 1434) {
			return "http://open.atlas.free.fr/PlayGround/GD_Lib/budapest-view/Tiles/kerekpar1/Tile_"+(a.x)+"_"+(a.y)+"_"+b+".jpg";
			} else {
			return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
			}
	}

	  function CustomGetTileUrl(a,b) {
      //converts tile x,y into keyhole string

    	var c=Math.pow(2,b);

        
        var d=a.x;
		var e=a.y;
		//alert(d+' '+e);
		var f="t";
        for(var g=0;g<b;g++){
            c=c/2;
            if(e<c){
                if(d<c){f+="q"}
                else{f+="r";d-=c}
            }
            else{
                if(d<c){f+="t";e-=c}
                else{f+="s";d-=c;e-=c}
            }
        }
        return "http://budapest-view.info/kerekparterkep-tiles/"+f+".jpg"
    }


