var map = null;
var geocoder = null;
var directionsPanel, directions, here;
var gmarkers = [];

var loaded = false; 

var iconBlue = new GIcon();
iconBlue.image = 'images/mm_20_blue.png';
iconBlue.shadow = 'images/mm_20_shadow.png';
iconBlue.iconSize = new GSize(12, 20);
iconBlue.shadowSize = new GSize(22, 20);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 1);

var iconRed = new GIcon();
iconRed.image = 'images/mm_20_red.png';
iconRed.shadow = 'images/mm_20_shadow.png';
iconRed.iconSize = new GSize(12, 20);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(6, 20);
iconRed.infoWindowAnchor = new GPoint(5, 1);

var iconGreen = new GIcon();
iconGreen.image = 'images/mm_20_green.png';
iconGreen.shadow = 'images/mm_20_shadow.png';
iconGreen.iconSize = new GSize(12, 20);
iconGreen.shadowSize = new GSize(22, 20);
iconGreen.iconAnchor = new GPoint(6, 20);
iconGreen.infoWindowAnchor = new GPoint(5, 1);

var customIcons = [];
customIcons["program"] = iconRed;
customIcons["szallas"] = iconGreen;
customIcons["vendeglato"] = iconBlue;



function setDirections(fromAddress, toAddress) {
	      directions.load("from: " + fromAddress + " to: " + toAddress);
}


function createMarker(point, type, name, town, address, description, id, link, image, load_type) {  
	var marker = new GMarker(point, {icon: customIcons[type], title: name + " - " + town + ", " + address});  

    GEvent.addListener(marker, "click", function() {    
	here = point.toString();
	here = here.substring(1,here.length-1);
	var html = "<a href=# onclick='document.forms.direction.from.value=here;'>innen</a> || ";
	html = html + "<a href=# onclick='document.forms.direction.to.value=here;'>ide</a><br>";

    var img_substr = image.substring(0,5);
	var tab = "<div style='width: 380px; height: 150px;'><img src='upload/" + img_substr + "/tn_" + image + "' border=0 align=left style='padding-right: 16px;'><span style='font-weight: bold; color: #444444; text-transform: uppercase'>" + name + "</span><br/>";
	tab += town + ", " + address + "<br/><br />";
	tab += description;
	if (link != "")
	{
		tab += "<a ";
		//if (load_type != "0") { tab += "onclick=\"opener.location='" + link + "'\" href=#"; }
		//else { tab += "href='" + link + "'"; }
		tab += "href='" + link + "' target=_blank";
		tab += ">bővebben &raquo;</a>";
	}
	tab += "</div>";


	var infoTabs = [  
	    new GInfoWindowTab("Info", tab),  
	    new GInfoWindowTab("Útvonalterv", html)
	    ];
	
	marker.openInfoWindowTabsHtml(infoTabs);

	}); 
	marker.mycategory = type;
	marker.myid = id;
	marker.point = point;
    gmarkers.push(marker);
	return marker;
}


function createMarkerSimple(point, town) {  
	var marker = new GMarker(point, {icon: customIcons['program'], title: town});  
	marker.point = point;
	marker.mycategory = 'utazas';
    gmarkers.push(marker);
	return marker;
}


// == a checkbox has been clicked ==
function boxclick(box,category) {
	if (box.checked) {
       show_markers(category);
    } else {
       hide_markers(category);
    }
}

// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show_markers(category) {
   
	process_it = function(doc) {

		// === Parse the JSON document === 
	    var jsonData = eval('(' + doc + ')');

		// === Plot the markers ===
	    for (var i=0; i<jsonData.length; i++) {

			point = new GLatLng(jsonData[i].lat, jsonData[i].lang);
			var marker = createMarker(point, jsonData[i].type, jsonData[i].name, jsonData[i].town, jsonData[i].address, jsonData[i].description, jsonData[i].id, jsonData[i].link, jsonData[i].image, category);
			map.addOverlay(marker); 

	    }


	   for (var i=0; i<gmarkers.length; i++) {
		   if (gmarkers[i].mycategory == category) {
				gmarkers[i].show();
			}
		}
	}

	if (loaded == false) {
		GDownloadUrl("ajax.php?method=get_hotels_for_map", process_it);
		loaded = true;
	}
	else {
	   for (var i=0; i<gmarkers.length; i++) {
		 if (gmarkers[i].mycategory == category) {
		   gmarkers[i].show();
	     }
	   }
	}


   document.getElementById(category+"box").checked = true;
}


