var fieramap;
var geoXml;
var geoXml_p;
var directionsDisplay;
var geocoder;
var ne;
var sw;
var initLatlng;
var initLat=45.488822;    // Vicomarino  44.9815898
var initLng=9.134977;     // Centro, 46  9.39255
var initZoom=10;

var dhxAccord;
var dhxcombo;

var eventi = new Array();
eventi['Cat_C'] = new Array();
eventi['Cat_L'] = new Array();
eventi['Cat_Vv'] = new Array();
eventi['Cat_P'] = new Array();
eventi['Cat_Va'] = new Array();
var segnaposti = new Array();

// 
function getTratteColorate()
{
    var resp = '';
    var ajax = ajaxObj();
    ajax.open('GET', "tratte_colorate.php", false);
    ajax.send(null);
    if(ajax.status == 200) {
        resp= ajax.responseText;
    }
    return resp;
}

/*
 * funzione di inizializzazione del tutto
 */

function initialize()
{
    // google maps
    if (GBrowserIsCompatible()) {
        // creo la mappa

        fieramap = new GMap2(elemento("map_canvas"));
        initLatlng = new GLatLng(initLat, initLng);
        fieramap.setCenter(initLatlng, initZoom);
        //fieramap.setUIToDefault();
        var customUI = fieramap.getDefaultUI();
        customUI.controls.largemapcontrol3d = true;
        customUI.controls.scalecontrol = true;
        customUI.controls.menumaptypecontrol = true;
        fieramap.setUI(customUI);
        //fieramap.addControl(new GMapTypeControl());
        //fieramap.addControl(new GLargeMapControl3D());
        //fieramap.addControl(new GScaleControl());
        
        // aggiungo la mappina
        fieramap.addControl(new GOverviewMapControl(new GSize(156,120)));

        var bounds = fieramap.getBounds();
        ne = bounds.getNorthEast();
        sw = bounds.getSouthWest();

        // aggiungo le autostrade
        geoXml = new GGeoXml('http://www.radiotraffic.it/kml/autostrade.kmz');      // versione tutt'Italia
//        geoXml = new GGeoXml('http://www.radiotraffic.it/kml/auto_lomb.kml');       // versione solo Lombardia
        fieramap.addOverlay(geoXml);
        // aggiungo le tratte colorate
        //tratcol = getTratteColorate();
        //if (tratcol) {
            //geoXml = new GGeoXml('http://www.radiotraffic.it/kml/'+tratcol);
            //fieramap.addOverlay(geoXml);
        //}
        // aggiungo i parcheggi
        geoXml_p = new GGeoXml('http://www.radiotraffic.it/kml/ParcheggiFiera.kmz');
        fieramap.addOverlay(geoXml_p);
        
        GEvent.addListener(fieramap, 'moveend', area_visibile);
        // quello che serve per i percorsi
        directionsDisplay = new GDirections(fieramap, elemento("directionsPanel"));
        GEvent.addListener(directionsDisplay, "load", rispostaPercorso);
        GEvent.addListener(directionsDisplay, "error", handleErrors);

        // accordion
        dhxAccord = new dhtmlXAccordion("accordObj", "dhx_fierami");
        dhxAccord.setIconsPath("dhtmlx/imgs/dhxaccord_dhx_fierami");
        dhxAccord.addItem("path", "Crea percorso");
        dhxAccord.cells("path").attachObject("divPercorsi");
        dhxAccord.addItem("sit", "Criticità");
        dhxAccord.cells("sit").attachObject("divEventi");
        dhxAccord.cells("sit").open();
        
        // combo
        dhxcombo = dhtmlXComboFromSelect("arrivo");
        dhxcombo.readonly(false);
        
//        elemento("Cat_C").checked = true;
//        elemento("Cat_Va").checked = true;
        setTimeout("fairefresh()",5000);
    } else {
        alert("Il browser utilizzato non e' compatibile con gli oggetti rappresentati in questa pagina.\n"+
              "Scarica Firefox gratuitamente dal sito di Mozilla");
    }
}

function destroy()
{
    GUnload();
}

function centramappa()
{
    fieramap.setCenter(initLatlng, initZoom);
}

function zooma_fiera()
{
    var fieraLatlng = new GLatLng(45.52084, 9.08117);
    fieramap.setCenter(fieraLatlng, 14);
}

/*
 * calcolo del percorso e centro su una localita'
 */
function php_urlencode (str) {
str = escape(str);
return str.replace(/[*+\/@]|%20/g,
function (s) {
switch (s) {
case "'": s = "%27"; break;
case "*": s = "%2A"; break;
case "+": s = "%2B"; break;
case "/": s = "%2F"; break;
case "@": s = "%40"; break;
}
return s;
}
);
}

