	dojo.require("dojo.rpc.JsonService");
	dojo.require("dojo.fx");
	dojo.require("dojo.html");
	dojo.addOnLoad(initialize);
	
	// Variables
	var map;
	var alertService;
	
	
    
    
	
	/**
	 * Initialize the Map 
	 */
    function initialize() {
    
      alertService = new dojo.rpc.JsonService('/json/alert');
      
      if (GBrowserIsCompatible()) {
        	map = new GMap2(document.getElementById("map"));
        	map.setUIToDefault();
			map.setMapType(G_NORMAL_MAP);
      }
      
            //We try Google Ajax Api, if not we use oure default
      if (google.loader.ClientLocation) {
        map.setCenter(new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude), 13);
      }else{
        map.setCenter(new GLatLng(46.227638, 2.213749), 4);
      }
            
      GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {  
	  		loadAlerts();
	  });

	  GEvent.addListener(map, "moveend", function() {  
		    loadAlerts();  
	  });
	  
	  loadAlerts();
    }

    /**
    * getAlerts
    */
    function loadAlerts()
    {
		//Alerts list for current GPoint center
        var alertList = alertService.getAllBetweenLocations(map.getBounds().getSouthWest().lat() , map.getBounds().getSouthWest().lng(), map.getBounds().getNorthEast().lat(),map.getBounds().getNorthEast().lng());
        alertList.addCallback(displayAlerts);
  	  	alertList.addErrback(errback);  
    }
    
    /** 
     * Display alerts 
     */
    function displayAlerts(result){
    
   	    //Clear all existent overlay
    	map.clearOverlays();
    		
   		   
		// display the alerts
		for (var i=0; i < result.length; ++i) {
		  	alert = result[i];
		  	
		  	// Set up our GMarkerOptions object
			markerOptions = { icon:getIcon(alert) };
		
			map.addOverlay(new GMarker(new GLatLng(alert.latitude,alert.longitude),markerOptions));
		}

    }
    
    function getIcon(alert)
    {
    	// Create our "tiny" marker icon
		var sosIcon = new GIcon();
		sosIcon.iconSize = new GSize(24, 24);
		sosIcon.image = "/img/alerts/" + (alert.code+'').toLowerCase() + ".png";
		sosIcon.shadowSize = new GSize(24, 24);
		sosIcon.iconAnchor = new GPoint(12, 12);
		
		return sosIcon;
    }

    /** ErrBack for the Json function */
    function errback(result) {
	   alert(result);
	}