﻿var _estabs = null;
var _addLoc = null;
var _searchType = null;

function findCity()
{
    MontaFiltro();

     _searchType = "city";
  
     if(typeof MaplinkAPI == 'undefined') return; 
     control = new MaplinkAPI();
     if(!control) return;
	 control.setAutoShowErrors(false);
	 control.setDivWait("divLoading");    
   
    var city = new MCity();
    if(QueryString("cidade") != "" && QueryString("UF") != "") {
        city.state = QueryString("UF");
        city.name = QueryString("cidade");       
    }
    else {
        city.state = $("cboUFs").value;
        city.name = $("cboCities").value;    
    }
    
    var rr = new ResultRange(); 
	rr.pageIndex = 1;
	rr.recordsPerPage = 1;
	     
    var ao = new MAddressOptions();
    ao.usePhonetic = true;
    ao.searchType = 0;
    ao.resultRange = rr;
 
    var wsAddrLocator = new MWsAdressLocator(); 
    wsAddrLocator.findCity(city, ao, function(cli)
        {
              if(cli != null && cli.cityLocation != null && cli.cityLocation.length == 1)
              {
                    findEstabs(cli.cityLocation[0].point.x, cli.cityLocation[0].point.y, city.name, city.state);
              }
        });
}

function findAddress()
{
    MontaFiltro();

     _searchType = "address";
      
//     if($("txtStreet").value.length < 3) {
//         alert("A rua do endereço deve ter no mínimo três caracteres.");
//         return;
//     }
    
     if(typeof MaplinkAPI == 'undefined') return; 
     control = new MaplinkAPI();
     if(!control) return;
	 control.setAutoShowErrors(false);
	 control.setDivWait("divLoading");   
    
     var add = new MAddress();
     add.street = $("txtStreet").value.replace('-', ' ');
     add.houseNumber = $("txtNumber").value;
     add.city = new MCity();
     add.city.name = $("cboCities").value;
     add.city.state = $("cboUFs").value;
    
     var mPagAdd = montaMPagAdd("divPagAddInt", $("cboCities").value, "confirmar");
     mPagAdd.onShow = function () {
               MElement.show("tblBuscas");
               MElement.show("divPagAddExt");
               MElement.hide("tblCamposPesquisa");
               MElement.hide("divPagEstabExt"); 
     };
  
    var mGeo = new MGeocoderMannager(mPagAdd);
    mGeo.findAddress(add,
            function(addLoc) {
                if(!objValido(addLoc))
                {
                    alert("O endereço não foi encontrado.");
                    return;
                }
               
                _addLoc = addLoc; 
                findEstabs(addLoc.point.x, addLoc.point.y, $("cboCities").value, $("cboUFs").value);
            });      
}

function findEstabs(x, y, cidade, estado)
{
    MElement.show("divLoading"); 
    MElement.hide("divPagAddExt");
    MElement.hide("divPagEstabExt");  
    MElement.hide("tblCamposPesquisa");
    MElement.hide("tblBuscas");   
   
    var strData = "SLType=" + $("hiddenSLType").value;
    //strData += "&tabela=" + $("hiddenTabela").value;
    strData += "&X=" + x;
    strData += "&Y=" + y;
    strData += "&cidade=" + cidade;
    strData += "&estado=" + estado;
    strData += "&bilhete=" + ($("chbBilhete").checked ? "1" : "0");
    strData += "&recarga=" + ($("chbRecarga").checked ? "1" : "0");
    strData += "&citybus=" + ($("chbCitybus").checked ? "1" : "0");

    var ajaxUtil = new AJAXUtil(AJAX_UTIL_POST, $("hiddenURLEstabs").value, callBackFindEstabs);
    ajaxUtil.setResponseType(AJAX_UTIL_PLAIN_TEXT);
    ajaxUtil.setParamsPost(strData);
    ajaxUtil.getData(); 
}