// == shows a specific marker of a particular category ==
function show_marker_specific(category, id) {
   for (var i=0; i<gmarkers.length; i++) {
     if ((gmarkers[i].mycategory == category) && (gmarkers[i].myid == id)) {
       gmarkers[i].show();
       map.setCenter(gmarkers[i].point, 10);
     }
   }
}

// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide_markers(category) {
   for (var i=0; i<gmarkers.length; i++) {
     if (gmarkers[i].mycategory == category) {
       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 load(load_type, load_id, varosok) {
 if (GBrowserIsCompatible()) {

	var point, marker_n;
	var addressMarker;
	var loadtype = load_type;


    map = new GMap2(document.getElementById("map"));
    directions = new GDirections(map, document.getElementById("directions"));
	
       
	var geocoder = new GClientGeocoder();
    map.addMapType(G_SATELLITE_3D_MAP);
	
    //map.addControl(new GHierarchicalMapTypeControl());
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());

	map.enableScrollWheelZoom();
	map.enableContinuousZoom();
	map.getContainer().style.overflow="hidden";
	
	function wheelevent(e) {
	 if (!e){
	 e = window.event
	 }
	 if (e.preventDefault){
	 e.preventDefault()
	 }
	 e.returnValue = false;
	}

	GEvent.addDomListener(map.getContainer(), "DOMMouseScroll", wheelevent);
	map.getContainer().onmousewheel = wheelevent; 
	


	if (load_type == "utazas")
	{

		 var geo_lats = document.getElementById('geo_lat').value.split("|");
		 var geo_langs = document.getElementById('geo_lang').value.split("|");
		 var towns = document.getElementById('town').value.split("|");

		 map.setCenter(new GLatLng(geo_lats[0], geo_langs[0]));
		 var bounds = new GLatLngBounds();

		 for (var i=0; i<geo_lats.length; i++) {
	        point = new GLatLng(geo_lats[i], geo_langs[i]);
			bounds.extend(point);
			var marker = createMarkerSimple(point, towns[i]);
			map.addOverlay(marker);
         }

		if (varosok == 0)
		{
		 map.setZoom(map.getBoundsZoomLevel(bounds));
		 map.setCenter(bounds.getCenter());
		}
		else {	// velenceikarneval.hu
		 map.setZoom(13);
		}

	}
	else if (load_type == "program" || load_type == "szallas") {

		var geo_lat = document.getElementById('geo_lat').value;
		var geo_lang = document.getElementById('geo_lang').value;
		var point = new GLatLng(geo_lat, geo_lang);
		var name = document.getElementById('town').value;
		var zoom_level = parseInt(document.getElementById('zoom_level').value);

		if (geo_lat != "0.000000") {
			map.setCenter(point, zoom_level, G_NORMAL_MAP);
			var marker = createMarkerSimple(point, name);
			map.addOverlay(marker);
		}
	    else map.setCenter(new GLatLng(47.44, 19.14), 8);
	}
	else {

		var geo_lat = document.getElementById('geo_lat').value;
		var geo_lang = document.getElementById('geo_lang').value;
		var point = new GLatLng(geo_lat, geo_lang);
		var zoom_level = parseInt(document.getElementById('zoom_level').value);
	
		if (geo_lat != "0.000000") map.setCenter(point, zoom_level, G_NORMAL_MAP);
	    else map.setCenter(new GLatLng(47.44, 19.14), 8);

	}
	
	
  }
}


/* az admin felületen ez tölti be a térképet */

function loader(lat, lang) {
 if (GBrowserIsCompatible()) {

    map = new GMap2(document.getElementById("map"));
        
	var geocoder = new GClientGeocoder();
    map.addMapType(G_SATELLITE_3D_MAP);
	
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());


	GEvent.addListener(map, "click", function(latlng) {  
        var mark = new GMarker(latlng, {draggable: true});
		map.addOverlay(mark);
	});

	map.enableScrollWheelZoom();
	map.enableContinuousZoom();
	map.getContainer().style.overflow="hidden";
	
	function wheelevent(e) {
	 if (!e){
	 e = window.event
	 }
	 if (e.preventDefault){
	 e.preventDefault()
	 }
	 e.returnValue = false;
	}

	GEvent.addDomListener(map.getContainer(), "DOMMouseScroll", wheelevent);
	map.getContainer().onmousewheel = wheelevent; 

	var point = new GLatLng(lat, lang);
	map.setCenter(point, 8);
	/*var marker = createMarkerSimple(point);
	map.addOverlay(marker);*/

  }
}



