﻿var fMSearchCityO, fMSearchCityD;
var map = null;
var routeManager = new MRouteMannager(); ;
var _markers = [];
var teste = 0;


Number.prototype.formatKm = function (c, d, t) { var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, i = parseInt(n = (+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0; return " " + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); };
Array.prototype.indexOf = function (item, i) { i || (i = 0); var length = this.length; if (i < 0) i = length + i; for (; i < length; i++) if (this[i] === item) return i; return -1; };

function SetTextOfLayer(i, newText) {
    document.getElementById("ctl00_cphBody_tipodesc").innerHTML = "<b>" + newText + "</b>";
}
function init() {
    var fStateO = new MField('divEstadoO', M_TP_STATE);
    fStateO.field.className = 'texto11';
    fStateO.setDefault("SP");
    fStateO.show();

    var fStateD = new MField('divEstadoD', M_TP_STATE);
    fStateD.field.className = 'texto11';
    fStateD.setDefault("SP");
    fStateD.show();

    fMSearchCityO = new MSearchCity(fStateO);
    fMSearchCityD = new MSearchCity(fStateD);
}
function enviarDados() {
    var tpr = ""; var tpv = "";
    if (document.getElementById("ctl00_cphBody_rbCurta").checked) tpr = "1";
    else tpr = "0";

    var r = document.getElementById("ctl00_cphBody_txtCombustivel").value + "|" + document.getElementById("ctl00_cphBody_txtConsumo").value + "|" + document.getElementById("ctl00_cphBody_txtCapacidade").value;

    if (document.getElementById("ctl00_cphBody_tpVeic1").checked) tpv = "1";
    else if (document.getElementById("ctl00_cphBody_tpVeic2").checked) tpv = "2";
    else if (document.getElementById("ctl00_cphBody_tpVeic3").checked) tpv = "3";
    else if (document.getElementById("ctl00_cphBody_tpVeic4").checked) tpv = "4";

    var tO = document.getElementById("ctl00_cphBody_AutoComplete1_hdnSelectedValue").value;
    var objt = eval('(' + tO + ')');

    var tD = document.getElementById("ctl00_cphBody_AutoComplete2_hdnSelectedValue").value;
    var obj = eval('(' + tD + ')');
    document.getElementById("ctl00_cphBody_hfOrigem").value = objt.city.state + "|" + objt.city.name + "|" + objt.point.x + "|" + objt.point.y;
    document.getElementById("ctl00_cphBody_hfDestino").value = obj.city.state + "|" + obj.city.name + "|" + obj.point.x + "|" + obj.point.y;
    document.getElementById("ctl00_cphBody_hfVeiculo").value = r + "|" + tpr + "|" + tpv;

    document.getElementById("aspnetForm").action = "rota.aspx";
    document.getElementById("aspnetForm").submit();
}
function ShowDados(tp) {
    document.getElementById("tb" + tp).style.display = "block";
    document.getElementById("ctl00_cphBody_lblEnd" + tp).style.display = "none";
}
function ShowMapRota(estO, cidO, estD, cidD, xO, yO, xD, yD, veiculo) {

        //        map.clearOverlays();
        //        routeManager.destroy();
        document.getElementById("ctl00_cphBody_hfOrigem").value = estO + "|" + cidO + "|" + xO + "|" + yO;
        document.getElementById("ctl00_cphBody_hfDestino").value = estD + "|" + cidD + "|" + xD + "|" + yD;
        var veiculo = veiculo.split("|");
        var ro = new MRouteOptions();
        var rd = new MRouteDetails();
        if (veiculo[3] == "0")
            rd.optimizeRoute = false;
        else
            rd.optimizeRoute = true;
        rd.routeType = 0;
        rd.descriptionType = 0;

        var ve = new MVehicle();
        ve.tankCapacity = veiculo[2];
        ve.averageConsumption = veiculo[1];
        ve.fuelPrice = veiculo[0];
        ve.averageSpeed = 80;
        ve.tollFeeCat = veiculo[4];

        var ro = new MRouteOptions();
        ro.language = "portugues";
        ro.vehicle = ve;
        ro.routeDetails = rd;

        var rs = new Array();
        rs[0] = new MRouteStop();
        rs[0].description = cidO;
        var point = new MPoint();
        point.x = xO;
        point.y = yO;
        rs[0].point = point;

        rs[1] = new MRouteStop();
        rs[1].description = cidD;
        var point = new MPoint();
        point.x = xD;
        point.y = yD;
        rs[1].point = point;

        var rp = new Array;
        var routePointAux;
        routePointAux = new MRoutePoint();
        routePointAux.routeStop = rs[0];
        routePointAux.icon = criaIcone("origem");
        rp.push(routePointAux);

        routePointAux = new MRoutePoint();
        routePointAux.routeStop = rs[1];
        routePointAux.icon = criaIcone("destino");
        rp.push(routePointAux);


        map = new MMap2(document.getElementById('divMap'));
        routeManager = new MRouteMannager(map);
        routeManager.createRoute(rp, ro, null);

        routeManager.createRoute(rp, ro, null, function(result) { ri(result, estO, cidO, estD, cidD, xO, yO, xD, yD, veiculo[0], veiculo[1], veiculo[2], veiculo[4]); });
}
function ri(result, estO, cidO, estD, cidD, xO, yO, xD, yD, preco, cons, tanque, veic) {
    var rtt = result.routeTotals;
    var rt = result.roadType;
    var sg = result.segDescription;

    document.getElementById('ctl00_cphBody_resRota').innerHTML = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>" +
    "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px'' align='left'>Distância Percorrida</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'>" + rtt.totalDistance.formatKm() + " Km </td></tr>" +
    "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px' align='left'>Tempo de viagem (80 km/h)</td><td width='60%' style='border-bottom:solid #D5CAB4 1px' align='right'>" + rtt.totalTime.toString().replace(/PT/, '').replace(/P/, '').replace(/DT/, (' dia(s) ')).replace(/H/, (' hora(s) ')).replace(/M/, (' minuto(s)')) + "</td>" +
    "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px' align='left'>Gasto de Pedágio</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'> R$ " + rtt.totaltollFeeCost.formatKm() + "</td></tr>" +
    "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px' align='left'>Combustível necessário</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'>" + rtt.totalFuelUsed.toString().replace('.', ',') + " litro(s)</td></tr>" +
    "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px' align='left'>Gasto de combustível</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'> R$ " + rtt.totalfuelCost.formatKm() + "</td>" +
    "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px' align='left'>Gasto total</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'> R$ " + rtt.totalCost.formatKm() + "</td></table>";
    var IVeic = "";
    IVeic = "<table><tr><td width='45%' colspan='4' valign='top'>" +
                                    "<img ID='imgVeic' src='img/ic_veiculos" + veic + ".gif' />" +
                                "</td>" +
                                "<td rowspan='3' width='3'>" +
                                    "<img src='img/spacer_1.gif' width='3' height='5'></td>" +
                                "<td width='55%' valign='top' rowspan='3'>" +
                                    "<table width='100%' border='1' cellspacing='0' cellpadding='0' bordercolor='#D5CAB4' 'bgcolor='#999999' height='100%'>" +
                                        "<tr>" +
                                            "<td height='20' bgcolor='#FFFCF0'>" +
                                                "<b>&nbsp;Dados:</b></td>" +
                                        "</tr>" +
                                        "<tr>" +
                                            "<td bgcolor='#FFFFFF'>" +
                                                "&nbsp;Combust&iacute;vel: " + preco + " / Litro/M³" +
                                            "</td>" +
                                        "</tr>" +
                                        "<tr>" +
                                            "<td bgcolor='#FFFFFF'>" +
                                                "&nbsp;Consumo M&eacute;dio: " + cons + " Km / Litro/M³" +
                                            "</td>" +
                                        "</tr>" +
                                        "<tr>" +
                                            "<td bgcolor='#ffffff'>" +
                                                "&nbsp;Capacidade do tanque: " + tanque + " Litro/M³" +
                                            "</td>" +
                                        "</tr>" +
                                    "</table>" +
                                "</td></tr>";
    if (veic == "1")
        IVeic += "<tr><td><b>.:Motocicletas, motonetas e bicicletas a motor</b></td></tr></table>";
    else if (veic == "2")
        IVeic += "<tr><td><b>.:Automóvel, caminhoneta e furgão (dois eixos simples)</b></td></tr></table>";
    else if (veic == "3")
        IVeic += "<tr><td><b>.:Automóvel, caminhoneta com semi-reboque (três eixos simples)</b></td></tr></table>";
    else if (veic == "4")
        IVeic += "<tr><td><b>.:Automóvel, caminhoneta com reboque (quatro eixos simples)</b></td></tr></table>";

    document.getElementById("ctl00_cphBody_InfVeic").innerHTML = IVeic;

    var trecho = "<table border='0' cellpadding='0' cellspacing='0' width='100%'>";
    if (rt.twoLaneHighway != "0")
        trecho += "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px'' align='left'><img src=\"img/pista/pd_pd.gif\" />Pista Dupla</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'>" + rt.twoLaneHighway.formatKm() + ' Km' + "</td>";
    if (rt.secondLaneUnderConstruction != "0")
        trecho += "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px'' align='left'><img src=\"img/pista/ed_ed.gif\" />Em obras de Duplicação</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'>" + rt.secondLaneUnderConstruction.formatKm() + ' Km' + "</td>";
    if (rt.oneLaneRoadway != "0")
        trecho += "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px'' align='left'><img src=\"img/pista/p_p.gif\" />Pista Simples</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'>" + rt.oneLaneRoadway.formatKm() + ' Km' + "</td>";
    if (rt.roadwayInPoorConditions != "0")
        trecho += "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px'' align='left'><img src=\"img/pista/cp_cp.gif\" />Rodovia em mau estado</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'>" + rt.roadwayInPoorConditions.formatKm() + ' Km' + "</td>";
    if (rt.pavingWorkInProgress != "0")
        trecho += "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px'' align='left'><img src=\"img/pista/ep_ep.gif\" />Em obras de Pavimentação</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'>" + rt.pavingWorkInProgress.formatKm() + ' Km' + "</td>";
    if (rt.dirtRoad != "0")
        trecho += "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px'' align='left'><img src=\"img/pista/t_t.gif\" />Estrada de chão</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'>" + rt.dirtRoad.formatKm() + ' Km' + "</td>";
    if (rt.ferry != "0")
        trecho += "<tr><td width='60%' style='border-bottom:solid #D5CAB4 1px'' align='left'><img src=\"img/pista/ba_ba.gif\" />Balsa</td><td width='40%' style='border-bottom:solid #D5CAB4 1px' align='right'>" + rt.ferry.formatKm() + ' Km' + "</td>";
    document.getElementById('ctl00_cphBody_resTrecho').innerHTML = trecho;

    BuscaAgencia(estO, cidO, estD, cidD, xO, yO, xD, yD, sg, rtt);
}
function BuscaAgencia(estO, cidO, estD, cidD, xO, yO, xD, yD, sg, rtt) {
    PageMethods.BuscarDetalhes(estO, cidO, estD, cidD, function (result) { ret(result, sg, cidO, estO, estD, cidD, xO, yO, xD, yD, rtt); });
}
var totalE = 0;
function ret(result, sg, estO, cidO, estD, cidD, xO, yO, xD, yD, rtt) {
    var dadosO = new Array();
    var dadosD = new Array();
    for (var res = 0; res < result.length; res++) {
        if (result[res].tipo == "O_AGENCIA") dadosO.push(result[res].tipo.replace("O_", ""));
        else if (result[res].tipo == "O_24H") dadosO.push(result[res].tipo.replace("O_", ""))
        else if (result[res].tipo == "O_INSTITUCIONAL") dadosO.push(result[res].tipo.replace("O_", ""));
    }
    var html = new Array();
    html.push('<table cellpadding="0" cellspacing="0" style="text-align:left" width="480px" border="0">' +
    '<tr><td style="width: 32px; height: 15px"></td><td style="height: 15px; padding-left: 3px" align="center"><b>Km</b></td>' +
    '<td><b>Rodovia / Local</b></td><td style="height: 15px" height="15px" align="center"><b/></td></tr>');
    html.push('<tr><td style="width: 32px" width="32" background="img/pista/P_P.gif"><img src="img/pista/sorigem.gif" style="float: left"/></td><td style="width: 12%"></td><td><b>' + cidO + " - " + estO + '</b></td><td></td><td align="right"><a href="javascript:center(%27' + xO + '%27,%27' + yO + '%27, 12)"><img src="img/ico_lupa.gif" border="0"/></a></td></tr>');

    for (var ic = 0; ic < dadosO.length; ic++) {
        if (dadosO[ic] == "AGENCIA") {
            html.push('<tr><td style="width: 32px" width="32" background="img/pista/P_P.gif"><td style="width: 12%; border-top:solid #D5CAB4 1px" align="center"><img src="img/icn_santander_1_1.gif" /></td><td style="border-top:solid #D5CAB4 1px"><b><a href="lista.aspx?tipo=ag&e=' + estO + "&c=" + cidO + '">Agências do Banco Santander em ' + cidO + '-' + estO + '</a></b></td><td style="border-top:solid #D5CAB4 1px">&nbsp;</td><td align="right" style="border-top:solid #D5CAB4 1px">&nbsp;</td></tr>');
        } else if (dadosO[ic] == "24H") {
            html.push('<tr><td style="width: 32px" width="32" background="img/pista/P_P.gif"><td style="width: 12%; border-top:solid #D5CAB4 1px" align="center"><img src="img/icn_cx_24.gif" /></td><td style="border-top:solid #D5CAB4 1px"><b><a href="lista.aspx?tipo=cx&e=' + estO + "&c=" + cidO + '">Agências Banco 24H em ' + cidO + '-' + estO + '</a></b></td><td style="border-top:solid #D5CAB4 1px">&nbsp;</td><td align="right" style="border-top:solid #D5CAB4 1px">&nbsp;</td></tr>');
        } else {
            html.push('<tr><td style="width: 32px" width="32" background="img/pista/P_P.gif"><td style="width: 12%; border-top:solid #D5CAB4 1px" align="center"><img src="img/icn_cx_real1.gif" /></td><td style="border-top:solid #D5CAB4 1px"><b><a href="lista.aspx?tipo=it&e=' + estO + "&c=" + cidO + '">Caixas Eletrônicos em ' + cidO + '-' + estO + '</a></b></td><td style="border-top:solid #D5CAB4 1px">&nbsp;</td><td align="right" style="border-top:solid #D5CAB4 1px">&nbsp;</td></tr>');
        }
    }
    var htmlEstrada = new Array();
    htmlEstrada.push('<table cellpadding="0" cellspacing="0" class="tblInfo" style="width: 100%" border=0>');
    var htmlPedagio = new Array();
    htmlPedagio.push('<table cellpadding="0" cellspacing="0" style="width:100%" border="0">');
    var par = false; var parEstrada = false; var parPedagio = false; var rodovia = ''; var pRoadType = 'p'; var cidades = [];
    cidades.push(cidO + "/" + estO);
    cidades.push(cidD + "/" + estD);

    for (var kkk = 1; kkk < (sg.length - 1); kkk++) {
        if (!isRotaRodoviaria(sg[kkk]))
            totalE += sg[kkk].distance;
    }
    var strEstrada = (Math.round(totalE * 100) / 100).toString().replace('.', ',') + ' Km';
    htmlEstrada.push('<tr><td style="width: 70%">Perimetro Urbano</td><td align="right" style="width: 30%"><b>' + strEstrada + '</b></td></tr>');

    var lim = 0;
    if (sg.length > 2)
        for (var kk = 1; kk < (sg.length - 1); kk++) {
            var flag = []; var comeco = true; var print = false; var pard = sg[kk].command.substring(0, 6);
            flag.push(cidades.indexOf(sg[kk].city.name + '/' + sg[kk].city.state) != -1);
            flag.push(sg[kk].tollFee == null);
            flag.push(rodovia == sg[kk].description);
            flag.push(flag.indexOf(true) != -1 || sg[kk].roadType == pRoadType);
            while (flag.length > 0) {
                if (flag.pop())
                    continue;
                print = false;
                switch (flag.length) {
                    case 2: /*rodovia*/
                        if (isRotaRodoviaria(sg[kk])) {
                            html.push('<tr>');
                            html.push('<td valign="bottom" width="32px" style="vertical-align: bottom; background:url(img/pista/' + pRoadType + '_' + sg[kk].roadType + '.gif)">');
                            html.push('</td><td style="border-top:solid #D5CAB4 1px" align="center">');
                            pRoadType = sg[kk].roadType;
                            if (comeco)
                                html.push(sg[kk - 1].cumulativeDistance.formatKm());
                            html.push('&nbsp;</td><td style="border-top:solid #D5CAB4 1px">');
                            html.push('<b><font color="#215D94">' + sg[kk].description + ' - ');
                            print = true;
                        }
                        if (print) {
                            var total = 0;
                            for (var jj = kk; sg[jj].description == sg[kk].description; jj++)
                                total += sg[jj].distance;
                            var str3 = (Math.round(total * 100) / 100).toString().replace('.', ',') + ' Km';
                            html.push('<font color="#007bb0">' + sg[kk].command + '</font>&nbsp;' + str3 + '&nbsp</font></b>');
                            html.push('</td><td style="border-top:solid #D5CAB4 1px">&nbsp;</td><td style="border-top:solid #D5CAB4 1px" align="right"><a href="javascript:center(%27' + sg[kk].point.x + '%27,%27' + sg[kk].point.y + '%27, 12);"><img src="img/ico_lupa.gif" border="0" /></a></td></tr>');
                            html.push('</td></tr>');
                        }
                        if (kk > lim) {
                            var total = 0;
                            for (var jj = kk; jj < sg.length - 1; jj++) {
                                if (sg[jj].description == sg[kk].description) total += sg[jj].distance;
                                else { if (isRotaRodoviaria(sg[jj])) { lim = jj - 1; break; } }
                                if (jj == sg.length - 2) lim = sg.length;
                            }
                            var str32 = (Math.round(total * 100) / 100).toString().replace('.', ',') + ' Km';
                            if (isRotaRodoviaria(sg[kk]))
                                if (htmlEstrada.length < 2)
                                    htmlEstrada.push('<tr><td style="width: 70%">' + sg[kk].description + '</td><td align="right" style="width: 30%"><b>' + str32 + '</b></td></tr>');
                                else
                                    htmlEstrada.push('<tr><td style="width: 70%; border-top:solid #D5CAB4 1px">' + sg[kk].description + '</td><td align="right" style="width: 30%; border-top:solid #D5CAB4 1px"><b>' + str32 + '</b></td></tr>');
                            parEstrada = !parEstrada;
                        }
                        rodovia = sg[kk].description;
                        break;
                    case 1: /*pedagio*/
                        html.push('<tr>');
                        html.push('<td valign="bottom" width="32" style="vertical-align: bottom; width: 32px; background:url(img/pista/' + pRoadType + '_' + sg[kk].roadType + '.gif)">');
                        html.push('</td><td style="border-top:solid #D5CAB4 1px" align="center">');
                        pRoadType = sg[kk].roadType;
                        html.push('&nbsp;<b>$</b></td><td style="border-top:solid #D5CAB4 1px">');
                        html.push('<b>' + sg[kk].tollFeeDetails.name + '</b></td><td style="border-top:solid #D5CAB4 1px" align="right">');
                        htmlPedagio.push('<tr>');
                        htmlPedagio.push('<td style="border-top:solid #D5CAB4 1px">' + sg[kk].tollFeeDetails.name + '</td><td width="20%" align="right" style="border-top:solid #D5CAB4 1px">R$ ' + sg[kk].tollFeeDetails.price.formatKm() + '</td></tr>');
                        html.push('&nbsp;');
                        html.push('&nbsp;</td><td align="right" style="border-top:solid #D5CAB4 1px"><b><a href="javascript:lf_Info(' + adicionaMarker(sg, kk) + ');" style="text-decoration:underline">Info</a></b></td></tr>');
                        html.push('</td></tr>');
                        parPedagio = !parPedagio;
                        break;
                    case 0: /*cidade*/
                        html.push('<tr>');
                        html.push('<td valign="bottom" width="32px" style="vertical-align: bottom; background:url(img/pista/' + pRoadType + '_' + sg[kk].roadType + '.gif)">');
                        html.push('</td><td style="border-top:solid #D5CAB4 1px" align="center">');
                        pRoadType = sg[kk].roadType;
                        if (comeco)
                            html.push(sg[kk - 1].distance.formatKm());
                        html.push('&nbsp;</td><td style="border-top:solid #D5CAB4 1px">');
                        cidades.push(sg[kk].city.name + '/' + sg[kk].city.state);
                        html.push(sg[kk].city.name + ' - ' + sg[kk].city.state);
                        html.push('</td><td style="border-top:solid #D5CAB4 1px">&nbsp;</td><td style="border-top:solid #D5CAB4 1px" align="right"><a href="javascript:center(%27' + sg[kk].point.x + '%27,%27' + sg[kk].point.y + '%27, 12);"><img src="img/ico_lupa.gif" border="0"/></a></td></tr>');
                        html.push('</td></tr>');
                        print = true;
                        break;
                } // fim switch
            } // fim-while
            comeco = false;
            if (!comeco)
                par = !par;
            print = false;
        } // fim-for        
    for (var resD = 0; resD < result.length; resD++) {
        if (result[resD].tipo == "D_AGENCIA") dadosD.push(result[resD].tipo.replace("D_", ""));
        else if (result[resD].tipo == "D_24H") dadosD.push(result[resD].tipo.replace("D_", ""));
        else if (result[resD].tipo == "D_INSTITUCIONAL") dadosD.push(result[resD].tipo.replace("D_", ""));
    }
    for (var icD = 0; icD < dadosD.length; icD++) {
        if (dadosD[icD] == "AGENCIA") {
            html.push('<tr><td style="width: 32px" width="32" background="img/pista/P_P.gif"><td style="width: 12%; border-top:solid #D5CAB4 1px" align="center"><img src="img/icn_santander_1_1.gif" /></td><td style="border-top:solid #D5CAB4 1px"><b><a href="lista.aspx?tipo=ag&e=' + cidD + "&c=" + estD + '">Agências do Banco Santander em ' + cidD + '-' + estD + '</a></b></td><td style="border-top:solid #D5CAB4 1px">&nbsp;</td><td align="right" style="border-top:solid #D5CAB4 1px">&nbsp;</td></tr>');
        } else if (dadosD[icD] == "24H") {
            html.push('<tr><td style="width: 32px" width="32" background="img/pista/P_P.gif"><td style="width: 12%; border-top:solid #D5CAB4 1px" align="center"><img src="img/icn_cx_24.gif" /></td><td style="border-top:solid #D5CAB4 1px"><b><a href="lista.aspx?tipo=cx&e=' + cidD + "&c=" + estD + '">Agências Banco 24H em ' + cidD + '-' + estD + '</a></b></td><td style="border-top:solid #D5CAB4 1px">&nbsp;</td><td align="right" style="border-top:solid #D5CAB4 1px">&nbsp;</td></tr>');
        } else {
            html.push('<tr><td style="width: 32px" width="32" background="img/pista/P_P.gif"><td style="width: 12%; border-top:solid #D5CAB4 1px" align="center"><img src="img/icn_cx_real1.gif" /></td><td style="border-top:solid #D5CAB4 1px"><b><a href="lista.aspx?tipo=it&e=' + cidD + "&c=" + estD + '">Caixas Eletrônicos em ' + cidD + '-' + estD + '</a></b></td><td style="border-top:solid #D5CAB4 1px">&nbsp;</td><td align="right" style="border-top:solid #D5CAB4 1px">&nbsp;</td></tr>');
        }
    }
    html.push('<tr><td style="height:18px; background:url(img/pista/' + pRoadType + '_chegada.gif) no-repeat scroll 50% 50%">&nbsp;</td><td style="border-top:solid #D5CAB4 1px">&nbsp;</td><td style="border-top:solid #D5CAB4 1px"><b>' + cidD + " - " + estD + '</b></td><td style="border-top:solid #D5CAB4 1px">&nbsp;</td><td align="right" style="border-top:solid #D5CAB4 1px"><a href="javascript:center(%27' + sg[kk].point.x + '%27,%27' + sg[kk].point.y + '%27, 12);"><img src="img/ico_lupa.gif" border="0" /></a></td></tr></table>');
    document.getElementById("ctl00_cphBody_divDesc").innerHTML = html.join('');
    document.getElementById('ctl00_cphBody_divRRRota').innerHTML = htmlEstrada.join('');
    htmlPedagio.push('<td><b>TOTAL:</b></td><td align="right"><b>R$' + rtt.totaltollFeeCost.formatKm() + '</b></td></tr></table>');
    document.getElementById("ctl00_cphBody_resPedagio").innerHTML = htmlPedagio.join('');
    document.getElementById("divLoadMap").style.display = "none";
    map.addControl(new GLargeMapControl());
}
function isRotaRodoviaria(addressLocation) {
    if (addressLocation != null) {
        if (addressLocation.city != null) {
            if (addressLocation.city.name.indexOf('|') != -1) return true;
            else {
                var desc = addressLocation.description; if (desc.substring(2, 3) == '-' && !isNaN(desc.substring(3, 7))) return true;
                else return false;
            }
        }
        else { var desc = addressLocation.description; if (desc.substring(2, 3) == '-' && !isNaN(desc.substring(3, 7))) return true; else return false; }
    } else return false;
}
function criaIcone(referencia) {
    if (referencia == "origem") {
        var icon = new GIcon();
        icon.image = "img/ic_origem.gif"; icon.iconAnchor = new GPoint(16, 6);
        icon.infoWindowAnchor = new GPoint(32, 13); icon.infoShadowAnchor = null;
        icon.iconSize = new GSize(32, 13);
        return icon;
    }
    if (referencia == "destino") {
        var icon = new GIcon();
        icon.image = "img/ic_destino.gif"; icon.iconAnchor = new GPoint(17, 6);
        icon.infoWindowAnchor = new GPoint(34, 13); icon.infoShadowAnchor = null;
        icon.iconSize = new GSize(34, 13);
        return icon;
    }
    if (referencia == "endereco") {
        var icon = new GIcon();
        icon.image = "img/ic_endereco.gif"; icon.iconAnchor = new GPoint(10, 5);
        icon.infoWindowAnchor = new GPoint(10, 10); icon.infoShadowAnchor = null;
        icon.iconSize = new GSize(10, 10);
        return icon;
    }
}
function adicionaMarker(sg, kk) {
    var str = ''; var ponto = null; var icone = false;
    icone = true;
    ponto = sg[kk].point;
    str = '<b>' + sg[kk].tollFeeDetails.name + '</b><br/>' + sg[kk].tollFeeDetails.concession + '<br />' + sg[kk].tollFeeDetails.direction + '<br />' + sg[kk].tollFeeDetails.address + '<br/>' + sg[kk].tollFeeDetails.phone + '<br/>Preço:<b> R$ ' + sg[kk].tollFeeDetails.price.formatKm() + '</b>';
    var marker = new GMarker(ponto, geraIcone(icone));
    marker.bindInfoWindowHtml('<div style="width:200px;text-align:center;background-color:#FFF">' + str + '</div>');
    map.addOverlay(marker); _markers.push(marker);
    return _markers.length;
}
function geraIcone(alt) {
    var hIcon = new GIcon(); hIcon.image = 'img/servicos/ic_pedagio.gif'; hIcon.iconSize = new GSize(8, 12); hIcon.infoWindowAnchor = new GPoint(4, 12);
    hIcon.iconAnchor = hIcon.infoWindowAnchor; hIcon.printImage = hIcon.image;
    return hIcon;
}
function lf_Info(markerIndex) { GEvent.trigger(_markers[markerIndex - 1], 'click'); var ponto = Sys.UI.DomElement.getLocation(document.getElementById('divMap')); window.scrollTo(ponto.x, ponto.y); }

// Busca de Cidade //
function enviarDadosCity() {
    var city = document.getElementById("ctl00_cphBody_AutoComplete1_hdnSelectedValue").value;
    var objtCity = eval('(' + city + ')');
    document.getElementById("ctl00_cphBody_hfCidade").value = objtCity.city.name + "|" + objtCity.city.state + "|" + objtCity.point.x + "|" + objtCity.point.y;

    document.getElementById("aspnetForm").action = "mapa.aspx";
    document.getElementById("aspnetForm").submit();
}
function ShowMap(name, state, x, y) {
    map = new MMap2(document.getElementById('divMap'));
    map.setCenter(new MPoint(x, y), 10);
    map.addControl(new GLargeMapControl());

    var marker = new GMarker(new MPoint(x, y), criaIcone("endereco"));
    map.addOverlay(marker);

    window.setTimeout('Tload();', 3000);
}
function Tload() {
    document.getElementById("divLoadMap").style.display = "none";
}
function CriaPag(uf, cidade, pag, tipo) {
    PageMethods.buscaDadosAg(uf, cidade, pag, tipo, retorno);
}
function retorno(r) {
    if (r.length == "0") {
        document.getElementById("ctl00_cphBody_lblContPag").innerHTML = "Não foi localizado nenhum estabelecimento próximo à cidade informada.";
    } else {
        criarPaginador(r[0].pagina, r[0].ttReg, r[0].CIDADE, r[0].UF, 5, 29);
        document.getElementById("ctl00_cphBody_divDados").innerHTML = "";

        var html = "";
        for (var i = 0; i < r.length; i++) {
            html += "<table width='515' cellspacing='0' cellpadding='0' border='0' bgcolor='#FFCB7F'>" +
                        "<tr >";
            if (r[i].tipo == "Agências")
                html += "<td colspan='3' class='subtitulo' bgcolor='#FFCB7F' width='515' height='20'>&nbsp;&nbsp;<b>AGÊNCIA " + r[i].AGENCIA + "</b></td>";
            else
                html += "<td colspan='3' class='subtitulo' bgcolor='#FFCB7F' width='515' height='20'>&nbsp;&nbsp;<b>" + r[i].AGENCIA + "</b></td>";
            html += "</tr>" +
                        "<tr>" +
                            "<td width='10'>&nbsp;</td>" +
                            "<td align='left' valign='top'>" +
                                "<table cellspacing='1' cellpadding='2' border='0' width='515'>" +
                                    "<tr>" +
                                        "<td width='65' class='texto' bgcolor='#FFF5CD'><b>Endereço:</b></td>" +
                                        "<td width='485' class='texto' bgcolor='#FFFFFF'><b>" + r[i].LOGRADOURO + "</b></td>" +
                                    "</tr>" +
                                    "<tr>" +
                                      "<td width='65' class='texto' bgcolor='#FFF5CD'><b>Bairro:</b></td>" +
                                      "<td width='485' class='texto' bgcolor='#FFFFFF'><b>" + r[i].BAIRRO + "</b></td>" +
                                    "</tr>" +
                                    "<tr>" +
                                      "<td width='65' class='texto' bgcolor='#FFF5CD'><b>Cidade:</b></td>" +
                                      "<td width='485' class='texto' bgcolor='#FFFFFF'><b>" + r[i].CIDADE + "</b></td>" +
                                    "</tr>" +
                                    "<tr>" +
                                      "<td width='65' class='texto' bgcolor='#FFF5CD'><b>Estado:</b></td>" +
                                      "<td width='485' class='texto' bgcolor='#FFFFFF'><b>" + r[i].UF + "</b></td>" +
                                    "</tr>" +
                                    "<tr>" +
                                      "<td width='65' class='texto' bgcolor='#FFF5CD'><b>CEP:</b></td>" +
                                      "<td width='485' class='texto' bgcolor='#FFFFFF'><b>" + r[i].CEP + "</b></td>" +
                                    "</tr>" +
                                    "<tr>" +
                                      "<td width='65' class='texto' bgcolor='#FFF5CD'><b>Telefone:</b></td>" +
                                      "<td width='485' class='texto' bgcolor='#FFFFFF'><b>" + r[i].TEL + "</b></td>" +
                                    "</tr>" +
            /*"<tr>" +
            "<td width='65' class='texto' bgcolor='#FFF5CD'><b>e-mail:</b></td>" +
            "<td width='485' class='texto' bgcolor='#FFFFFF'><b>" + r[i].EMAIL + "</b></td>" +
            "</tr>" +*/
                                "</table>" +
                            "</td>" +
                        "</tr>" +
                        "<br />" +
                    "</table>";
        }
        document.getElementById("ctl00_cphBody_divDados").innerHTML = html;
    }
}
function criarPaginador(pag, totalRegs, cid, uf, regsPag, faixa) {
    var inicial, final;
    if (totalRegs <= regsPag)
        document.getElementById("ctl00_cphBody_divPag").innerHTML = "";
    else {
        var nPags = Math.ceil(totalRegs / regsPag);
        if (nPags > faixa) {
            if (pag > faixa)
                inicial = pag - faixa;
            else
                inicial = 1;

            final = inicial + faixa;
        }
        else {
            inicial = 1;
            final = nPags;
        }
        var htmlPaginador = new Array();
        htmlPaginador.push("<table width='auto' heigth='20px'><br />");
        if (nPags > 1) {
            for (var i = inicial; i <= final; i++) {
                htmlPaginador.push("<td align='center' width='10px' style='border:solid 1px #D69610'>");
                if (i == pag)
                    htmlPaginador.push(i);
                else
                    htmlPaginador.push("<a href=\"#topo\" onclick=\"javascript:CriaPag('" + uf + "','" + cid + "','" + i + "');\">" + i + "</a>");
                htmlPaginador.push("</td>");
            }
            htmlPaginador.push("</tr></table>");
        }
        document.getElementById("ctl00_cphBody_divPag").innerHTML = htmlPaginador.join("");
    }
}
function CaminhoInverso() {

    //totalE = 0;
    //document.getElementById("divLoadMap").style.display = "block";
    var org = document.getElementById("ctl00_cphBody_hfDestino").value.split('|');
    var dst = document.getElementById("ctl00_cphBody_hfOrigem").value.split('|');

    document.getElementById("ctl00_cphBody_lblOrigem").innerHTML = org[0] + ", " + org[1];
    document.getElementById("ctl00_cphBody_lblDestino").innerHTML = dst[0] + ", " + dst[1];
    teste = 1;
    //ShowMapRota(org[0], org[1], dst[0], dst[1], org[2], org[3], dst[2], dst[3], document.getElementById("ctl00_cphBody_hfVeiculo").value);
    TesteTeste(org[0], org[1], dst[0], dst[1], org[2], org[3], dst[2], dst[3], document.getElementById("ctl00_cphBody_hfVeiculo").value);


}
function center(x, y) {
    map.setCenter(new MPoint(x, y), 11);
    var ponto = Sys.UI.DomElement.getLocation(document.getElementById('divMap'))
    window.scrollTo(ponto.x, ponto.y);
}

function TesteTeste(estO, cidO, estD, cidD, xO, yO, xD, yD, veiculo) { 
        map.clearOverlays();
        routeManager.destroy();
        document.getElementById("ctl00_cphBody_hfOrigem").value = estO + "|" + cidO + "|" + xO + "|" + yO;
        document.getElementById("ctl00_cphBody_hfDestino").value = estD + "|" + cidD + "|" + xD + "|" + yD;
        var veiculo = veiculo.split("|");
        var ro = new MRouteOptions();
        var rd = new MRouteDetails();
        if (veiculo[3] == "0")
            rd.optimizeRoute = false;
        else
            rd.optimizeRoute = true;
        rd.routeType = 0;
        rd.descriptionType = 0;

        var ve = new MVehicle();
        ve.tankCapacity = veiculo[2];
        ve.averageConsumption = veiculo[1];
        ve.fuelPrice = veiculo[0];
        ve.averageSpeed = 80;
        ve.tollFeeCat = veiculo[4];

        var ro = new MRouteOptions();
        ro.language = "portugues";
        ro.vehicle = ve;
        ro.routeDetails = rd;

        var rs = new Array();
        rs[0] = new MRouteStop();
        rs[0].description = cidO;
        var point = new MPoint();
        point.x = xO;
        point.y = yO;
        rs[0].point = point;

        rs[1] = new MRouteStop();
        rs[1].description = cidD;
        var point = new MPoint();
        point.x = xD;
        point.y = yD;
        rs[1].point = point;

        var rp = new Array;
        var routePointAux;
        routePointAux = new MRoutePoint();
        routePointAux.routeStop = rs[0];
        routePointAux.icon = criaIcone("origem");
        rp.push(routePointAux);

        routePointAux = new MRoutePoint();
        routePointAux.routeStop = rs[1];
        routePointAux.icon = criaIcone("destino");
        rp.push(routePointAux);


        //map = new MMap2(document.getElementById('divMap'));
        routeManager = new MRouteMannager(map);
        routeManager.createRoute(rp, ro, null);

        routeManager.createRoute(rp, ro, null, function(result) { ri(result, estO, cidO, estD, cidD, xO, yO, xD, yD, veiculo[0], veiculo[1], veiculo[2], veiculo[4]); });
}
