﻿window.App = {};
//para nao repetir o valor do querystring
function GetUrlViaJS(vetor)
{
    var query = document.location.href;
    var subst = '';
    for (var i = 0; i <= vetor.Count(); i++)
    {
        var vlInicial = query.indexOf(vetor[i]);
        if (vlInicial > 0)
        {
            var varsub = query.substring(query.indexOf(vetor[i]));
            subst = varsub.indexOf('&') <= 0 ? query.substring(query.indexOf(vetor[i]) - 1) : varsub.substring(varsub.indexOf(vetor[i]), varsub.indexOf('&') + 1);
            query = query.replace(subst, '');
        }
    }
    return query;
}

// para chamar a página atual com outra ordenação vinda de dropdown
function OrdenaResultado(ordenacao)
{
    var url = GetUrlViaJS(new Array('idOrdenacao'));
    var x = (url.indexOf('?') > 0) ? "&" : "?";
    document.location = String.Format("{0}{1}idOrdenacao={2}", url, x, ordenacao.value);
}

function OrdenaItensPagina(objeto)
{
    var url = GetUrlViaJS(new Array('itensPagina'));
    var x = (url.indexOf('?') > 0) ? "&" : "?";
    document.location = String.Format("{0}{1}itensPagina={2}", url, x, objeto.options[objeto.selectedIndex].value);
}

App.MenuServicos = {
    GetPopup: function()
    {
        return $Get('drop_viagem');
    },
    GetKillZone : function()
    {
        return $Get('drop_viagem_kill_zone');
    },
    Mostra: function()
    {
        this.GetPopup().style.visibility = 'visible';
        this.GetKillZone().style.visibility = 'visible';
    },
    Oculta: function()
    {
        this.GetPopup().style.visibility = 'hidden';
        this.GetKillZone().style.visibility = 'hidden';
    }
}

App.MenuServicosDistribuidor = {
    GetPopup: function() {
        return $Get('drop_viagem_distr');
    },
    GetKillZone: function() {
        return $Get('drop_viagem_kill_zone_distr');
    },
    Mostra: function() {
        this.GetPopup().style.visibility = 'visible';
        this.GetKillZone().style.visibility = 'visible';
    },
    Oculta: function() {
        this.GetPopup().style.visibility = 'hidden';
        this.GetKillZone().style.visibility = 'hidden';
    }
}

App.AbrePopup = function()
{
    App.divPop = document.getElementById('divPop');
    var ctrl = App.divPop;
    App.EscondeTela();
    ctrl.style.position = 'absolute';
    ctrl.style.display = '';
    App.CentralizaControleInvisivel(ctrl);
}

App.FechaPopup = function()
{
    App.divPop = document.getElementById('divPop');
    App.ExibeTela();
    App.divPop.style.display = 'none';
}

App.EscondeTela = function()
{
    App.DivEscondeTela = document.getElementById('divEscondeTela');
    App.EscondeTela.Count = (App.EscondeTela.Count || 0) + 1;
    App.TelaHabilitada = false;
    App.DivEscondeTela.style.position = 'absolute';
    App.DivEscondeTela.style.top = '0px';
    App.DivEscondeTela.style.left = '0px';
    App.DivEscondeTela.style.height = document.documentElement.scrollHeight + 'px';
    App.DivEscondeTela.style.width = document.documentElement.scrollWidth + 'px';
    App.DivEscondeTela.style.display = '';
}

App.CentralizaControleInvisivel = function(ctrl, topAlterado)
{
    if (ctrl == null) return;
    ctrl.style.position = 'absolute';
    ctrl.style.display = '';
    ctrl.style.zIndex = 1001;
    var scrollTop = parseInt(document.documentElement.scrollTop) || parseInt(document.body.scrollTop);
    var top = Math.max(scrollTop, scrollTop + document.documentElement.clientHeight - (ctrl.clientHeight) - ((document.documentElement.clientHeight - ctrl.clientHeight) / 2));
    if (top <= 160) top = 165;
    if (topAlterado != null) top = topAlterado;
    ctrl.style.top = top + 'px';
    ctrl.style.left = (document.documentElement.scrollLeft + (document.documentElement.clientWidth / 2) - (ctrl.clientWidth / 2)) + 'px';
}

