﻿/// <reference path="../JQuery/jquery-vsdoc.js" />

window.BuscaMapaBox = {
    DivID: null,
    Map: null,
    Refreshing: false,
    Moving: false,
    RefreshTimeoutController: null,
    RefreshData: null,
    IdTipoIntercambio: 0,
    IdTipoProduto: 0,
    AjusteLatitude: 0.01,
    AjusteLongitude: 0.006,
    ComportamentoLanding: false,
    ComportamentoHome: false,
    LastItemType: 0,
    LastObjMapa: {},
    PontosMapa: [],
    WindowData: function(zoomLevel, latitudeMinima, longitudeMinima, latitudeMaxima, longitudeMaxima) {
        this.zoomLevel = zoomLevel;
        this.latitudeMinima = Math.max(parseFloat(latitudeMinima) - BuscaMapaBox.AjusteLatitude, -90);
        this.longitudeMinima = Math.max(parseFloat(longitudeMinima) - BuscaMapaBox.AjusteLongitude, -180);
        this.latitudeMaxima = Math.min(parseFloat(latitudeMaxima) + BuscaMapaBox.AjusteLatitude, 90);
        this.longitudeMaxima = Math.min(parseFloat(longitudeMaxima) + BuscaMapaBox.AjusteLongitude, 180);
    },
    SetZoomStyle: function(zoomLevel) {
        var style = zoomLevel <= 2 ? 'zoom1' :
            zoomLevel <= 4 ? 'zoom2' :
            zoomLevel <= 6 ? 'zoom3' :
            zoomLevel <= 8 ? 'zoom4' :
            zoomLevel <= 10 ? 'zoom5' :
            zoomLevel <= 12 ? 'zoom6' :
            zoomLevel <= 14 ? 'zoom7' :
            zoomLevel <= 16 ? 'zoom8' : 'zoom9';
        $Get('dimZoomLevel').className = style;
    },
    SetMapLayer: function() {
        BuscaMapaBox.Map.SetMapType(Tesla.Map.MapTypes.Street);
    },
    SetSatelliteLayer: function() {
        BuscaMapaBox.Map.SetMapType(Tesla.Map.MapTypes.Satellite);
    },
    SetHybridLayer: function() {
        BuscaMapaBox.Map.SetMapType(Tesla.Map.MapTypes.Hybrid);
    },
    GetWindowData: function() {
        var map = this.Map;
        var dims = map.GetRectangle();
        var zoomLevel = map.GetZoom();
        if (zoomLevel <= 3 || dims == null)
            dims = { X1: -180, X2: 180, Y1: -90, Y2: 90 };
        var ret = new BuscaMapaBox.WindowData(zoomLevel, dims.Y1, dims.X1, dims.Y2, dims.X2);
        return ret;
    },
    Load: function(divID, IdTipoIntercambio) {
        if (this.DivID) alert('Já existe um box de busca nesta janela. Não é permitido carregar mais de um. Desculpe!');
        if (!divID) alert('divID inválido');
        this.DivID = divID;
        this.IdTipoIntercambio = IdTipoIntercambio || 0;
        this.Map = new Tesla.Map.MapControl(this.DivID);
        var map = this.Map;
        map.SetCenter(new Tesla.Map.Point(23, 0), 1);
        map.OnMove = this.OnMove;
        map.OnMarkerClick = this.OnMarkerClick;
        map.DisableToolPanel();
        //BuscaMapaBox.BeginAtualizaMapa();
        setTimeout('BuscaMapaBox.BeginAtualizaMapa()', 1000);
    },
    OnMove: function() {
        //if (!BuscaMapaBox.Moving)
        BuscaMapaBox.BeginAtualizaMapa();
    },
    OnMarkerClick: function(obj) {
        BuscaMapaBox.SelectItem(obj.Data.Tipo, obj.Data.LatitudeMapa, obj.Data.LongitudeMapa, obj.Data, obj, obj.Data.NomeMapa);
    },
    BeginAtualizaMapa: function() {
        if (this != BuscaMapaBox) alert('invalid instance');
        if (BuscaMapaBox.InfoWindowOpen) { return; }
        if (BuscaMapaBox.Refreshing) return;
        BuscaMapaBox.ClearTimeoutHandler();
        BuscaMapaBox.Refreshing = true;
        BuscaMapaBox.RefreshTimeoutController = setTimeout('BuscaMapaBox.RefreshTimeoutHandler()', 10000);
        var dados = this.GetWindowData();
        this.RefreshData = { Window: dados };
        if (dados.zoomLevel < 3) {
            //Continentes
            Ajax.BuscaMapa.ListaContinentes(BuscaMapaBox.IdTipoIntercambio, BuscaMapaBox.IdTipoProduto, this.EndAtualizaMapa);
        }
        else if (dados.zoomLevel < 4 || BuscaMapaBox.IdTipoIntercambio == 2 || (BuscaMapaBox.IdTipoIntercambio == 1 && BuscaMapaBox.IdTipoProduto == 2)) {
            //Paises
            Ajax.BuscaMapa.ListaPaises(dados.latitudeMinima, dados.longitudeMinima, dados.latitudeMaxima, dados.longitudeMaxima, this.IdTipoIntercambio, this.IdTipoProduto || 0, this.EndAtualizaMapa);
        }
        /*
        else if (dados.zoomLevel < 7)
        {
        //Regioes
        Ajax.BuscaMapa.ListaRegioes(dados.latitudeMinima, dados.longitudeMinima, dados.latitudeMaxima, dados.longitudeMaxima, this.IdTipoIntercambio, this.EndAtualizaMapa);
        }
        */
        else if (dados.zoomLevel < 10 || BuscaMapaBox.IdTipoIntercambio != 1 || BuscaMapaBox.IdTipoProduto == 2) //Tipo de intercambio definido e diferente de estudo
        {
            //Cidades
            Ajax.BuscaMapa.ListaCidades(dados.latitudeMinima, dados.longitudeMinima, dados.latitudeMaxima, dados.longitudeMaxima, this.IdTipoIntercambio, this.IdTipoProduto || 0, this.EndAtualizaMapa);
        }
        else if ((BuscaMapaBox.IdTipoIntercambio == 1 || BuscaMapaBox.IdTipoIntercambio == 0)) {
            //Centros           
            Ajax.BuscaMapa.ListaCentros(dados.latitudeMinima, dados.longitudeMinima, dados.latitudeMaxima, dados.longitudeMaxima, this.IdTipoIntercambio, BuscaMapaBox.IdTipoProduto, this.EndAtualizaMapa);
        }
        else {
            BuscaMapaBox.ClearTimeoutHandler();
        }
    },
    RefreshTimeoutHandler: function() {
        if (BuscaMapaBox.Refreshing) {
            alert("Não foi possível processar sua requisição no momento. Aguarde alguns instantes e tente novamente.");
        }
        BuscaMapaBox.Refreshing = false;
    },
    ClearTimeoutHandler: function() {
        BuscaMapaBox.Refreshing = false;
        clearTimeout(BuscaMapaBox.RefreshTimeoutController);
    },
    EndAtualizaMapa: function(ret) {
        $Get('DivResultadoMapa').style.display = "none";
        BuscaMapaBox.AtualizaMapa(ret);
        BuscaMapaBox.ClearTimeoutHandler();
    },
    AtualizaMapa: function(ret) {
        if (!BuscaMapaBox.Refreshing) return;
        //if (this.LastItemType != undefined && this.LastItemType == 5)
        //{
        //    BuscaMapaBox.ClearTimeoutHandler();
        //    return;
        //}
        var map = this.Map;
        map.ClearMarkers();
        var icon = new Tesla.Map.MarkerIcon(page.ResolveUrl('~/images/Geral/ico_mapa_generico.gif'), new Tesla.Map.Size(16, 16), new Tesla.Map.Point(5, 5), null, null);
        BuscaMapaBox.PontosMapa = ret;
        for (var i = 0; i < ret.length; i++) {
            var marker = new Tesla.Map.Marker(map, new Tesla.Map.Point(ret[i].LatitudeMapa, ret[i].LongitudeMapa), icon);
            marker.Data = ret[i];
            var idTipoIntercambio = BuscaMapaBox.IdTipoIntercambio || 0;
            var idTipoProduto = BuscaMapaBox.IdTipoProduto || 0;
            var imagem = 'ico_mapa_geral.gif';
            var path = page.ResolveUrl('~/images/Geral/');
            switch (parseInt(idTipoIntercambio)) {
                case 1:
                    imagem = 'ico_mapa_estudo.gif';
                    if (idTipoProduto == 2)
                        imagem = 'ico_mapa_ensinomedio.gif';
                    break;
                case 2:
                    imagem = 'ico_mapa_trabalho.gif';
                    break;
                case 3:
                    imagem = 'ico_mapa_turismo.gif';
                    break;
            }
            marker.Icon = new Tesla.Map.MarkerIcon(path + imagem, new Tesla.Map.Size(32, 32), new Tesla.Map.Point(16, 16));
            //marker.Icon = new Tesla.Map.MarkerIcon(path + imagem);
            map.AddMarker(marker);
        }
        BuscaMapaBox.SetZoomStyle(this.GetWindowData().zoomLevel);
        BuscaMapaBox.ClearTimeoutHandler();
    },
    IncreaseZoom: function() {
        var zoomLevel = this.GetWindowData().zoomLevel;
        zoomLevel = Math.min(19, zoomLevel + 1);
        this.Map.SetZoom(zoomLevel);
    },
    DecreaseZoom: function() {
        var zoomLevel = this.GetWindowData().zoomLevel;
        zoomLevel = Math.max(0, zoomLevel - 1);
        this.Map.SetZoom(zoomLevel);
    },
    ResetZoom: function() {
        var center = this.Map.GetCenter();
        center.Latitude = 23;
        center.Longitude = 0;
        this.Map.SetCenter(center);
        setTimeout('BuscaMapaBox.Map.SetZoom(1);', 1000);
    },
    SelectItem: function(itemType, latitude, longitude, itemData, objMapa, nomeEscola) {
        var zoomLevel = 3;

        switch (itemType) {
            case 0:
                zoomLevel = 1;
                break;
            case 1:
                zoomLevel = 3;
                break;
            case 2:
                zoomLevel = 4;
                break;
            case 3:
                zoomLevel = 10;
                break;
            case 4:
                zoomLevel = 12;
                break;
            case 5:
                zoomLevel = 12;
                LastObjMapa = objMapa;
                BuscaMapaBox.InfoWindowOpen = true;
                Ajax.BuscaMapa.InfosEscolas(nomeEscola, this.EndRecuperaInfosEscolas);
                this.LastItemType = 5;
                /*if (this.LastItemType == 5)
                {
                LastObjMapa = objMapa;
                Ajax.BuscaMapa.InfosEscolas(nomeEscola, this.EndRecuperaInfosEscolas);
                this.LastItemType = 5;
                return;
                }*/
                break;
        }

        var center = this.Map.GetCenter();
        center.Latitude = latitude;
        center.Longitude = longitude;

        BuscaMapaBox.Moving = true;

        var zoomLevelAtual = BuscaMapaBox.Map.GetZoom();

        if (zoomLevel > zoomLevelAtual)
            this.Map.SetCenter(center, zoomLevel);
        else
            this.Map.SetCenter(center);

        setTimeout('BuscaMapaBox.Moving = false;', 100);

        if (this.OnSelectItem) this.OnSelectItem(itemType, latitude, longitude, itemData);
        this.LastItemType = itemType;
    },
    EndRecuperaInfosEscolas: function(retorno) {
        var objMapa = this.LastObjMapa;
        BuscaMapaBox.DivInfosEscolas(objMapa, retorno);
        ResultadoBuscaMapa.IdInstituicao = retorno.IdInstituicao;
        ResultadoBuscaMapa.EfetuaBusca();
    },
    DivInfosEscolas: function(objMapa, retorno) {
        var descricao = retorno.Descricao;
        descricao = descricao.split('.');
        descricao = descricao[0];

        var imagemInstituicao = retorno.UrlArquivoImagem;
        if (imagemInstituicao == null || imagemInstituicao == undefined)
            imagemInstituicao = page.ResolveUrl('~/images/Geral/Img_Padrao_SemInstituicao.gif');
        var htmlDivMarker = '<div style="width:410px;">' +
        '<div>' +
        '<img style="width:60px; height:60px; float:left; padding-right: 10px;" alt="" src="' + imagemInstituicao + '">' +
        '<p><b>' + retorno.Nome + '</b></p> <p>' + descricao +
        '. <a href="#" onclick="jQuery(\'#spnNomeEscola\').click(); RetornaInformacoesInstituicao(' + retorno.IdInstituicao + ');">Leia mais...</a></p> <br />' +
        '<a href="#" onclick="$(\'html,body\').animate({scrollTop: $(\'#lnkDivInfosEscolasMapa\').offset().top}, 2000);" style="float:right;">Veja os cursos desta escola</a>' +
        '</div>' +
        '</div>';

        if (BuscaMapaBox.CurrentInfoWindow && BuscaMapaBox.CurrentInfoWindow.close)
            BuscaMapaBox.CurrentInfoWindow.close();

        //BuscaMapaBox.InfoWindowOpen = true;
        BuscaMapaBox.CurrentInfoWindow = objMapa.ShowInfo('', htmlDivMarker);
        google.maps.event.addListener(BuscaMapaBox.CurrentInfoWindow, 'closeclick', function() { BuscaMapaBox.InfoWindowOpen = false; });
        return objMapa;
    },
    MoveFocus: function(dirUp, dirRight) {
        var factor = Math.max(10 - this.Map.GetZoom(), 1);
        dirRight = (dirRight / factor).toFixed(2);
        dirUp = (dirUp / factor).toFixed(2);
        var center = this.Map.GetCenter();
        var win = this.GetWindowData();
        var nextLatMax;
        var nextLngMax;
        var nextLatMin;
        var nextLngMin;

        nextLatMax = win.latitudeMaxima + (dirUp * (win.latitudeMaxima - win.latitudeMinima));
        nextLngMax = win.longitudeMaxima + (dirRight * (win.longitudeMaxima - win.longitudeMinima));
        nextLatMin = win.latitudeMinima + (dirUp * (win.latitudeMaxima - win.latitudeMinima));
        nextLngMin = win.longitudeMinima + (dirRight * (win.longitudeMaxima - win.longitudeMinima));

        center.Latitude += (dirUp * (win.latitudeMaxima - win.latitudeMinima));
        center.Longitude += (dirRight * (win.longitudeMaxima - win.longitudeMinima));
        this.Map.SetCenter(center);
    },
    OnDdlTipoIntercambio: function(combo) {
        BuscaMapaBox.IdTipoIntercambio = combo.SelectedValue();
        BuscaMapaBox.BeginAtualizaMapa();
        if (BuscaMapaBox.OnChangeTipoIntercambio) BuscaMapaBox.OnChangeTipoIntercambio(combo);
    },
    OnChangeTipoIntercambio: function(combo) {
    },
    RedirectPaginaInterna: function(itemType, latitude, longitude, itemData) {
        if (itemType == 1) return;
        var url = page.ResolveUrl('~/aspx/Produtos/ResultadoBuscaMapa.aspx');
        url += '?';
        url += 'type=' + itemType.toString() + '&';
        url += 'latitude=' + latitude.toFixed(8).replace(',', '.') + '&';
        url += 'longitude=' + longitude.toFixed(8).replace(',', '.') + '&';
        url += 'id=' + itemData.IdItemBuscaMapa.toString() + '&';
        if (BuscaMapaBox.IdTipoIntercambio != 0)
            url += 'IdTipoIntercambio=' + BuscaMapaBox.IdTipoIntercambio.toString() + '&';
        if (BuscaMapaBox.IdTipoProduto != 0)
            url += 'IdTipoProduto=' + BuscaMapaBox.IdTipoProduto.toString();
        location.href = url;
    },
    OnSelectItem: function(itemType, latitude, longitude, itemData) {
        return true;
    },
    SetLandingBehavior: function() {
        BuscaMapaBox.ComportamentoLanding = true;
        BuscaMapaBox.OnSelectItem = BuscaMapaBox.RedirectPaginaInterna;
    },
    SetHomeBehavior: function() {
        BuscaMapaBox.ComportamentoHome = true;
        BuscaMapaBox.OnSelectItem = BuscaMapaBox.RedirectPaginaInterna;
    },
    SetText: function(txt) {
        page.BoxBuscaMapaControls_h3Localidade.innerHTML = txt;
    },
    InitScreen: function(itemType, latitude, longitude, id, text) {
        setTimeout('BuscaMapaBox.BeginAtualizaMapa();', 6000);
        BuscaMapaBox.SetText(text);
        BuscaMapaBox.SelectItem(itemType, latitude, longitude, { 'IdItemBuscaMapa': id });
    },
    LoadSelecioneIntercambioVazio: function() {
        //        $Get('divSelecioneIntercambioVazio').style.display = "none";

        //        var url = location.search.split("IdTipoIntercambio=");
        //        url[1] = url[1].substr(0, 1);

        //        if (url[1] == 0 || url[1] == '')
        //            $Get('divSelecioneIntercambioVazio').style.display = "block";

        var idIntercambioUrl = page.QueryString['idtipointercambio'];
        if (idIntercambioUrl != undefined && idIntercambioUrl != null && idIntercambioUrl != '' && idIntercambioUrl != 0)
            $Get('divSelecioneIntercambioVazio').style.display = "none";
        else
            $Get('divSelecioneIntercambioVazio').style.display = "block";
    }
}

