var clickHandler;
var map;
var lat;
var lng;
var locations;
var bounds;


$(document).ready(function() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(50.077886, 14.447647), 13);
        
        if(content){
        	if(info==1)
        		show=1;
        	else 
        		show=0	
        	processLocations(content,show);
        }
    }
       
    
    $('a#zoom_show_all').click(function() {
        zoomShowAll();
    });

});

function setNewMarker(point) {
    $('div#formular').show('slow');
    $('a#new_location').show();
    $('div#info').hide();
    lat = point.lat();
    lng = point.lng();
    $('div#formular').find('p:nth-of-type(0) ').html('Latitude=<b>'+lat+'</b>, Longitude=<b>'+lng+'</b>');
    $('div#formular').show();
    GEvent.removeListener(clickHandler);
}

function processLocations(content,show) {
    eval("locations = "+content);
    $('p#location_list').html('');
   var lght = locations.length;
   for (var i = 0; i< lght; i++){
      	 createMark(locations[i],i,show)
      	  }
    
    zoomShowAll();
}


function createMark(loc,i,info){
			// create custom icon
			var relativepath = "http://www.city-info.cz/images/ico/ico_star.gif"; 
			var icon = new GIcon();
			icon.image = relativepath;
			icon.iconSize = new GSize(13, 13);
			icon.iconAnchor = new GPoint(6, 18);
			icon.infoWindowAnchor = new GPoint(5, 1);
	
		var marker = new GMarker(new GLatLng(loc.latitude, loc.longitude),icon);
           
		
		if(info==1){
        	GEvent.addListener(marker, 'click', function() {
            marker.openInfoWindowHtml('<br/><a href="detail/d'+loc.ubytovani_id+'/'+loc.url+'"><img width="92" height="92" src="http://www.city-info.cz/data_images/ubytovani/thumb/'+loc.ubytovani_id+'_01.jpg" class="maps_image"></a><b>'+loc.nazev+'</b><br /><br/>Adresa: <b>'+loc.lokalita+' '+loc.adresa+' '+loc.cislo_ulice+'</b><br/>www: <a href="detail/d'+loc.ubytovani_id+'/'+loc.url+'"><b>detailní informace</b></a><br/><br/><br/>');       
        	});
		}
        	
        	map.addOverlay(marker);
        	if(info){
        link = '<li><a  onclick="moveMapTo('+i+')">'+loc.nazev+'</a></li>';
        $('p#location_list').append(link);
        	}
}

function moveMapTo(i) {
    map.panTo(new GLatLng(locations[i].latitude, locations[i].longitude));
}

function zoomShowAll() {
    bounds = new GLatLngBounds();
    map.setCenter(new GLatLng(0,0),0);
    var lght = locations.length;
    for (var id = 0; id < lght; id++){
    	  		bounds.extend(new GLatLng(locations[id].latitude, locations[id].longitude));
    	}
       
    map.setZoom(map.getBoundsZoomLevel(bounds));
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
    map.setCenter(new GLatLng(clat,clng));
}