App.ExibeTela = function()
{
    App.DivEscondeTela = document.getElementById('divEscondeTela');
    App.EscondeTela.Count = (App.EscondeTela.Count || 1) - 1;

    if (App.EscondeTela.Count)
        return;

    App.TelaHabilitada = true;
    App.DivEscondeTela.style.display = 'none';
}
App.Loading = {
    Enabled: true,
    ShowControl: null,
    HideControl: null,
    Timeout: 500,
    InternalShow: function()
    {
        App.Loading.StartControl = null;
        //App.EscondeTela();
        App.CentralizaControleInvisivel($Get('divLoading'));
    },
    InternalHide: function()
    {
        App.Loading.HideControl = null;
        //App.ExibeTela();
        if ($Get('divLoading') != null)
            $Get('divLoading').style.display = 'none';
    },
    Show: function()
    {
        if (!App.Loading.Enabled) return;
        if (App.Loading.HideControl)
        {
            clearTimeout(App.Loading.HideControl);
            App.Loading.HideControl = null;
        }
        if (!App.Loading.StartControl) App.Loading.StartControl = setTimeout('App.Loading.InternalShow()', App.Loading.Timeout);
    },
    Hide: function()
    {
        if (!App.Loading.Enabled) return;
        if (App.Loading.StartControl)
        {
            clearTimeout(App.Loading.StartControl);
            App.Loading.StartControl = null;
        }
        App.Loading.HideControl = setTimeout('App.Loading.InternalHide()', App.Loading.Timeout);
    }
}
Ajax.BeginInvoke = function(componente, metodo, parametros)
{
    App.Loading.Show();
}
Ajax.EndInvoke = function(retorno, componente, metodo, parametros)
{
    App.Loading.Hide();
}
App.AddBookmark = function()
{
    var url = document.location;
    var title = document.title;
    if (window.sidebar) window.sidebar.addPanel(title, url, "");
    else if (window.opera && window.print) {
        var mbm = document.createElement('a');
        mbm.setAttribute('rel', 'sidebar');
        mbm.setAttribute('href', url);
        mbm.setAttribute('title', title);
        mbm.click();
    }
    else if (document.all) { window.external.AddFavorite(url, title); }
}

App.URLRedirect = function(url, action)
{
    if (action == null) action = "get";
    this.url = url;
    this.action = action;
    this.args = [];
    this.Add = function(name, value)
    {
        this.args.push({ 'name': name, 'value': value });
        return this;
    }
    this.Go = function()
    {
        if (action.toLowerCase() == "get")
        {
            var urlRedirect = url + '?';
            for (var i = 0; i < this.args.length; i++)
            {
                if (i > 0) urlRedirect += '&';
                urlRedirect += this.args[i].name + '=' + encodeURIComponent(this.args[i].value);
            }
            location.href = urlRedirect;
        }
        else if (action.toLowerCase() == "post")
        {
            var frm = page.CreateForm('frmUrlRedirect', url, 'post', '_self');
            for (var i = 0; i < this.args.length; i++)
                frm.AddField(this.args[i].name, this.args[i].value);
            frm.submit();
        }
    }
}

App.URLOpen = function(url,nome, statusTam)
{
    this.url = url;
    this.args = [];
    this.Add = function(name, value)
    {
        this.args.push({ 'name': name, 'value': value });
        return this;
    }
    this.Open = function()
    {
        var urlOpen = url + '?';
        for (var i = 0; i < this.args.length; i++)
        {
            if (i > 0)
                urlOpen += '&';
            urlOpen += this.args[i].name + '=' + encodeURIComponent(this.args[i].value);
        }
        window.open(urlOpen,nome,statusTam);
    }
}


App.InicializaMapa = function(latidude, longitude, nomeDiv, titulo, descricao, tipoLoja, endereco) {
    if (Tesla.Map == null || Tesla.Map == "") return;
    if (nomeDiv == null) nomeDiv = 'divMapa';
    var mapa = new Tesla.Map.MapControl(nomeDiv);
    var ponto = new Tesla.Map.Point(latidude, longitude);
    mapa.SetCenter(ponto, 14);
    var marker = mapa.CreateMarker(ponto);
    var imagem = 'ico_mapa_geral.gif';
    var path = page.ResolveUrl('~/images/Geral/');
    switch (window.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;
    }

    if (tipoLoja != null)
        marker.Icon = new Tesla.Map.MarkerIcon(page.ResolveUrl('~/images/Geral/ico_mapa_loja.gif'), new Tesla.Map.Size(42, 36), new Tesla.Map.Point(34, 28));
    else
        marker.Icon = new Tesla.Map.MarkerIcon(path + imagem, new Tesla.Map.Size(32, 32), new Tesla.Map.Point(16, 16));

    var htmlDivMarker = '<div style="width: 250px;"><b>' + titulo + '</b><br>' + descricao + '</div><br /><div id="divLink"><a id="chegar" href="#" onclick="MostrarBuscaEndereco(this); return false;">Como chegar: <b>Até aqui</b></a></div><div id="origem" style="display:none;"><input id="txtOrigem" type="text" /><input id="btnIr" value="Ir" type="button" onclick="AbrirRota(' + "'" + endereco + "'" + ')"/></div>';


    if (titulo && descricao) {
        marker.Info = { "titulo": titulo, "descricao": descricao };
        mapa.CoreExec("openInfoWindow", [ponto.ToApiObject(), htmlDivMarker]);
    }
    mapa.AddMarker(marker);
    mapa.OnMarkerClick = function(marker) {
    if (marker.Info)
            marker.Map.CoreExec("openInfoWindow", [ponto.ToApiObject(), htmlDivMarker]);
    }

    page.Mapa = mapa;
}