function stampaPercorso()
{
    var fieraLatLng = fieramap.getCenter();
    var attr = "width=800,height=600,location=no,menubar=yes,status=no,toolbar=yes,scrollbars=yes,resizable=yes";
    var start = elemento("partenza").value;
    //var end = elemento("arrivo").value;
    var end = dhxcombo.getActualValue();
    var URL = "stampapercorso.php?A="+fieraLatLng.lat()+"&B="+fieraLatLng.lng()+"&C="+fieramap.getZoom()+"&D="+php_urlencode(start)+"&E="+php_urlencode(end)+"&F="+elemento('noautostrade').checked;
    var me=window.open(URL, "Fiera Milano - Percorsi", attr);
    me.focus();
}

function rispostaPercorso(response, status)
{
    elemento('stampa').style.visibility = 'visible';
}

function calcolaPercorso()
{
    var opts = {};
    var start = elemento("partenza").value;
    //var end = elemento("arrivo").value;
    var end = dhxcombo.getActualValue();
    /*if (end.toUpperCase() == 'FIERAMILANO') {
        end = 'Piazzale Sud Est Rho';
    }*/
    /*if (elemento("apiedi").checked) {
        opts.travelMode = G_TRAVEL_MODE_WALKING;
    }*/
    if (elemento("noautostrade").checked) {
        opts.avoidHighways = true;
    }
    opts.locale='it_IT';
    directionsDisplay.load("from: " + start + " to: " + end, opts);
}

function trovaLocalita()
{
    geocoder = new GClientGeocoder();
    // geocoder.setViewPort(); se voglio restringere la ricerca
    geocoder.setBaseCountryCode("it");   // ma dovrebbe essere gia' il default
    //alert(geocoder.getBaseCountryCode());
    var address = elemento("localita").value+' Italia';
    if (geocoder) {
        geocoder.getLatLng(address, function(point) {
            if (point) {
                fieramap.setCenter(point, 11);
                marker = new GMarker(point);
                fieramap.addOverlay(marker);
                segnaposti.push(marker);
            } else {
                alert("Non ho trovato "+address);
            }
        });
    }
}

function cancellaLocalita()
{
    for (s in segnaposti) {
        // tolgo il marker dalla mappa
        fieramap.removeOverlay(segnaposti[s]);
    }
    // svuoto l'array
    segnaposti.splice(0, segnaposti.length());
}

/*
 * aggiunta ed eliminazione degli eventi sulla mappa e nell'accordion
 */

// estrai: richiede gli eventi in formato JSON
function estrai(where, order)
{
    var ajax = ajaxObj();
    ajax.open('GET', "load_rec.php?where="+where+'&order='+order, false);
    ajax.send(null);
    if(ajax.status == 200)
        var resp= ajax.responseText;
    return eval('('+resp+')');
}

function esiste_evento(indice, eid)
{
    for (j=0;j<eventi[indice].length;j++) {
        if (eventi[indice][j].situazione == eid) {
            return j;
        }
    }
    return -1;
}

function aggiungi_punti(dati)
{
    for (k=0;k<dati.length;k++){
        indice = dati[k]['F_WEBCATEGORY'];
        var esiste = esiste_evento(indice, dati[k]['F_ID']);
        if (esiste == -1) {
            var evento = new eventoTraffico(fieramap, dati[k]);
            eventi[indice].push(evento);
        }
    }
}

function refresh(id)
{
    var len = 0;
    var i = 0;
    if (elemento(id).checked) {
        var where = "(F_WEBCATEGORY='"+id+"')";
        where += ' and (F_XCOORD_DA between '+sw.lng()+' and '+ne.lng()+') and (F_YCOORD_DA between '+sw.lat()+' and '+ne.lat()+')';
        var dati=estrai(where, 'G_CHAR_STRADA(F_ROADNUMBER), G_NUM_STRADA(F_ROADNUMBER), F_LOCNAME_DA');
        if (typeof(dati) == 'string') return;
        //togli_elenco(id);
        len = eventi[id].length;
        // marco gli evevnti come obsoleti
        for (i=0;i<len;i++) {
            if (eventi[id][i]) eventi[id][i].marca('O');
        }
        aggiungi_punti(dati);
        // puo' essere cambiato da aggiungi punti
        len = eventi[id].length;
        // cancello gli obsoleti
        for (i=0;i<len;i++) {
            if (eventi[id][i].flag == 'O') {
                eventi[id][i].destroy();
            }
        }
        for (i=len-1;i>=0;i--) {
            if (eventi[id][i].flag == 'O') {
                eventi[id].splice(i, 1);
            }
        }
    } else {
        len = eventi[id].length;
        for (i=0;i<len;i++) {
            if (eventi[id][i]) eventi[id][i].destroy();
        }
        eventi[id].splice(0, len);
    }
    //debug2();
}

/*
 * procedura di aggiornamento periodico
 */

