var urlStations = 'meteo/ajax/get-meteo-stations';
var urlStationsData = 'meteo/ajax/get-meteo-stations-data';
/**
 * google.maps.Map object
 */
var gmap;

/**
 * counter for cache
 */
var counter = 0;

/**
 * centro di default della mappa
 */
var defaultMapCenterLatLng = new google.maps.LatLng(42.1, 13 );

/**
 * centro di default della mappa
 */
var defaultMapZoomLevel = 6;

/**
 * meteostation marker image
 */
var meteostationMarkerImage = new google.maps.MarkerImage('/assets/meteoStationIcon.png',
	      // This marker is 12 pixels wide by 12 pixels tall.
	      new google.maps.Size(13, 13),
	      // The origin for this image is 0,0.
	      new google.maps.Point(0,0),
	      // The anchor for this image is the center of the circle.
	      new google.maps.Point(6, 6));
/**
 * meteostationMarkers array
 */
var meteostationMarkers = new Array();

/**
 * meteostationInfoBoxes array
 */
var meteostationInfoBoxes = new Array();

/**
 * timer object
 */
var timer;

function initialize()
{
    var mapOptions = {
      zoom: defaultMapZoomLevel,
      center: defaultMapCenterLatLng,
      mapTypeControl: false,
      mapTypeId: google.maps.MapTypeId.SATELLITE,
      scrollwheel: false
    }
    gmap = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    
    /**
     * aggiungo i markers delle stazioni meteo
     */
    addMeteoStationMarkers(gmap);
    
}

function start(map)
{
	var f = function(){addMeteoStationInfoBoxes(map)};
	setInterval(f, 5000);
	//setTimeout(f, 5000);
}

function addMeteoStationMarkers(map)
{
	$.get(jsCommon.baseUrl + '/' + jsCommon.locale + '/' + urlStations,
            {cache: counter},
            function ($data)
            {
                $.each($data, function($index, $object)
                {
                    //alert($object.latitude);
                    /**
                    * creo i markers
                    */
                    var markerLatLng = new google.maps.LatLng(parseFloat($object.latitude), parseFloat($object.longitude));

                    var marker = new google.maps.Marker({
                            position: 		markerLatLng,
                            map:		map,
                            icon: 		meteostationMarkerImage,
                            title: 		$object.name,
                            label_offset:	$object.label_offset,
                            label_position:	$object.label_position,
                            idInfospot:         $object.id_infospot
                    });

                    /**
                     * event listener per quando termino il caricamento della mappa
                     */
                    google.maps.event.addListener(marker, 'click', function() {
                        document.location.replace(jsCommon.baseUrl + '/' + jsCommon.locale + '/meteo/stations/detail-station/id_station/' + $object.id_station);
                      });

                    meteostationMarkers[$object.id_station] = marker;
                });
            });
            start(map);
}

function addMeteoStationInfoBoxes(map)
{
	$.get(jsCommon.baseUrl + '/' + jsCommon.locale + '/' + urlStationsData,
			{
                            cache: counter,
                            useHeader: 1
                        },
			function ($data)
			{
				$($data).each(function()
					{
						/**
						 * recupero l'id della stazione
						 */
						if(typeof meteostationMarkers[this.id] != 'undefined')
						{
							if(counter > 0)
							{
								/**
								* aggiorno gli infobox
								*/
								meteostationInfoBoxes[this.id].setValueObject(this);
							}
							else
							{								
								//alert('creo infobox: ' + this.id);
								meteostationInfoBoxes[this.id] = new InfoBox({
									latlng: 	meteostationMarkers[this.id].getPosition(),
									map:		map,
									stationName:	meteostationMarkers[this.id].title,
									idInfospot:	meteostationMarkers[this.id].idInfospot,
									valueObject:	this,
									label_offset:	meteostationMarkers[this.id].label_offset,
									label_position:	meteostationMarkers[this.id].label_position,
									div_x_offset:	1,
									div_y_offset:	0
								});
							}
						};				
					});
					
					if(counter == 0) $('#realtime_box_identity,#realtime_box_not_identity').fadeOut('slow');
					
					counter++;
			});
}

var jsLocal =
{
    init: function()
    {

        /**
         * inizializzo il link per il reset della vista
         */
        $('.jqResetViewMap').click(function($evt)
            {
                $evt.preventDefault();
                /**
                 * creo il nuovo centro della mappa
                 */
                gmap.setCenter(defaultMapCenterLatLng);
                gmap.setZoom(defaultMapZoomLevel);
            })

        /**
         * map controls
         */
        $('.map_controls').click(function(evt)
            {
                evt.preventDefault();
                gmap.setMapTypeId($(this).attr('rel'));
            })

        /*
        yqlgeo.get('visitor',function(o)
        {
            if(o.error)
            {
                alert('No location found for user :(');
            }
            else
            {
                alert(o.place.name + ',' + o.place.country.content + ' (' + o.place.centroid.latitude + ',' +o.place.centroid.longitude + ')');
            }
        });
        */
    },
    
    modalWindow: function()
    {
        $('#dialog').jqm({
            modal: true,
            onHide: function(h)
            {
                if($('.jqmHide').attr('checked'))
                    $.cookie('jqmHide', $('.jqmHide').attr('jqmLastUpdate'),{expires: 7, path: '/', domain: '', secure: false});
                else
                    $.cookie('jqmHide', $('.jqmHide').attr('jqmLastUpdate'),{expires: 1, path: '/', domain: '', secure: false});
                h.w.hide();
                if(h.o)h.o.remove();
            }
        });
        
        /* se il cookie è attivo non mostro la finestra */
        if(!$.cookie('jqmHide') || jqmLastUpdate > $.cookie('jqmHide'))
        {
            $('#dialog').jqmShow();
        }
    }
}

$(document).ready(function(){
	jsLocal.init();
        jsLocal.modalWindow();
})

$(window).load(function(){
	initialize();
})