RetornaInformacoesInstituicao = function(IdInstituicao)
{
    Ajax.BuscaMapa.RetornaInformacoesInstituicao(IdInstituicao, this.EndRetornaInformacoesInstituicao);    
}

EndRetornaInformacoesInstituicao = function(retorno)
{ 
    $Get('divNomeEscola').style.display = "";
    
    /*if (retorno != null && retorno != undefined)
    {
        $Get('divRetornoNomeEscola').style.display = "";
        $Get('spnRetornoNomeEscolaTexto').innerHTML = retorno.Nome;
        $Get('divRetornoImgInstituicao').src = retorno.UrlArquivoImagem;
        $Get('parRetornoTextoEscola').innerHTML = retorno.Descricao;
    }*/
}

/* NOVA BUSCA MAPA HOME */

function HabilitaEnterBusca(objeto, event)
{
    if (event.keyCode == 13)
    {        
        if ($Get(objeto).value != '')
            Ajax.BuscaMapaHome.BuscaMapaBoxHome($Get(objeto).value, End_PostBuscaMapaHome);
        else
        {
            alert('Digite um termo para pesquisar');
            return false;
        }
    }
}

PostBuscaMapaHome = function(objeto)
{
    $Get(objeto).value = $Get(objeto).value.replace(/%/g, '').Trim();

    var tipoIntercambio = page.ddlTipoIntercambio.SelectedValue();
    if (tipoIntercambio == null || tipoIntercambio == '' || tipoIntercambio == 0)
    {
        if (page.ddlTipoIntercambioMapa != undefined)
            tipoIntercambio = page.ddlTipoIntercambioMapa.SelectedValue();
    }
    /*if (tipoIntercambio == 0)
    {
    alert('Selecione um tipo de intercâmbio para efetuar a pesquisa');
    return false;
    }*/

    if ($Get(objeto).value == '' || $Get(objeto).value == 'Digite um País ou Cidade')
    {
        alert('Digite um termo para pesquisar');
        return false;
    }
    if ($Get(objeto).value.length < 3 || $Get(objeto).value == 'Digite um País ou Cidade')
    {
        alert('Digite um termo com mais de 3 caracteres para pesquisar');
        return false;
    }
    Ajax.BuscaMapaHome.BuscaMapaBoxHome($Get(objeto).value, End_PostBuscaMapaHome);
}

