var mapLoaded = false;
var gm_callbackFunction;
var gm_select=false;
var gm_geocoder;
var gm_map;
var new_marker;
var gm_mng ;
var clickListener;

function mapsLoaded() {
  mapInitialize();
  if(gm_callbackFunction != undefined)gm_callbackFunction();
}

function loadMaps() {
  google.load("maps", "2", {"callback" : mapsLoaded});
}


function loadMap(GM_KEY, method,select){
    gm_callbackFunction = method;
	if(!select){gm_select = true}
	else {gm_select = false}
	if(!mapLoaded){
		var script = document.createElement("script");
		script.src = "http://www.google.com/jsapi?key="+GM_KEY+"&callback=loadMaps";
  		script.type = "text/javascript";
  		document.getElementsByTagName("head")[0].appendChild(script);
  		mapLoaded = true;
	} else {
		mapInitialize();
  		if(gm_callbackFunction != undefined)gm_callbackFunction();
	}
}

function mapInitialize(){    
 
     if(GBrowserIsCompatible())  // sprawdzamy, czy przeglądarka jest kompatybilna    
     {    
        gm_geocoder =  new GClientGeocoder();
        gm_map = new GMap2(document.getElementById("gm_map"));    
        gm_map.setCenter(new GLatLng(50.2612538275847,19.6435546875),7);    
		gm_mng =  new GMarkerManager(gm_map,{maxZoom: 19});        
        var mapControl = new GMapTypeControl();
		gm_map.addControl(mapControl);
		gm_map.addControl(new GLargeMapControl());
     }    
 }  


function showAddress(address) {
      if (gm_geocoder) {
        gm_geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " - nie znaleziono");
            } else {
              gm_map.setCenter(point,12);
            }
          }
        );
      }
}

function addNewMarker(lat,lon,my_ico,txt, options, extraParams){

	if(options == 'undefined' || options == null)
		options = new Object();
	options.icon = my_ico;
	
	var marker = new GMarker(new GLatLng(lat,lon),options);  
      marker.txt=txt;  
      GEvent.addListener(marker,"click",function() {  
          marker.openInfoWindowHtml(marker.txt);  
      }); 
       if(extraParams != 'undefined') {
       	 marker = $.extend(extraParams, marker);
       	/* for(iter in extraParams)
       		eval('marker.'+iter+' = extraParams[iter];'); */
       }
       
       return marker;  
}

function addAdminClickListener(){

		clickListener = GEvent.addListener(gm_map, "click", function(overlay,point) {     
		
			if(point){
				selectPoint = true;
				document.getElementById("gm_lat").value =point.y
				document.getElementById("gm_lng").value =point.x;
				new_marker.setPoint(point);
			}	
			});
}

function disableAdminClickListener(){
		GEvent.removeListener(clickListener);
}

 function toggleIconCateogry(category,show)  
 {  
     for(var i=0; i<markers.length; i++)  
     {  
         if(markers[i].category==category)  
         {  
             if(show==true)  
                 markers[i].show();  
             else  
                 markers[i].hide();  
         }  
     }  
 }  
   
 function refreshMap(checkbox,category)  
 {         
     if(document.getElementById(checkbox).checked)  
         toggleIconCateogry(category,true);  
     else  
         toggleIconCateogry(category,false);  
 } 
 
 function showPoint(lat,lng) {
     gm_map.setCenter(new GLatLng(lat,lng),14);    
}



///GMAPS CONTEXT MENU

function ContextMenu(oMap){this.initialize(oMap);}


ContextMenu.prototype.addMarkerMenuItem = function(menuTitle, method) {
	var val = {
		name: menuTitle,
		fireFunction: method
	};
	ContextMenu.prototype.markerMenuItems.push(val);
}
ContextMenu.prototype.removeMarkerMenuItems = function() {
	ContextMenu.prototype.markerMenuItems = new Array();
}

ContextMenu.prototype.removeMarkerMenuItems();