App.InsereStreetView = function() {
    page.Mapa.AddNearestStreetViewPanorama();
}

function MostrarBuscaEndereco() {
    document.getElementById('origem').style.display = '';
    document.getElementById('divLink').style.display = 'none';

}

function AbrirRota(endereco) {
       window.open(String.Format('http://maps.google.com.br/maps?daddr={0}&saddr={1}',endereco, document.getElementById('txtOrigem').value));
}

App.InsereTagGoogle = function(url)
{
    try {
        var pageTracker = _gat._getTracker(window.IdGoogleAnalytics);
        pageTracker._trackPageview(url);
    } catch (err) { }

}

App.IsDecimal = function(st)
{
    if (String.IsNullOrEmpty(st))
        return false;

    var pointCount = 0;
    for (var i = 0; i < st.length; i++)
    {
        if (st.charAt(i) == ',')
            pointCount++;
        if (st.charAt(i) != ',' && !st.IsDigit(i))
            return false;
    }
    return pointCount <= 1;
}

App.PostBuscaGeral = function(objeto)
{
    $Get(objeto).value = $Get(objeto).value.replace(/%/g, '').Trim();

    if ($Get(objeto).value == '' || $Get(objeto).value == 'Pesquisar')
    {
        alert('Digite um termo para pesquisar');
        return false;
    }
    if ($Get(objeto).value.length < 3 || $Get(objeto).value == 'Pesquisar')
    {
        alert('Digite um termo com mais de 3 caracteres para pesquisar');
        return false;
    }
    //window.location.href = String.Format("http://{0}/{1}aspx/geral/ResultadoBusca.aspx?PalavraChave={2}", document.domain, $Servidor, $Get(objeto).value);
    window.location.href = String.Format("{0}aspx/geral/ResultadoBusca.aspx?PalavraChave={1}", page.ResolveUrl('~/'), $Get(objeto).value);
}

App.LoadConsultorOnline = function(top)
{
    page.FindControl(ConsultorOnlineControl).Load();
    $Get(ConsultorOnlineControl).style.display = 'none';
    setTimeout("App.LoadConsultorOnlineTimeOut("+top+")", 100);
}

App.LoadConsultorOnlineTimeOut = function(top) {
    if ($Get('imgLogoConsultor') == null) {
        setTimeout("App.LoadConsultorOnline();", 300);
        return false;
    }
    if (top == null || top == "") top = 350;
    $Get('imgLogoConsultor').src = page.ResolveUrl("~/Images/Geral/logo_stb_p.gif");
    $Get('imgbtXConsultor').src = page.ResolveUrl("~/Images/Geral/bt_x.gif");
    $Get('imgEnviarConsultor').src = page.ResolveUrl("~/Images/Geral/bt_enviar.gif");
    App.CentralizaControleInvisivel($Get(ConsultorOnlineControl), top);
    $Get(ConsultorOnlineControl).style.display = '';
}

App.LoadSuporteOnline = function(top)
{
    page.FindControl(SuporteOnlineControl).Load();
    $Get(SuporteOnlineControl).style.display = 'none';
    setTimeout("App.LoadSuporteOnlineTimeOut();", 300);
}

App.LoadSuporteOnlineTimeOut = function(top)
{
    if ($Get('imgLogoSuporte') == null)
    {
        setTimeout("App.LoadSuporteOnline();", 300);
        return false;
    }
    if (top == null || top == "") top = 350;
    $Get('imgLogoSuporte').src = page.ResolveUrl("~/Images/Geral/logo_stb_p.gif");
    $Get('imgbtXSuporte').src = page.ResolveUrl("~/Images/Geral/bt_x.gif");
    $Get('imgEnviarSuporte').src = page.ResolveUrl("~/Images/Geral/bt_enviar.gif");
    App.CentralizaControleInvisivel($Get(SuporteOnlineControl), top);
    $Get(SuporteOnlineControl).style.display = '';
}


App.LoadEnvieAmigo = function()
{
    page.FindControl(EnvieAmigoControl).Load();
    $Get('imgLogoEnvieAmigo').src = page.ResolveUrl("~/Images/Geral/logo_stb_p.gif");
    $Get('imgbtXEnvieAmigo').src = page.ResolveUrl("~/Images/Geral/bt_x.gif");
    $Get('imgEnviarAmigo').src = page.ResolveUrl("~/Images/Geral/bt_enviar.gif");
}