End_PostBuscaMapaHome = function(rt)
{
    if (rt != undefined && rt != '')
    {
        if (rt.Count() > 0 && rt[0].Latitude != null || rt[0].Longitude != null)
        {
            /*if (page.ddlTipoIntercambio.SelectedValue() != 0)
            {
                var tipoIntercambio = page.ddlTipoIntercambio.SelectedValue().toString();
                if (tipoIntercambio == null || tipoIntercambio == '' || tipoIntercambio == 0)
                    tipoIntercambio = page.ddlTipoIntercambioMapa.SelectedValue();              
            }*/

            if (page.ddlTipoIntercambioMapa == undefined)
                tipoIntercambio = page.ddlTipoIntercambio.SelectedValue();
            else
                tipoIntercambio = page.ddlTipoIntercambioMapa.SelectedValue();

            var url = page.ResolveUrl('~/aspx/Produtos/ResultadoBuscaMapa.aspx');
            url += '?';
            url += 'id=' + rt[0].Id.toString() + '&';
            url += 'type=' + rt[0].IdTipo.toString() + '&';
            url += 'latitude=' + rt[0].Latitude.toFixed(8).replace(',', '.') + '&';
            url += 'longitude=' + rt[0].Longitude.toFixed(8).replace(',', '.') + '&';
            if (tipoIntercambio != undefined && tipoIntercambio != '')
                url += 'IdTipoIntercambio=' + tipoIntercambio
                
            location.href = url;
        }
        else
        {
            $Get('DivResultadoMapa').style.display = '';
            $Get('pSemResultadoMapa').style.display = '';
            $Get('msgSemResultadoMapa').innerHTML = $Get('txtBuscaMapaHome').value;
        }
    }
    else
    {
        $Get('DivResultadoMapa').style.display = '';
        $Get('pSemResultadoMapa').style.display = '';
        $Get('msgSemResultadoMapa').innerHTML = $Get('txtBuscaMapaHome').value;
    }
}

FechaLoadSelecioneIntercambioVazio = function()
{
   $Get('divSelecioneIntercambioVazio').style.display = "none";
}

FechaDivSemResultadoEstudo = function()
{
    //jQuery("#divSemResultadoEstudo").fadeOut("slow");
    $Get('divSemResultadoEstudo').style.display = "none";
}
