﻿/// <reference name="MicrosoftAjax.js"/>
/// <reference path="GMAPJSHelper_Release.js" />

/*  == Google Maps ==*/
$(document).ready(function() {
    $("a.btImprimirRota").click(imprimirGoogleMaps);
});

var directionsPanel;
var directions;
var map;
var center;
var useCep;
var geocoder;

function initializeMap(p_map, p_directionsPanel, p_center) {
    map = p_map;
    map.setCenter(new GLatLng(-23.583357, -46.542989), 4);
    directionsPanel = document.getElementById(p_directionsPanel);
    directions = new GDirections(map, directionsPanel);
    center = p_center;
    geocoder = new GClientGeocoder();
}
var cep1;
var cep2;
var endereco
var chk1;
var chk2;
var chk3;
var imageUrl;
var sizeIcon;
function initializeRota(p_w, p_h, p_cep1, p_cep2, p_endereco, p_imageUrl, p_chk1, p_chk2, p_chk3) {
    cep1 = document.getElementById(p_cep1);
    cep2 = document.getElementById(p_cep2);
    endereco = document.getElementById(p_endereco);
    if (p_chk1 != null && p_chk1 != "")
        chk1 = document.getElementById(p_chk1);
    if (p_chk2 != null && p_chk2 != "")
        chk2 = document.getElementById(p_chk2);
    if (p_chk3 != null && p_chk3 != "")
        chk3 = document.getElementById(p_chk3);
    imageUrl = p_imageUrl;
    sizeIcon = new GSize(p_w, p_h);
}

function existeEndereco(address, txtEndereco) {
    if (address != "") {
        geocoder.getLocations(address, function(result) {
            if (!result || result.Status.code != 200)
                txtEndereco.style.backgroundColor = 'yellow';
            else {
                txtEndereco.style.backgroundColor = '';
                txtEndereco.value = result.Placemark[0].address;
            }
        });
    }
    else
        txtEndereco.style.backgroundColor = '';
}

function tracarRota() {
    if (endereco.value != "") {
        cep1.value = "";
        cep2.value = "";
        return route(endereco.value);
    }
    else if (cep1.value != "" && cep2.value != "") {
        return route(cep1.value + "-" + cep2.value);
    }
    else {
        return route("");
    }
}

var temEndereco;
var enderecos = new Array();
function route(address) {
    temEndereco = false;
    //map.clearOverlays();
    GEvent.addListener(directions, 'error',
        function(directions) {
            enderecos.length = 0;
            directionsPanel.innerHTML = "Rota nao encontrada.";
            //$('#boxOrientacoes').css("top", 0);
        }

    );

    GEvent.addListener(directions, 'load',
        function(directions) {
            //Caso carregue com sucesso.
            directionsPanel.innerHTML = "";
            enderecos.length = 0;
            for (var i = 0; i < 4; i++) {
                if (directions.getMarker(i) != null) {
                    enderecos.push(directions.getMarker(i).getLatLng());
                    if (directions.getMarker(i).getIcon() != null) {
                        if (temEndereco && i == 0) {
                            directions.getMarker(i).getIcon().image = "http://maps.google.com/intl/pt-BR_ALL/mapfiles/marker_greenA.png";
                            directions.getMarker(i).getIcon().iconSize = new GSize(20, 34);
                        }
                        else {
                            directions.getMarker(i).getIcon().image = imageUrl;
                            directions.getMarker(i).getIcon().iconSize = sizeIcon;
                        }
                        directions.getMarker(i).getIcon().shadow = "";
                        directions.getMarker(i).getIcon().shadowSize = new GSize(0, 0);
                        //directions.getMarker(i).hide();
                    }
                }
            }
        }
    );

    GEvent.addListener(directions, "addoverlay", function() {
        //$('#boxOrientacoes').jScrollPane({ scrollbarWidth: 12, scrollbarMargin: 10, showArrows: true, dragMaxHeight: 6 });
    });

    var rotaCompleta = "from: "
    if (address != "") {
        address += ", BRA";
        rotaCompleta += address;
        temEndereco = true;
    }

    if (chk1 != null && chk1.checked) {
        if (rotaCompleta == "from: ")
            rotaCompleta += chk1.alt;
        else
            rotaCompleta += " to: " + chk1.alt;
    }
    if (chk2 != null && chk2.checked) {
        if (rotaCompleta == "from: ")
            rotaCompleta += chk2.alt;
        else
            rotaCompleta += " to: " + chk2.alt;
    }
    if (chk3 != null && chk3.checked) {
        if (rotaCompleta == "from: ")
            rotaCompleta += chk3.alt;
        else
            rotaCompleta += " to: " + chk3.alt;
    }

    if (rotaCompleta.indexOf("to:") == -1 && rotaCompleta != "from: ") {
        geocoder.getLatLng(
          rotaCompleta.replace("from: ", ""),
          function(point) {
              if (!point) {
                  directionsPanel.innerHTML = "Lugar nao encontrado.";
              } else {
                  directionsPanel.innerHTML = "";
                  var cyrelaIcon = new GIcon(G_DEFAULT_ICON);
                  cyrelaIcon.iconSize = sizeIcon;
                  cyrelaIcon.image = imageUrl;
                  markerOptions = { icon: cyrelaIcon };


                  map.setCenter(point, 14);
                  var marker = new GMarker(point, markerOptions);
                  var html = "";
                  if (address == rotaCompleta.replace("from: ", ""))
                      html = address;
                  else if (chk1.alt == rotaCompleta.replace("from: ", ""))
                      html = "<h1>" + chk1.parentNode.childNodes[1].nodeValue + "</h1>";
                  else if (chk2.alt == rotaCompleta.replace("from: ", ""))
                      html = "<h1>" + chk2.parentNode.childNodes[1].nodeValue + "</h1>";
                  else
                      html = "<h1>" + chk3.parentNode.childNodes[1].nodeValue + "</h1>";

                  GEvent.addListener(marker, "click", function() {
                      marker.openInfoWindowHtml(html);
                  });
                  map.addOverlay(marker);
              }
          }
        );

    }
    else
        directions.load(rotaCompleta, { getSteps: true });

    return false;
}