App.CentralizaControle = function(ctrl, topAlterado)
{
    ctrl.style.position = 'absolute';
    ctrl.style.zIndex = 30;
    var scrollTop = parseInt(document.documentElement.scrollTop) || parseInt(document.body.scrollTop);
    var top = Math.max(scrollTop, scrollTop + document.documentElement.clientHeight - (ctrl.clientHeight) - ((document.documentElement.clientHeight - ctrl.clientHeight) / 2));
    if (top <= 160) top = 165;
    ctrl.style.top = (topAlterado != null ? topAlterado : top) + 'px';
    ctrl.style.left = (document.documentElement.scrollLeft + (document.documentElement.clientWidth / 2) - (ctrl.clientWidth / 2)) + 'px';
}

App.ValidaEmailEnviarParaUmAmigo = function()
{
    if ($Get('txtNomeEnviaAmigo').value == "" || $Get('txtNomeEnviaAmigo').value == "Preencha seu nome")
    {
        alert('O campo Nome é obrigatório, por favor digite-o.');
        $Get('txtNomeEnviaAmigo').focus();
        return false;
    }

    if (!Validator.IsEmail($Get('txtEmailEnviaAmigo').value))
    {
        alert('O campo Email é inválido');
        $Get('txtEmailEnviaAmigo').focus();
        return false;
    }

    if ($Get('txtNomeAmigoEnviaAmigo').value == "" || $Get('txtNomeAmigoEnviaAmigo').value == "Preencha o nome do amigo")
    {
        alert('O campo Nome do amigo é obrigatório, , por favor digite-o.');
        $Get('txtNomeAmigoEnviaAmigo').focus();
        return false;
    }

    if (!Validator.IsEmail($Get('txtEmailAmigoEnviaAmigo').value))
    {
        alert('O campo Email do amigo é inválido');
        $Get('txtEmailAmigoEnviaAmigo').focus();
        return false;
    }

    return true;
}

App.EnviaEmailEnviarParaUmAmigo = function()
{
    if (!App.ValidaEmailEnviarParaUmAmigo())
        return false;

    $Get('divEnvieAmigoBoxPadrao').style.display = 'none';

    Ajax.Email.EnviarParaUmAmigo($Get('txtNomeEnviaAmigo').value,
        $Get('txtEmailEnviaAmigo').value,
        $Get('txtNomeAmigoEnviaAmigo').value,
        $Get('txtEmailAmigoEnviaAmigo').value,
        $Get('txtMensagemEnviaAmigo').value,
        document.location.href,
        App.EnviaEmailEnviarParaUmAmigo_End)

    return false;
}

App.EnviaEmailEnviarParaUmAmigo_End = function(rt)
{
    if (rt.Sucesso)
    {

    }
}

App.ImprimeForm = function(titulo)
{
    var resultado = new App.URLOpen(page.ResolveUrl("~/aspx/Servicos/DocVistosImprime.aspx"),"Imprimir: " + titulo,"width=600,height=400,scrollbars=NO,location=NO, resizable=NO");
    resultado.Add('Titulo', titulo);
    resultado.Add('Endereco', $Get('txtEndereco').value);
    resultado.Add('Hotel', $Get('txtHotel').value);
    resultado.Add('Cidade', $Get('txtCidade').value);
    resultado.Add('Estado', $Get('txtEstado').value);
    resultado.Add('CepZip', $Get('txtCep').value);
    resultado.Open();
}

function FormatarData(textBox, evento)
{
    var mascara = "##/##/####";
    var key;

    if (evento)
        key = parseInt(evento.which || evento.charCode || evento.keyCode);

    if ((key >= 48 && key <= 57) || (key >= 96 && key <= 105))
    {
        var caracter = mascara.substring(textBox.value.length, textBox.value.length + 1);

        if (caracter != mascara.substring(0, 1))
            textBox.value += caracter;

        return true;
    }
    else if ((key >= 37 && key <= 40) || key == 8 || key == 9 || key == 46)
    {
        return true;
    }
    else
    {
        return false;
    }
}
function GetPosition(e)
{
    var left = 0;
    var top = 0;

    while (e.offsetParent)
    {
        left += e.offsetLeft;
        top += e.offsetTop;
        e = e.offsetParent;
    }

    left += e.offsetLeft;
    top += e.offsetTop;

    return { x: left, y: top };
}

/*
var posicao = GetPosition($Get('divXpto'));
posicao.x
posicao.y
*/

function TextLimiter(field, maxlimit) 
{
    if (field.value.length > maxlimit)
        field.value = field.value.substring(0, maxlimit);
}