function getAddress(formname) {
	var geocoder = new GClientGeocoder();

	if (formname == 'place') {  var country_id = document.place.country_id[document.place.country_id.selectedIndex].value;	}
	else { var country_id = document.szallas.country_id[document.szallas.country_id.selectedIndex].value; }

 	var jsonRequest = new Request.JSON({url: "/ajax.php", onComplete: function(reply){
	if (reply.text == "OK")	{
				 var resp = reply.answer;
				 if (formname == 'place')
				 {
					 var addr = resp + ", " + document.place.zip.value + " " + document.place.town.value + " " + document.place.address.value;
				 }
				 else var addr = resp + ", " + document.szallas.szallas_zipcode.value + " " + document.szallas.town.value + " " + document.szallas.szallas_address.value;

				 geocoder.getLatLng( addr, function(point) {
				 if (!point) { alert("A cím koordinátáit nem sikerült meghatározni!\n" + addr); }
				 else { 
					alert("OK!");
					if (formname == 'place') {
					 document.place.geo_lat.value = point.lat();
					 document.place.geo_lang.value = point.lng();
					}
					else {
					 document.szallas.geo_lat.value = point.lat();
					 document.szallas.geo_lang.value = point.lng();
					}
					}
				 });
	}
	else {
		alert (reply.text);
	}
	}}).get({'method': 'get_country', 'country_id': country_id });

}



function getGPS(index) {

	var geocoder = new GClientGeocoder();
	var myTable = document.getElementById('destination');
	var tBody = myTable.getElementsByTagName('tbody')[0];
	var country_select = tBody.rows[index].cells[0].childNodes[0];
	var country_id = country_select[country_select.selectedIndex].value;
	var town = tBody.rows[index].cells[2].childNodes[0].value;
	var geo_lat_input = tBody.rows[index].cells[3].childNodes[0];
	var geo_lang_input = tBody.rows[index].cells[4].childNodes[0];

 	var jsonRequest = new Request.JSON({url: "/ajax.php", onComplete: function(reply){
	if (reply.text == "OK")	{

				 var resp = reply.answer;
				 var addr = resp + ", " + town;
				 geocoder.getLatLng( addr, function(point) {
					if (!point) { alert("A koordinátákat nem sikerült meghatározni!\n" + addr); }
					 else { 
					 geo_lat_input.value = point.lat();
					 geo_lang_input.value = point.lng();
					}
				  });
	}
	else {
		alert (reply.text);
	}
	}}).get({'method': 'get_country', 'country_id': country_id });
}


/**
 * Concatenates the values of a variable into an easily readable string
 * by Matt Hackett [scriptnode.com]
 * @param {Object} x The variable to debug
 * @param {Number} max The maximum number of recursions allowed (keep low, around 5 for HTML elements to prevent errors) [default: 10]
 * @param {String} sep The separator to use between [default: a single space ' ']
 * @param {Number} l The current level deep (amount of recursion). Do not use this parameter: it's for the function's own use

function print_r(x, max, sep, l) {

	l = l || 0;
	max = max || 10;
	sep = sep || ' ';

	if (l > max) {
		return "[WARNING: Too much recursion]\n";
	}

	var
		i,
		r = '',
		t = typeof x,
		tab = '';

	if (x === null) {
		r += "(null)\n";
	} else if (t == 'object') {

		l++;

		for (i = 0; i < l; i++) {
			tab += sep;
		}

		if (x && x.length) {
			t = 'array';
		}

		r += '(' + t + ") :\n";

		for (i in x) {
			try {
				r += tab + '[' + i + '] : ' + print_r(x[i], max, sep, (l + 1));
			} catch(e) {
				return "[ERROR: " + e + "]\n";
			}
		}

	} else {

		if (t == 'string') {
			if (x == '') {
				x = '(empty)';
			}
		}

		r += '(' + t + ') ' + x + "\n";

	}

	return r;

};
var_dump = print_r;
 */