function busca(cep1, cep2, p_endereco) {
    useCep = false;
    endereco = p_endereco;
    if (document.getElementById(p_endereco).value != "") {
        document.getElementById(cep1).value = "";
        document.getElementById(cep2).value = "";
        return find(document.getElementById(p_endereco).value);
    }
    else {
        useCep = true;
        return find(document.getElementById(cep1).value + "-" + document.getElementById(cep2).value);
    }
}

function find(address) {
    GEvent.addListener(directions, 'error',
        function(directions) {
            enderecos.length = 0;
            if (useCep)
                directionsPanel.innerHTML = "CEP nao encontrado.";
            else
                directionsPanel.innerHTML = "Endereco nao encontrado.";

            //$('#boxOrientacoes').css("top", 0);
        }
    );


    GEvent.addListener(directions, 'load',
        function(directions) {
            //Caso carregue com sucesso.
            directionsPanel.innerHTML = "";

            enderecos.push(directions.getMarker(0).getLatLng());
            enderecos.push(directions.getMarker(1).getLatLng());

            directions.getMarker(1).getIcon().image = "";
            directions.getMarker(1).getIcon().iconSize = new GSize(0, 0);
            directions.getMarker(1).getIcon().shadow = "";
            directions.getMarker(1).getIcon().shadowSize = new GSize(0, 0);
            directions.getMarker(1).hide();
        }
    );

    GEvent.addListener(directions, "addoverlay", function() {
        //$('#boxOrientacoes').jScrollPane({ scrollbarWidth: 12, scrollbarMargin: 10, showArrows: true, dragMaxHeight: 6, dragMinHeight: 6 });
    });

    address += ", BRA";
    directions.load("from: " + address + " to: " + center.y + "," + center.x, { getSteps: true });

    return false;

}

function imprimirGoogleMaps() {
    
    if (enderecos.length > 0) {
        var bounds;
        var url = "http://maps.google.com/maps?f=d&saddr=" + enderecos[0].y + "," + enderecos[0].x;
        if (enderecos.length >= 1) {
            bounds = new GLatLngBounds();
            bounds.extend(enderecos[0]);
            bounds.extend(enderecos[enderecos.length - 1]);
            url += "&daddr=" + enderecos[1].y + "," + enderecos[1].x;
        }
        if (enderecos.length >= 2)
            for (var i = 2; i < enderecos.length; i++) {
            url += "+to:" + enderecos[i].y + "," + enderecos[i].x;
        }

        url += "&hl=pt-BR&ie=UTF8&pw=2";
        if (bounds != null)
            url += "&z=" + map.getBoundsZoomLevel(bounds);
        else
            url += "&z=14";
        return openPopup(url, 800, 600);
    }
    else
        return false;
}

/*function logRotaImovel(p_idImovel, p_cepInicio, p_cepFim, p_endereco) {
    PageMethods.logRotaImovel(p_idImovel, document.getElementById(p_cepInicio).value + document.getElementById(p_cepFim).value, document.getElementById(p_endereco).value);
    return busca(p_cepInicio, p_cepFim, p_endereco);
}*/

// Abre uma janela popup com url, largura e altura customizadas
function openPopup(strUrl, width, height) {
    window.open(strUrl, '', 'left=0,top=0,width=' + width + ',height=' + height + ',toolbar=0,scrollbars=1,status=0');
    return false;
}

//GMarker.prototype.idEmpresa = 0;
