﻿
// Constantes
var DOMAIN_SWISSPORTAIL = "http://www.swissportail.ch"; // Pour iframe StreetView
var URL_KML = "http://kml.swissportail.ch/KmlSubscriptions.aspx"; // Pour les serveurs de google

// Variables
var map = null;
var geocoder = null;
var infoWindow = null;
var kmlLayer = null;
var localityTimeout = null;
var initKmlLayerTimeout = null;
var zoomKml = null;
var latLngBoundsKml = null;
var enableSubIdToOpen = true;


function initGMapLatLng(lat, lng, zoom) {
    latLng = new google.maps.LatLng(lat, lng);
    initGMap(latLng, zoom);
}

function initGMapLatLngBounds(neLat, neLng, swLat, swLng) {

    swLatLng = new google.maps.LatLng(swLat, swLng);
    neLatLng = new google.maps.LatLng(neLat, neLng);
    latLngBounds = new google.maps.LatLngBounds(swLatLng, neLatLng);

    initGMap(latLngBounds, null);
}

/**
* Méthode pour initialiser la map
*/
function initGMap(position, zoom) {

    // Options Map
    optionsMap = null;
    isBounds = typeof (position.getCenter) != "undefined";


    // Si LatLngBounds
    if (isBounds) {
        optionsMap = {
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
    }

    // Si LatLng
    else {
        optionsMap = {
            zoom: zoom,
            center: position,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
    }

    // Initialisation de :  Map + Geocoder + InfoWindow
    map = new google.maps.Map(document.getElementById("map_canvas"), optionsMap);
    if (isBounds) map.fitBounds(position);
    geocoder = new google.maps.Geocoder();
    infoWindow = new google.maps.InfoWindow({ maxWidth: 370 });

    // Listener pour écouter "bounds_changed"
    google.maps.event.addListener(map, "bounds_changed", function () {
        clearTimeout(initKmlLayerTimeout);
        initKmlLayerTimeout = setTimeout("initKmlLayer();", 50);

        clearTimeout(localityTimeout);
        localityTimeout = setTimeout("showLocalityFromCenterMap();", 400);
    });

    // Listener click
    google.maps.event.addListener(map, "click", function() {
        infoWindow.close();
    });

    // Listener pour écouter "zoom_changed"
    google.maps.event.addListener(map, "zoom_changed", function() {
        infoWindow.close();
    });
}

/**
* Init du KmlLayer
*/
function initKmlLayer() {

    v = 110;
    newZoomKml = map.getZoom();
    newLatLngBoundsKml = map.getBounds();

    if (latLngBoundsKml == null || zoomKml != newZoomKml || !(latLngBoundsKml.contains(newLatLngBoundsKml.getNorthEast()) && latLngBoundsKml.contains(newLatLngBoundsKml.getSouthWest()))) {

        // Supprime l'ancien KmlLayer
        if (kmlLayer != null) kmlLayer.setMap(null);

        // Positions de la vue
        neLatLng = newLatLngBoundsKml.getNorthEast();
        swLatLng = newLatLngBoundsKml.getSouthWest();

        // Largeur et hauteur de la vue
        deltaLat = (neLatLng.lat() - swLatLng.lat()) * 0.5;// * 2; 2 me semble trop grand
        deltaLng = (neLatLng.lng() - swLatLng.lng()) * 0.5;// * 2;

        // Agrandissement
        neLat = neLatLng.lat() + deltaLat;
        neLng = neLatLng.lng() + deltaLng;
        swLat = swLatLng.lat() - deltaLat;
        swLng = swLatLng.lng() - deltaLng;

        // Controle
        min = -179.999999;
        max = 179.999999;
        if (neLat > max) neLat = max;
        if (neLat < min) neLat = min;
        if (neLng > max) neLng = max;
        if (neLng < min) neLng = min;
        if (swLat > max) swLat = max;
        if (swLat < min) swLat = min;
        if (swLng > max) swLng = max;
        if (swLng < min) swLng = min;

        swLatCH = 45.733;
        swLngCH = 5.746;
        neLatCH = 47.865;
        neLngCH = 10.585;

        if (neLat > swLat && neLng > swLng && ((swLat > neLatCH) || (neLat < swLatCH) || (swLng > neLngCH) || (neLng < swLngCH)))
            return; // La zone est totalement en dehors de la Suisse

        if (neLat > neLatCH) neLat = neLatCH;
        if (neLng > neLngCH) neLng = neLngCH;
        if (swLat < swLatCH) swLat = swLatCH;
        if (swLng < swLngCH) swLng = swLngCH;

        // Agrandissement de la vue
        newNeLatLng = new google.maps.LatLng(neLat, neLng);
        newSwLatLng = new google.maps.LatLng(swLat, swLng);
        newLatLngBoundsKml = new google.maps.LatLngBounds(newSwLatLng, newNeLatLng); //sw, ne

        // Récup. des coordonnées
        neLat = newLatLngBoundsKml.getNorthEast().lat().toFixed(3);
        neLng = newLatLngBoundsKml.getNorthEast().lng().toFixed(3);
        swLat = newLatLngBoundsKml.getSouthWest().lat().toFixed(3);
        swLng = newLatLngBoundsKml.getSouthWest().lng().toFixed(3);

        // Url du KmlLayer
        param = "neLat=" + neLat + "&neLng=" + neLng + "&swLat=" + swLat + "&swLng=" + swLng + "&z=" + newZoomKml + "&subIdToOpen=" + subIdToOpen + "&c=" + categoryId + "&k=" + encodeURIComponent(keyword) + "&v=" + v;
        urlKml = URL_KML + "?" + param;

        // Ajout du KmlLayer
        kmlLayer = new google.maps.KmlLayer(urlKml, { suppressInfoWindows: true, preserveViewport: true, map: map });
        google.maps.event.addListener(kmlLayer, "click", function(kmlMouseEvent) {
            showInfoWindow(kmlMouseEvent.featureData.id, kmlMouseEvent.position);
        });
        if (enableSubIdToOpen && subIdToOpen != -1) {
            enableSubIdToOpen = false;
            showInfoWindow(subIdToOpen); // loadKml(urlKml);
        }

        zoomKml = newZoomKml;
        latLngBoundsKml = newLatLngBoundsKml;
    }
}

/*
function loadKml(params) {

    $j.ajax({
        type: "GET",
        url: "/KmlSubscriptions.aspx?" + params,
        dataType: "xml",
        success: function(xml) {

            // Pour chaque markers
            $j(xml).find("Placemark").each(function() {

                // Id placemark
                var id = $j(this).attr('id');
                if (id == subIdToOpen) {

                    enableSubIdToOpen = false;
                    var coordinates = $j(this).find('coordinates').text();
                    var latlng = coordinates.split(",");
                    showInfoWindow(id, new google.maps.LatLng(latlng[1], latlng[0]));
                }
            });
        }
    });
}*/

/**
* Méthode pour afficher l'info window
*
* Le paramètre "latlng" peut être à null
*/
function showInfoWindow(subId, latlng) {

    //urlSrc = "/MapDetail.aspx?" + SUBSCRIBTION_ID_PARAM + "=" + subId + "&" + LAT_PARAM + "=" + latlng.lat() + "&" + LNG_PARAM + "=" + latlng.lng();
    //iframeWindow = "<iframe frameborder='0' style='margin:0px; padding:0px; margin-right:10px; width:380px; height:150px;' src='" + urlSrc + "'></iframe>";


    // Variables pour "contentWindow"
    Ch.Swissportail.Services.SwissportailService.GetSubscriptionById(parseInt(subId), function (sub) {

        raisonSociale = sub.Tradename;
        urlSnapshot = sub.URLSnapshot;
        address = sub.Address;
        zip = sub.ZIP;
        city = sub.City;
        adMessage = sub.AdMessage;
        latitude = sub.Latitude;
        longitude = sub.Longitude;
        if (latlng == null) latlng = new google.maps.LatLng(latitude, longitude);

        // Construction de "contentWindow"
        contentWindow = "";
        contentWindow += "<div style='margin:1px;'>";
        contentWindow +=    "<div style='float:left; padding-right:5px;'>";
        contentWindow +=        "<div ><img alt='' src='http://www.websnaper.ch/ShowSnap.aspx?url=" + urlSnapshot + "'  width='110' height='77' style='border: solid 1px #C9C9C9; display:" + (urlSnapshot != "" ? "block" : "none") + ";' /></div>";
        contentWindow +=    "</div>";
        contentWindow +=    "<div style='padding-left:5px; float:left; width:200px;'>";
        contentWindow +=        "<div><b><a href='#' onclick='onDetailClick(" + subId + "); return false;'>" + raisonSociale + "</a></b></div>";
        contentWindow +=        "<div>" + address + "</div>";
        contentWindow +=        "<div>" + zip + " " + city + "</div>";
        contentWindow +=        "<div><br/><a href='#' onclick='onDetailClick(" + subId + "); return false;'>" + adMessage + "</a></div>";
        contentWindow +=    "</div>";
        contentWindow +=    "<div style='clear:both;'></div>";
        contentWindow += "</div>";

        // Affiche l'infoWindow
        infoWindow.setContent(contentWindow);
        //infoWindow.setContent(iframeWindow);
        infoWindow.setPosition(latlng);
        infoWindow.open(map);
    });
}

/**
* Lorsque l'utilisateur clic sur le détail d'une entreprise
*/
function onDetailClick(subId) {

    //latlng = map.getCenter();
    //address = $j("#locality").text();
    //filtre = "&" + KEYWORDS_PARAM + "=" + encodeURIComponent(keyword);
    //document.location = "/Detail.aspx?" + SUBSCRIBTION_ID_PARAM + "=" + subId + "&" + LAT_PARAM + "=" + latlng.lat() + "&" + LNG_PARAM + "=" + latlng.lng() + "&" + ZOOM_PARAM + "=" + map.getZoom() + filtre;


    // Récupère données
    latLngBounds = map.getBounds();
    neLatLng = latLngBounds.getNorthEast();
    swLatLng = latLngBounds.getSouthWest();

    // Coordonnées
    neLat = neLatLng.lat();
    neLng = neLatLng.lng();
    swLat = swLatLng.lat();
    swLng = swLatLng.lng();

    // Paramètres
    subParams = SUBSCRIBTION_ID_PARAM + "=" + subId;
    zoomParams = ZOOM_PARAM + "=" + map.getZoom();
    boundsParams = NE_LAT_PARAM + "=" + neLat + "&" + NE_LNG_PARAM + "=" + neLng + "&" + SW_LAT_PARAM + "=" + swLat + "&" + SW_LNG_PARAM + "=" + swLng;
    filtreParams = KEYWORDS_PARAM + "=" + encodeURIComponent(keyword);

    // Redirection
    document.location = "/Detail.aspx?" + subParams + "&" + zoomParams + "&" + boundsParams + "&" + filtreParams;
}

/**
* Méthode pour afficher la localité du centre de la carte
*/
function showLocalityFromCenterMap() {

    // Récupère coordonnée
    latLng = map.getCenter();
    address = latLng.lat() + ", " + latLng.lng();

    // Applique la coordonnée à la barre de recherche
    if (typeof (setLatRequest) == "function") setLatRequest(latlng.lat());
    if (typeof (setLngRequest) == "function") setLngRequest(latlng.lng());

    // Recherche de l'adresse en fonction de la coordonnée
    geocoder.geocode({ 'latLng': latLng }, function(results, status) {

        localityBox = $j(".carte .liste-ville");

        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {

                address = results[0].formatted_address;
                split = address.split(", ");
                if (split.length >= 3) {
                    address = split[split.length - 2] + ", " + split[split.length - 1];
                }
            }
        }

        // Affiche l'adresse
        localityBox.text(address);
        
        
        //
        // Change l'url de la "liste"
        //
        
        // Récupère données
        latLngBounds = map.getBounds();
        neLatLng = latLngBounds.getNorthEast();
        swLatLng = latLngBounds.getSouthWest();
        
        // Coordonnées
        neLat = neLatLng.lat();
        neLng = neLatLng.lng();
        swLat = swLatLng.lat();
        swLng = swLatLng.lng();
        
        // Paramètres
        boundsParams = NE_LAT_PARAM + "=" + neLat + "&" + NE_LNG_PARAM + "=" + neLng + "&" + SW_LAT_PARAM + "=" + swLat + "&" + SW_LNG_PARAM + "=" + swLng;
        filtreParams = KEYWORDS_PARAM + "=" + encodeURIComponent(keyword);
        
        // Nouvelle URL
        url = "/List.aspx?" + boundsParams + "&" + filtreParams;
        $j(".listTabLink").attr("href", url);
    });
}

/**
* Lorsque l'utilisateur veut afficher le "streeview" d'une inscription
*/
function onStreetViewClick(subId) {
    oWnd = $find("<%=GStreetViewRadWindow.ClientID %>");
    oWnd.setUrl(DOMAIN_SWISSPORTAIL + "/GMap/GStreetView.aspx?" + SUBSCRIBTION_ID_PARAM + "=" + subId);
    oWnd.show();
}
