var urlStations = 'meteo/ajax/get-meteo-stations-infospots';
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));
              
/**
 * infospot marker image
 */
var infospotMarkerImage = new google.maps.MarkerImage('/assets/infospotIcon.png',
	      // This marker is 12 pixels wide by 12 pixels tall.
	      new google.maps.Size(16, 32),
	      // 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(8, 28));
              
/**
 * latitudes and longitud bound
 */
var latitudeSW;
var latitudeNE;
var longitudeSW;
var longitudeNE;

/**
 * meteostationMarkers array
 */
var meteostationMarkers = new Array();

/**
 * meteostationInfoBoxes array
 */
var meteostationInfoBoxes = new Array();

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);
    /*google.maps.event.addListenerOnce(gmap, 'tilesloaded',function()
    {
        if(latitudeSW != latitudeNE && longitudeSW != longitudeNE)
        {
            gmap.fitBounds(
                new google.maps.LatLngBounds(
                    new google.maps.LatLng(latitudeSW,longitudeSW),
                    new google.maps.LatLng(latitudeNE,longitudeNE)
            ));
        }
        else
        {
            gmap.setCenter(
                new google.maps.LatLng(latitudeSW,longitudeSW)
            );
        }
    })*/
    
    /**
     * aggiungo i markers delle stazioni meteo
     */
    addMeteoStationMarkers();
    
}

function start()
{
    if(latitudeSW != latitudeNE && longitudeSW != longitudeNE)
    {
        gmap.fitBounds(
            new google.maps.LatLngBounds(
                new google.maps.LatLng(latitudeSW,longitudeSW),
                new google.maps.LatLng(latitudeNE,longitudeNE)
        ));
    }
    else
    {
        gmap.setCenter(
            new google.maps.LatLng(latitudeSW,longitudeSW)
        );
    }   
    
    var f = function(){addMeteoStationInfoBoxes()};
    setInterval(f, 5000);
}

function addMeteoStationMarkers()
{
    $.get(
        jsCommon.baseUrl + '/' + jsCommon.locale + '/' + urlStations,
        {cache: counter},
        function (data)
        {
            $.each(data, function(index, item)
            {
                switch(index)
                {
                    case 'infospots':
                        parseInfospotsMarkers(item);
                        break;

                    case 'stations':
                        parseStationsMarkers(item);
                        break;
                }
            });
            start();
    });
}

function parseInfospotsMarkers(items)
{
    if(items.length > 0)
    {
        $.each(items, function(index, item)
        {
            getMapBounds(parseFloat(item.latitude), parseFloat(item.longitude));
            /**
            * creo il markers
            */
            var markerLatLng = new google.maps.LatLng(parseFloat(item.latitude), parseFloat(item.longitude));

            var marker = new google.maps.Marker({
                    position:       markerLatLng,
                    map:		gmap,
                    icon: 		infospotMarkerImage,
                    title: 		item.name
            });

            /**
             * event listener per quando termino il caricamento della mappa
             */
            google.maps.event.addListener(marker, 'click', function()
            {
                document.location.replace(jsCommon.baseUrl + '/' + jsCommon.locale + '/meteo/infospots/detail-infospot/id_infospot/' + item.id_infospot);
            });
        })  
    }
}

function parseStationsMarkers(items)
{
    if(items.length > 0)
    {
        $.each(items, function(index, item)
        {
            getMapBounds(parseFloat(item.latitude), parseFloat(item.longitude));
            /**
            * creo il markers
            */
            var markerLatLng = new google.maps.LatLng(parseFloat(item.latitude), parseFloat(item.longitude));

            var marker = new google.maps.Marker({
                            position: 		markerLatLng,
                            map:		gmap,
                            icon: 		meteostationMarkerImage,
                            title: 		item.name,
                            label_offset:	item.label_offset,
                            label_position:	item.label_position,
                            idInfospot:         item.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/' + item.id_station);
              });

            meteostationMarkers[item.id_station] = marker;
        })   
    }
}

function getMapBounds(latitude, longitude)
{
    if(latitudeSW != undefined)
    {
        if(latitude < latitudeSW)
            latitudeSW = latitude;
    }
    else
        latitudeSW = latitude;
    
    if(latitudeNE != undefined)
    {
        if(latitude > latitudeNE)
            latitudeNE = latitude;
    }
    else
        latitudeNE = latitude;
    
    if(longitudeSW != undefined)
    {
        if(longitude < longitudeSW)
            longitudeSW = longitude;
    }
    else
        longitudeSW = longitude;
    
    if(longitudeNE != undefined)
    {
        if(longitude > longitudeNE)
            longitudeNE = longitude;
    }
    else
        longitudeNE = longitude;
}

function addMeteoStationInfoBoxes()
{
	$.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:		gmap,
									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
                 */
                if(latitudeSW != latitudeNE && longitudeSW != longitudeNE)
                {
                    gmap.fitBounds(
                        new google.maps.LatLngBounds(
                            new google.maps.LatLng(latitudeSW,longitudeSW),
                            new google.maps.LatLng(latitudeNE,longitudeNE)
                    ));
                }
                else
                {
                    gmap.setCenter(
                        new google.maps.LatLng(latitudeSW,longitudeSW)
                    );
                }
            })

        /**
         * 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();
})
