﻿var results = null;
var map;
var from = null;
var to = null;
var line = null;
var baseIcon = new GIcon();
var bounds = new GLatLngBounds();
var circleF = null;
var circleT = null;
var journeys = [];
var lines = [];
var qsParm = [];
var maxLat = 45;
var minLat = 43;
var maxLng = 10;
var minLng = 8;
baseIcon.iconSize = new GSize(35, 35);
baseIcon.shadow = "./images/start_s.png";
baseIcon.iconAnchor = new GPoint(10, 30);
baseIcon.infoWindowAnchor = new GPoint(15, 10);
baseIcon.shadowSize = new GSize(52, 35);
var startIcon = new GIcon(baseIcon, "./images/start.png", null, "");
baseIcon.shadow = "./images/stop_s.png";
baseIcon.iconAnchor = new GPoint(25, 30);
var stopIcon = new GIcon(baseIcon, "./images/stop.png", null, "");
function mload() {
    var imap = document.getElementById("map");
    if (imap != null) {
        if (GBrowserIsCompatible()) {
            map = new GMap2(imap);
            var center = new GLatLng(44.457062, 8.923990);
			var zoom = 11;
            var queryString = window.top.location.search.substring(1);
            if (queryString.indexOf('pegli') > -1) {
                center = new GLatLng(44.427256, 8.808584);
				zoom = 13;
            }
            map.setCenter(center, zoom);
            map.addControl(new GSmallMapControl());
        }
    }
}

function showVal(selection) {
    var val = document.getElementById("validity");
    var s = document.getElementById(tbVSDATE);
    var e = document.getElementById(tbVEDATE);
    if ((selection.selectedIndex == 0) ||
        (selection.selectedIndex == 1)) {
        val.style.display = "none";
        var d = new Date();
        var gg = d.getDate();
        if (gg < 10)
            gg = "0" + gg;
        var mm = d.getMonth() + 1;
        if (mm < 10)
            mm = "0" + mm;
        s.value = gg + "/" + mm + "/" + d.getFullYear();
        e.value = s.value;
    }
    else {
        var d = document.getElementById(tbDATE);
        val.style.display = "block";
        s.value = d.value;
        var tg = new Date();
        tg.setDate(tg.getDate() + 30);
        var gg = tg.getDate();
        if (gg < 10)
            gg = "0" + gg;
        var mm = tg.getMonth() + 1;
        if (mm < 10)
            mm = "0" + mm;
        e.value = gg + "/" + mm + "/" + tg.getFullYear();
    }
}

function createMarker(point, name, html, deficon, tofrom) {
    var marker = new GMarker(point, { icon: deficon, draggable: false, bouncy: true });
    map.addOverlay(marker);
    map.setCenter(point, 13);
    var radius = document.getElementById("ctl00_ContentPlaceHolder1_radius");
    if (radius != null) {
        var givenRad = (radius.value * 1) / 1000;
        var givenQuality = 100;
        if (tofrom == 1) {
            circleT = drawCircle(point, givenRad, givenQuality, "#ff0000"); 
            map.addOverlay(circleT);
        }
        else {
            circleF = drawCircle(point, givenRad, givenQuality, "#00ff00"); 
            map.addOverlay(circleF);
        }
    }
    return marker;
}

function createLine(frpoint, topoint, drpr) {
    var color = "#FF00FF";
    if (drpr)
        color = "#FF8040";
    var line = new GPolyline([
  		  frpoint,
  		  topoint],
  		  color, 5);
    return line;
}

function drawCircle(center, radius, nodes, liColor, liWidth, liOpa, fillColor, fillOpa) {
    // Esa 2006
    //calculating km/degree
    var latConv = center.distanceFrom(new GLatLng(center.lat() + 0.1, center.lng())) / 100;
    var lngConv = center.distanceFrom(new GLatLng(center.lat(), center.lng() + 0.1)) / 100;

    //Loop 
    var points = [];
    var step = parseInt(360 / nodes) || 10;
    for (var i = 0; i <= 360; i += step) {
        var pint = new GLatLng(center.lat() + (radius / latConv * Math.cos(i * Math.PI / 180)), center.lng() +
	(radius / lngConv * Math.sin(i * Math.PI / 180)));
        points.push(pint);
        //bounds.extend(pint); //this is for fit function
    }
    points.push(points[0]); // Closes the circle, thanks Martin
    fillColor = fillColor || liColor || "#0055ff";
    liWidth = liWidth || 2;
    var poly = new GPolygon(points, liColor, liWidth, liOpa, fillColor, fillOpa);
    return poly;
}

function dropOverlay(marker) {
    map.removeOverlay(marker);
    marker = null;
}