//Construct the DOM tree of the menu
ContextMenu.prototype.initLink = function(oMap, menuType, overlay){
	var that=this;
	
		
	a_link = document.createElement("li");
	a_link.innerHTML="<a href='javascript:void(0);'>&raquo;Wyśrodkuj tutaj</a>";
	GEvent.addDomListener(a_link, 'click', function() {
		var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
		that.map.panTo(point);
		that.contextmenu.style.display="none";
	});
	this.ul_container.appendChild(a_link);
		
	if(menuType == 'undefined' || menuType == null) {
		a_link = document.createElement("li");
		a_link.innerHTML="<a href='javascript:void(0);'>&raquo;Przybliż</a>";
		GEvent.addDomListener(a_link, 'click', function() {
			that.map.zoomIn();
			that.contextmenu.style.display='none';
		});
		this.ul_container.appendChild(a_link);
		
		a_link = document.createElement("li");
		a_link.innerHTML="<a href='javascript:void(0);'>&raquo;Oddal</a>";
		GEvent.addDomListener(a_link, 'click', function() {
			that.map.zoomOut();
			that.contextmenu.style.display='none';
		});
		this.ul_container.appendChild(a_link);
		
		a_link = document.createElement("li");
		a_link.id = 'createNewMarker';
		a_link.innerHTML="<a href='javascript:void(0);'>&raquo;Dodaj punkt tutaj</a>";
		GEvent.addDomListener(a_link, 'click', function() {
				var point = that.map.fromContainerPixelToLatLng(that.clickedPixel);
				var marker = addNewMarker(point.lat(), point.lng(), null, null, {draggable:true});
				eval('GMAPS_PLACES.markers.m_'+Math.ceil(Math.random())+' = marker');
				GEvent.addListener(marker, 'dragend', function() {
					GMAPS_PLACES.changeMarkerPosition(this);
				});
				that.map.addOverlay(marker);
				that.contextmenu.style.display="none";
		});
		this.ul_container.appendChild(a_link);
	} else if(menuType == 'marker') {
		
		var extraItems = ContextMenu.prototype.markerMenuItems;
		var name = 'title not defined!';
		ContextMenu.fireUserFunction = function() { that.contextmenu.style.display='none'; }
		for(i in extraItems) {
			a_link = document.createElement("li");
			name = extraItems[i].name;
			ContextMenu.currMenuItem = extraItems[i];
			a_link.innerHTML="<a href='javascript:void(0);' alt='"+i+"' >&raquo;"+name+"</a>";
			
			GEvent.addDomListener(a_link, 'click', function() {
				var i_ = $(this).find('a').attr('alt');
				ContextMenu.prototype.markerMenuItems[i_].fireFunction(overlay);
				that.contextmenu.style.display='none';
			});
			this.ul_container.appendChild(a_link);
		}
	}
}
ContextMenu.prototype.bind = function(method) {
	var self = this;
	var opt_args = [].slice.call(arguments, 1);
	return function() {
		var args = opt_args.concat([].slice.call(arguments));
		return method.apply(self, args);
	}
}

//The object 'constructor'
ContextMenu.prototype.initialize = function(oMap){
	this.map = oMap;
	var that=this;

//map context menu
	this.contextmenu = document.createElement("div");
	this.contextmenu.style.display="none";
//CSS class name of the menu
	this.contextmenu.className="contextmenu";
	this.ul_container = document.createElement("ul");
	this.ul_container.id="context_menu_ul";
	this.contextmenu.appendChild(this.ul_container);	
	this.initLink(null);
	this.map.getContainer().appendChild(this.contextmenu);


//Event listeners that will interact with our context menu
	GEvent.addListener(oMap,"singlerightclick",function(pixel,tile, overlay) {
		  
		that.clickedPixel = pixel;
		var x=pixel.x;
		var y=pixel.y;
//Prevents the menu to go out of the map margins, in this case the expected menu size is 150x110
		if (x > that.map.getSize().width - 160) { x = that.map.getSize().width - 160 }
		if (y >that.map.getSize().height - 120) { y = that.map.getSize().height - 120 }
		var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x,y));
		
		//click on the map
		if(overlay == null) {
			while ( that.ul_container.hasChildNodes() ) { that.ul_container.removeChild( that.ul_container.firstChild ); }
			that.initLink(null);
		} else { //click on the point
			while ( that.ul_container.hasChildNodes() ) { that.ul_container.removeChild( that.ul_container.firstChild ); }
			that.initLink(null, 'marker', overlay);
		}
		pos.apply(that.contextmenu);
		that.contextmenu.style.display = "";
		GEvent.addListener(oMap, "move", function() {
			that.contextmenu.style.display="none";
		});
		GEvent.addListener(oMap, "click", function(overlay,point) {
			that.contextmenu.style.display="none";
		});	
	});	
}