function callBackFindEstabs(data)
{
    MElement.hide("divLoading");   
    MElement.show("tblBuscas"); 
    
    _estabs = eval("(" + data + ")"); 
    if(_estabs.length > 0)
    {
        MElement.show("divPagEstabExt"); 
    
        var htmlEstabs = new Array();
        
        for(var i = 0; i < _estabs.length; i++)
        { 
            htmlEstabs[i]  = '<table width="530px" align="center" style="margin-top: 2px">';
            htmlEstabs[i] += '<tr><td>';
            htmlEstabs[i] += '<b>' + _estabs[i].Name + '</b><br />'; 
            htmlEstabs[i] +=  _estabs[i].Address.Street + (objValido(_estabs[i].Address.Number)? ", " + _estabs[i].Address.Number: "") + (objValido(_estabs[i].Address.District)? " - " + _estabs[i].Address.District: "") + '<br />';
            htmlEstabs[i] +=  (objValido(_estabs[i].Address.CEP)? "CEP: " + _estabs[i].Address.CEP + " - ": "") + (objValido(_estabs[i].Address.City)? _estabs[i].Address.City: "") + (objValido(_estabs[i].Address.State)? " - " + _estabs[i].Address.State: "") + "<br />";
            htmlEstabs[i] +=  (objValido(_estabs[i].Memo)? _estabs[i].Memo.replace(/\`/g, "'"): "");
            htmlEstabs[i] += _estabs[i].Funcionamento;
            htmlEstabs[i] += '</td><td style="text-align: right; width: 100px">';
            htmlEstabs[i] += '<a href="javascript:showMap(' + i + ')">Ver Mapa</a><br />';
            if(_searchType != "city" && _searchType != "neighborhood" && _estabs[i].AllowRoute == true)
            {
                htmlEstabs[i] += '<a href="javascript:routeByCar(' + i + ')">Como chegar de carro</a><br />';
                htmlEstabs[i] += '<a href="javascript:routeOnFoot(' + i + ')">Como chegar a pé</a>';  
            }
            htmlEstabs[i] += '</td></tr>';
            htmlEstabs[i] += '</table>';
        }
        
        if($("hiddenClientCode").value == "30") // WIFI
            mPag = new MPaginationControl("divPagEstabInt", "texto", "text-align: center", 50);
        else
            mPag = new MPaginationControl("divPagEstabInt", "texto", "text-align: center", 10);
            
        //mPag.setClassLinkNavigation("texto");
	    //mPag.setClassActualNavigation("texto");
        mPag.fxPaginationControl= "moveToPage";

        var minhaColuna= new MColumn("<b>Header</b>", "100%", "left", M_TP_CUSTOM, M_LABEL, htmlEstabs);
        //minhaColuna.customData = htmlEstabs;

        var t = new MTable(530);
        t.noHeader = true;
        t.add(minhaColuna);

        t.setLineStyle('background-color: #F4F4F4'); 
	    t.setLineAlterStyle('background-color: #FFFFFF');
	    //t.setLineClass("texto");
        //t.setLineAlterClass("texto");
        //t.setTitleClass("texto");
    	
        mPag.table = t;

        mPag.definePage(htmlEstabs.length);
        mPag.dataSet = htmlEstabs;

        moveToPage(1);
    }
    else
    {
        MElement.show("divEstabNotFound"); 
    } 
}

function moveToPage(nPag){
	mPag.getPage(nPag);
	mPag.show();
}

function forwardCEP3()
{
    if($("txtCEP5").value.length == 5)
         $("txtCEP3").focus();
}

function findCEP()
{
    MontaFiltro();

    _searchType = "CEP";
     
    if($("txtCEP5").value.length != 5 && $("txtCEP3").value.length != 3)  
    {
         alert("O CEP deve ter 8 digitos.");
         return;
    }
   
    if(typeof MaplinkAPI == 'undefined') return; 
    control = new MaplinkAPI();
    if(!control) return;
	control.setAutoShowErrors(false);
	control.setDivWait("divLoading");   
	
	var add = new MAddress();
    add.zip = $("txtCEP5").value + $("txtCEP3").value;  
     
    var mGeo = new MGeocoderMannager();
    mGeo.findAddress(add,
            function(addLoc) {
                if(!objValido(addLoc))
                {
                    alert("O CEP não foi encontrado.");
                    return;
                }
                
                _addLoc = addLoc;
                findEstabs(addLoc.point.x, addLoc.point.y, addLoc.address.city.name, addLoc.address.city.state) 

            });    
}

function findDistrict()
{
    MontaFiltro();

    _searchType = "district";
    
    var x = parseFloat($("cboDistricts").value.split('/')[0]);
    var y = parseFloat($("cboDistricts").value.split('/')[1]);
      
    findEstabs(x, y, $("cboCities").value, $("cboUFs").value);
 
}

function callFindAddressFunction(ev)
{
    var e;
    if(ev)
        e = ev;
    else
        e = window.event;
     
    if(e.keyCode == 13) {
        findAddress();
    }
}

function callFindCEPFunction(ev)
{
    var e;
    if(ev)
        e = ev;
    else
        e = window.event;
     
    if(e.keyCode == 13) {
        findCEP();
    }
}

function backSLProximity()
{
    MElement.hide("divPagAddExt");
    MElement.hide("divPagEstabExt"); 
    MElement.hide("divEstabNotFound"); 
    MElement.hide("tblBuscas");
    MElement.show("tblCamposPesquisa");
}

function showMap(i)
{
    document.location.href = "mapa.aspx?type=" + $("hiddenSLType").value + "&codcliente=" + $("hiddenClientCode").value + "&codsubcliente=" + _estabs[i].SubClientCode;
}

function routeByCar(i)
{
   $("hiddenRouteType").value = 0;
   $("hiddenAddLoc").value = _addLoc.toJSONString();
   $("formProximityMap").action = "mapa.aspx?type=" + $("hiddenSLType").value + "&codcliente=" + $("hiddenClientCode").value + "&codsubcliente=" + _estabs[i].SubClientCode; 
   $("formProximityMap").submit();    
}

function routeOnFoot(i)
{
   $("hiddenRouteType").value = 2;
   $("hiddenAddLoc").value = _addLoc.toJSONString();
   $("formProximityMap").action = "mapa.aspx?type=" + $("hiddenSLType").value + "&codcliente=" + $("hiddenClientCode").value + "&codsubcliente=" + _estabs[i].SubClientCode; 
   $("formProximityMap").submit();    
}

function MontaFiltro()
{
    var stipo = "";
    if($('chbBilhete').checked)
        stipo += "Bilhete";
    if($('chbRecarga').checked)
    {
        if(stipo == "")
            stipo = 'Carga';
        else
            stipo += ' /Carga';
    }
   
    $('hdnTipo').value = stipo;
}