function drawLine() {
    bounds = new GLatLngBounds();
    bounds.extend(from.getLatLng());
    bounds.extend(to.getLatLng());
    line = new GPolyline([
  		  from.getLatLng(),
  		  to.getLatLng()],
  		  "#0000ff", 5);
    map.addOverlay(line);
    fit();
}

function fit() {
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());
}

function changeRadius() {
    var givenRad = (document.getElementById("ctl00_ContentPlaceHolder1_radius").value * 1) / 1000;
    var givenQuality = 100;
    if (circleT != null) {
        dropOverlay(circleT);
        circleT = drawCircle(to.getLatLng(), givenRad, givenQuality, "#ff0000");
        map.addOverlay(circleT);
    }
    if (circleF != null) {
        dropOverlay(circleF);
        circleF = drawCircle(from.getLatLng(), givenRad, givenQuality, "#00ff00");
        map.addOverlay(circleF);
    }    
}


function go(i,tbAdd,tf) {
    var place = results.Placemark[i];
    var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    var lat, lng;
    if (tf == "f") {
        lat = document.getElementById(fLat);
        lng = document.getElementById(fLng);
        from = createMarker(point, null, null, startIcon, 0);
    }
    else {
        lat = document.getElementById(tLat);
        lng = document.getElementById(tLng);
        to = createMarker(point, null, null, stopIcon, 1);
    }
    if (line != null) {
        dropOverlay(line);
    }
    if ((from != null) && (to != null)) {
        drawLine();
    }
    var t = document.getElementById(tbAdd);
    t.value = place.address;
    lat.value = point.lat();
    lng.value = point.lng();
    var g = document.getElementById(tf + "Geo");
    var gl = document.getElementById(tf + "List");
    gl.innerHTML = "";
    g.style.display = "none";
    var gImg = document.getElementById(tf + "imgLoad");
    gImg.style.display = "block";
}

function checkBounds(place) {
    return (
        (place.coordinates[1] < maxLat) &&
        (place.coordinates[1] > minLat) &&
        (place.coordinates[0] > minLng) &&
        (place.coordinates[0] < maxLng));
}

function geocode(tbAdd) {
    var address = tbAdd.value;
    if (address.search(/GENOVA/) == -1)
        address += ", Genova";
    result = null;
    var geocoder = new GClientGeocoder();
    var tf = "f";
    if (tbAdd.id.match("tbDest") != null) {
        if (to != null) {
            dropOverlay(to);
            if (circleT != null) {
                dropOverlay(circleT);
                circleT = null;
            }
            to = null;
        }
        tf = "t";
    }
    else {
        if (from != null) {
            dropOverlay(from);
            if (circleF != null) {
                dropOverlay(circleF);
                circleF = null;
            }
            from = null;
        }
    }
    if (geocoder) {
        var g = document.getElementById(tf + "Geo");
        var gl = document.getElementById(tf + "List");
        var gImg = document.getElementById(tf + "imgLoad");
        gImg.style.display = "block";
        g.style.height = "18px";
        g.style.display = "block";
        geocoder.getLocations(address, function(result) {
            // show status code
            // document.getElementById("message").innerHTML = status[result.Status.code]+"<br>";
            results = result;
            var html = "<ul>";
            var res = 0;
            var end = false;
            if (result.Status.code == G_GEO_SUCCESS) {
                for (var i = 0; i < result.Placemark.length; i++) {
                    if (checkBounds(result.Placemark[i].Point)) {
                        if (result.Placemark[i].AddressDetails.Accuracy > 4)
                            end = true;
                        html += "<li><a href='#' onclick='go(" + i + ",\"" + tbAdd.id + "\",\"" + tf + "\")'>" + result.Placemark[i].address + " " + result.Placemark[i].AddressDetails.Accuracy + "</a></li>";
                        res++;
                    }
                }
            }
            if (!end)
            {
                var j = 0;
                var type = "Via ";
                for (j=0;j<4;j++) {
                    if (j == 1)
                        type = "Vico ";
                    if (j == 2)
                        type = "Salita ";
                    if (j == 3)
                        type = "Piazza ";
                    var addressG = type + address;
                    geocoder.getLocations(addressG, function(result) {
                        if (result.Status.code == G_GEO_SUCCESS) {
                            for (var i = 0; i < result.Placemark.length; i++) {
                                if (checkBounds(result.Placemark[i].Point)) {
                                    html += "<li><a href='#' onclick='go(" + i + ",\"" + tbAdd.id + "\",\"" + tf + "\")'>" + result.Placemark[i].address + " " + result.Placemark[i].AddressDetails.Accuracy + "</a></li>";
                                    res++;
                                }
                            }
                        }     
                    });
                }
            }
            if (res == 0) {
                html += "<li>Nessun luogo trovato</li>";
                res = 1;
            }
            html += "</ul>";
            gImg.style.display = "none";
            var dim = res * 12;
            g.style.height = dim + "px";
            gl.innerHTML = html;
        });
    }
}