function refreshAll()
{
    var where = "";
    var webcat = "";
    var sep = "";
    var elem = "";
    var nome = "";
    var temporeale = false;
    // cerco gli eventi checkati
    for (id in eventi) {
        elem = elemento(id);
        if (elem.style.visibility == "visible") {
            if (id == 'Cat_C') temporeale = true;
            else {
                webcat += sep+"'"+id+"'";
                sep = ",";
            }
        }
    }
    if (webcat || temporeale) {
        // richiedo gli eventi al server
        if (temporeale) {
            where = "(F_WEBCATEGORY in ('Cat_C'))";
        }
        if (webcat) {
            if (where) where += ' OR ';
            where += '((F_WEBCATEGORY in ('+webcat+')) and (F_XCOORD_DA between '+sw.lng()+' and '+ne.lng()+') and (F_YCOORD_DA between '+sw.lat()+' and '+ne.lat()+'))';
        }
        dati=estrai(where, 'G_CHAR_STRADA(F_ROADNUMBER), G_NUM_STRADA(F_ROADNUMBER), F_LOCNAME_DA');
        if (typeof(dati) == 'string') return;
        // svuoto gli eventi vecchi
        for (id in eventi) {
            len = eventi[id].length;
            for (i=0;i<len;i++) {
                if (eventi[id][i]) eventi[id][i].destroy();
            }
            eventi[id].splice(0, len);
        }
        // inserisco gli eventi nuovi
        aggiungi_punti(dati);
    } else {
        for (id in eventi) {
            len = eventi[id].length;
            for (i=0;i<len;i++) {
                if (eventi[id][i]) eventi[id][i].destroy();
            }
            eventi[id].splice(0, len);
        }
    }
    var tabEventi = elemento("tabEventi");
    if (tabEventi.rows.length == 0) {
        var nulla = new Array();
        nulla[0] = new Array();
        nulla[0]['F_ID'] = 1;
        nulla[0]['F_ICON'] = 'null';
        nulla[0]['F_YCOORD_DA'] = sw.lat()+'';
        nulla[0]['F_XCOORD_DA'] = sw.lng()+'';
        nulla[0]['F_TRADUZIONE_BREVE'] = null;
        nulla[0]['F_ROADNUMBER'] = null;
        nulla[0]['F_ROADNAME'] = 'NESSUNA SEGNALAZIONE PERVENUTA';
        nulla[0]['F_WEBCATEGORY'] = 'Cat_Vv';
        nulla[0]['DOVE'] = '';
        nulla[0]['DIR'] = null;
        aggiungi_punti(nulla);
    }
}

function fairefresh()
{
    refreshAll();
    dataora();
    setTimeout("fairefresh()",120000);
}

function area_visibile()
{
    // debug
    var bounds = fieramap.getBounds();
    ne = bounds.getNorthEast();
    sw = bounds.getSouthWest();
    // debug1();
    refreshAll();
}

function handleErrors()
{
    if (directionsDisplay.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
        alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directionsDisplay.getStatus().code);
    else if (directionsDisplay.getStatus().code == G_GEO_SERVER_ERROR)
        alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directionsDisplay.getStatus().code);

    else if (directionsDisplay.getStatus().code == G_GEO_MISSING_QUERY)
        alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directionsDisplay.getStatus().code);

    //   else if (directionsDisplay.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + directionsDisplay.getStatus().code);

    else if (directionsDisplay.getStatus().code == G_GEO_BAD_KEY)
        alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directionsDisplay.getStatus().code);

    else if (directionsDisplay.getStatus().code == G_GEO_BAD_REQUEST)
        alert("A directions request could not be successfully parsed.\n Error code: " + directionsDisplay.getStatus().code);

    else alert("An unknown error occurred.");
}
// varie ed eventuali

function apriFumetto(sit)
{
    // cerco la situazione
    for (categoria in eventi) {
        for (evento in eventi[categoria]) {
            if (eventi[categoria][evento].situazione == sit) {
                eventi[categoria][evento].showFumetto();
                return;
            }
        }
    }
}

function debug1()
{
    loca = elemento("divLocalita");
    loca.innerHTML = 'nord-est lat='+ne.lat()+'<br>';
    loca.innerHTML+= 'nord-est lng='+ne.lng()+'<br>';
    loca.innerHTML+= 'sud-ovest lat='+sw.lat()+'<br>';
    loca.innerHTML+= 'sud-ovest lng='+sw.lng()+'<br>';
}

function debug2()
{
    path = elemento("divPercorsi");
    path.innerHTML = 'Cat_C='+eventi['Cat_C'].length+'<br>';
    path.innerHTML+= 'Cat_L='+eventi['Cat_L'].length+'<br>';
    path.innerHTML+= 'Cat_B='+eventi['Cat_B'].length+'<br>';
    path.innerHTML+= 'Cat_Va='+eventi['Cat_Va'].length+'<br>';
    path.innerHTML+= 'Cat_Vv='+eventi['Cat_Vv'].length+'<br>';
}