function searchBtn() {
    showLoad();
}

function clearLines() {
    for(var i=0; i<lines.length; i++) {
        dropOverlay(lines[i]);
    } 
    lines = []
    journeys = []
}

function showLoad() {
    map.getInfoWindow().hide();
    clearLines();
    var loadDiv = $get('mload');
    var mapDiv = $get('map');
    var mapDivBounds = Sys.UI.DomElement.getBounds(mapDiv);
    loadDiv.style.height = mapDivBounds.height + "px";
    loadDiv.style.top = (mapDivBounds.y) + "px";
    loadDiv.style.left = (mapDivBounds.x) + "px";
    loadDiv.style.width = (mapDivBounds.width - 1) + "px";
    loadDiv.style.display = "block";
    
    getJourneys();
}

function qs() {
    var query = window.location.search.substring(1);
    var parms = query.split('&');
    for (var i = 0; i < parms.length; i++) {
        var pos = parms[i].indexOf('=');
        if (pos > 0) {
            var key = parms[i].substring(0, pos);
            var val = parms[i].substring(pos + 1);
            qsParm[key] = val;
        }
    }
}

function homeStart() {
    map.getInfoWindow().hide();
    clearLines();
    var loadDiv = $get('mload');
    var mapDiv = $get('map');
    var mapDivBounds = Sys.UI.DomElement.getBounds(mapDiv);
    loadDiv.style.height = mapDivBounds.height + "px";
    loadDiv.style.top = (mapDivBounds.y) + "px";
    loadDiv.style.left = (mapDivBounds.x) + "px";
    loadDiv.style.width = (mapDivBounds.width - 1) + "px";
    loadDiv.style.display = "block";

    getAllJourneys();
}

function getAllJourneys() {
    JourneyService.GetAllJourneys(
        onSucceeded,
        onFailed);
}

function getJourneys() {
    qs();
    var period = document.getElementById("ctl00_ContentPlaceHolder1_lbPeriod");
    var radius = document.getElementById("ctl00_ContentPlaceHolder1_radius");
    var date = document.getElementById("ctl00_ContentPlaceHolder1_tbDate");
    var type = (qsParm["t"] == "a");
    if (period.value != 0) {
        JourneyService.GetJourney(
        document.getElementById(fLat).value,
        document.getElementById(fLng).value,
        document.getElementById(tLat).value,
        document.getElementById(tLng).value,
        radius.value,
        period.value,
        date.value,
        type,
        onSucceeded,
        onFailed);
    }
    else {
        JourneyService.GetJourney(
        document.getElementById(fLat).value,
        document.getElementById(fLng).value,
        document.getElementById(tLat).value,
        document.getElementById(tLng).value,
        radius.value,
        null,
        date.value,
        type,
        onSucceeded,
        onFailed);
    }
}

function onSucceeded(markers) {
    journeys = markers;
    for (var i = 0; i < markers.length; i++) {
      var frlat = parseFloat(markers[i].FromLat);
      var frlng = parseFloat(markers[i].FromLng);
      var tolat = parseFloat(markers[i].ToLat);
      var tolng = parseFloat(markers[i].ToLng);
      var frpoint = new GLatLng(frlat, frlng);
      var topoint = new GLatLng(tolat, tolng);
      var marker = createLine(frpoint, topoint, markers[i].DrPr);
      map.addOverlay(marker);
      lines.push(marker);
  }
  hideLoad();
}

function onFailed(error) {
}

function hideLoad() {
    var loadDiv = $get('mload');
    loadDiv.style.display = "none";
}

function checkBrowser() {
    var isMSIE = (navigator.userAgent.toLowerCase().indexOf('msie 6') != -1) &&
        ((navigator.userAgent.toLowerCase().indexOf('msie 7') == -1) &&
        (navigator.userAgent.toLowerCase().indexOf('msie 8') == -1));
    if (isMSIE) {
        alert("Attenzione avete una versione di Internet Explorer obsoleta e non supportata.\r\n Per usare correttamente l'applicazione aggiornate il vostro browser!");
    }
}

var immagini = new Array()
function preload() {
    for (cont = 0; cont < preload.arguments.length; cont++) {
        immagini[cont] = new Image()
        immagini[cont].src = preload.arguments[cont]
    }
}
preload("./images/loader.gif", "./images/start.png", "./images/stop.png");
