// JavaScript Document

//global vars

var link;

var sizePage;

var defineTarget;

var returnGlobal;

var breakSub;

var escopoURL = "http://www.tellfree.com.br/";

var loopCount = 2;

var loopTotal = 4;

var loopLinks = Array(loopTotal);

var loopInter;

//********************************************************************************************

function setDisplayRespostas(p, el, t) {
    //comunicacoes unificadas

    for (var x = 1; x <= 43; x++) {
        if (document.getElementById("comunicacoes_unificadas_" + x.toString())) {
            document.getElementById("comunicacoes_unificadas_" + x.toString()).style.display = "none";
        }

        if (document.getElementById("telefoniaip_" + x.toString())) {
            document.getElementById("telefoniaip_" + x.toString()).style.display = "none";
        }

        if (document.getElementById("equipa_" + x.toString())) {
            document.getElementById("equipa_" + x.toString()).style.display = "none";
        }
    }

    if (t == 1)

        document.getElementById("telefoniaip_" + p.toString()).style.display = "block";

    if (t == 2)

        document.getElementById("equipa_" + p.toString()).style.display = "block";

    if (t == 3)

        document.getElementById("comunicacoes_unificadas_" + p.toString()).style.display = "block";

    $(document).ready

	(

		function () {
		    $(".moveRespostas").animate({ top: el }, 600);
		}

	);
}

//********************************************************************************************

function listarPop(id) {
    $(document).ready

	(

		function () {
		    var aParams = id.split("[split]");

		    var stype = "get";

		    var surl = "Mapa.aspx";

		    var params = "info=vendas.pops&idName=" + aParams[0] + "&id=" + aParams[1] + "&name=" + aParams[2];

		    $(".lista_pops").css("display", "block");

		    $("#listarPops").html("carregando contatos...");

		    $("#nameCidade").html(aParams[2]);

		    $.ajax

			(

				{
				    type: stype.toUpperCase(),

				    url: surl,

				    data: params,

				    success: function (data) {
				        $("#listarPops").html(data);
				    }
				}

			);
		}

	);
}

//********************************************************************************************

function Vendas(id) {
    $(".lista_pops").css("display", "none");

    if (id != 0) {
        $(".lista_vendas").html('<h2>Carregando cidades...</h2>');

        var stype = "get";

        var surl = "Mapa.aspx";

        var params = "info=vendas&id=" + id.toString();

        $.ajax

		(

			{
			    type: stype.toUpperCase(),

			    url: surl,

			    data: params,

			    success: function (data) {
			        $(".lista_vendas").html(data);
			    }
			}

		);
    }

    else {
        $(".lista_vendas").html('<h2>Selecione um estado</h2>');
    }
}

//$(document).ready(function() { Vendas(0); });

//********************************************************************************************

function windowPopUp(w, h, url) {
    window.open(url, 'meunome', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no,top=10,left=10,width=' + w + ',height=' + h + ',scrolling=no');
}

//********************************************************************************************

function setLinks(selected) {
    loopLinks[2] = "../Compra/ExchangeOnline.aspx";

    loopLinks[3] = "../Compra/OfficeCommunicator.aspx";

    loopLinks[4] = "../Compra/PabxIP.aspx";

    loopLinks[1] = "../Compra/TelefoniaIP.aspx";

    return loopLinks[selected];
}

//********************************************************************************************

function AlterSequenceImages(count) {
    loopCount = count;

    clearInterval(inter);

    showImageBanner();
}

//********************************************************************************************

function CreateSeguenceImages() {
    var escopo = document.getElementById('sequenceImages');

    for (var s = 1; s <= loopTotal; s++) {
        var a = document.createElement("a");

        a.style.float = "left";

        a.style.marginRight = "5px";

        a.style.paddingLeft = "3px";

        a.style.paddingRight = "3px";

        a.style.paddingTop = "1px";

        a.style.paddingBottom = "0px";

        a.innerHTML = s;

        a.href = "javascript:AlterSequenceImages('" + s + "');";

        escopo.appendChild(a);
    }
}

//********************************************************************************************

function showImageBanner() {
    if (loopCount <= loopTotal) {
        $(".changeImage").hide();
        $('#changeLink').attr("href", setLinks(loopCount));
        $("#changeImage" + loopCount).fadeIn(300);
        loopCount++;
    }
    else {
        loopCount = 1;
    }
    $("#sequenceImages a").removeClass("bannerVigente");
    var numeroLink = loopCount - 1;
    $("#sequenceImages a:contains('" + numeroLink + "')").addClass("bannerVigente");
}

//********************************************************************************************

function SlideBanners() {
    CreateSeguenceImages();

    inter = setInterval("showImageBanner();", 5000);
}

//********************************************************************************************

function fillFooter() {
    var interURL = window.location.toString().split(".php");

    var endURL = interURL[0].split("/");

    var iniURL = interURL[0].substr(0, interURL[0].length - endURL[endURL.length - 1].length);

    document.getElementById("linkpageOutput").value = iniURL + "#" + endURL[endURL.length - 1] + interURL[1].toString();
}

//********************************************************************************************

function verifyPage(surl, stype, params) {
    $(document).ready(function () {
        $.ajax

		(

			{
			    type: stype.toUpperCase(),

			    url: surl,

			    data: params,

			    success: function (data) {
			        ((data == "existe") ? openPageFrame() : "");
			    }
			}

		);
    });
}

//********************************************************************************************

function requestURL() {
    var url = window.location.toString().split("#");

    if ((url[1] != "") && (url[1] != null)) {
        //page

        link = url[1];

        verifyPage("instructions.php", "get", "info=verify.page&page=" + link);
    }
}

//********************************************************************************************

function modifySizeH() {
    $(document).ready(function () {
        $("#contentRemote", parent.document).animate({ height: ($("#masterH").attr("scrollHeight") - 5) }, 600);

        $("#overflow", parent.document).css("display", "none");
    });
}

//********************************************************************************************

function openPageFrame() {
    var aLink = link.split("?");

    link = aLink.join(".php?");

    link = (link.indexOf("php") == -1 ? link + ".php" : link);

    $("#contentRemote").attr("src", link);
}

//********************************************************************************************

function initIframe() {
    $('.clickLink').click

	(

		function () {
		    //style

		    $('.contextMargin ul li span a').css('color', '#fff');

		    $('.contextMargin ul li span a').find('img').remove();

		    $('#menuText ul li a').css('color', '#999');

		    $('#subMenuUp ul li a').css('color', '#999');

		    //request

		    link = $(this).attr('href').replace("#", "");

		    sizePage = $(this).attr('sizePage');

		    defineTarget = $(this).attr('defineTarget');

		    breakSub = link;

		    var aLink = link.split("?");

		    link = aLink.join(".php?");

		    link = (link.indexOf("php") == -1 ? link + ".php" : link);

		    if (breakSub != "") {
		        $("#overflow").html("<blink>Carregando, por favor, aguarde....</blink>");

		        if (defineTarget == "parent") {
		            $("#contentRemote", parent.document).attr("src", link);

		            $("#overflow", parent.document).css("display", "block");

		            var protocol = parent.window.location.href;

		            protocol = protocol.split("#");

		            protocol = protocol[0].toString();

		            parent.window.location.href = protocol + "#";

		            parent.window.location.href = protocol + "#" + breakSub;
		        }

		        else {
		            $("#contentRemote").attr("src", link);

		            $("#overflow").css("display", "block");

		            window.location.href = "#";

		            window.location.href = $(this).attr('href');
		        }
		    }

		    switch (breakSub) {
		        case ("trabalhe_conosco"):

		            breakMenu = false;

		            breakOverMenu = true;

		            $(this).css('color', '#005782');

		            ShowHide();

		            return false;

		            break;

		        default:

		            $(this).css('color', '#666');

		            if (breakSub == "") {
		                breakMenu = false;

		                Menu(true, globalMenu, elsGlobal);
		            }

		            else {
		                switch (breakSub) {
		                    case ("tellfree_na_midia"):

		                    case ("releases"):

		                    case ("cadastro_jornalistas"):

		                    case ("contato_assessoria"):

		                    case ("eventos"):

		                    case ("suporte_tecnico"):

		                    case ("vendas"):

		                    case ("sobre_a_tellfree"):

		                    case ("sac"):

		                    case ("diferenciais"):

		                    case ("operadoras"):

		                    case ("fotos"):

		                    case ("missao_visao_valores"):

		                    case ("inicio"):

		                        breakMenu = false;

		                        return false;

		                        break;

		                    case ("business_mail"): /*nothing*/break;

		                    case ("chat_corporativo"): /*nothing*/break;
		                }
		            }

		            break;
		    }

		    breakMenu = true;

		    breakOverMenu = true;

		    //$(this).css('color','#005782');

		    /*

		    if(breakSub != "trabalhe_conosco")

		    {
		    $(this).css('color','#666');

		    $(this).append('<img src="/Tellfree/images/overSubMenu.png" class="overSubMenu">');

		    breakMenu = false;

		    Menu(true, globalMenu, elsGlobal);
		    }

		    else

		    {
		    ShowHide();
		    }*/
		}

	);
}

//$(document).ready(function() { initIframe(); });

//********************************************************************************************

function Fotos() {
    $('.clickFotos').click

	(

		function () {
		    document.getElementById("imagem_selecionada").value = $(this).attr('href').replace("#", "");

		    $("#baixarDownload").css("display", "block");
		}

	);
}

//$(document).ready(function() { Fotos(); });

//********************************************************************************************

function _setQS(qs) {
    var querystr = new Array();

    loc = window.location.search.substr(1).split('&');

    if ((loc != "") && (loc != null)) {
        for (var icnt = 0; icnt < loc.length; icnt++) {
            var q = loc[icnt].split('=');

            querystr[q[0]] = q[1];
        }

        return querystr[qs];
    }

    else {
        return (null);
    }
}

//********************************************************************************************

function array_reverse(array, preserve_keys) {
    var arr_len = array.length,

		newkey = 0,

		tmp_arr = {},

		key = '';

    preserve_keys = !!preserve_keys;

    for (key in array) {
        newkey = arr_len - key - 1;

        tmp_arr[preserve_keys ? key : newkey] = array[key];
    }

    return tmp_arr;
}

//********************************************************************************************

function CalcularValorTotal(nomeVlTotal, nomeValorUnitario, campoQuantidade) {
    var trial = false;

    if (document.getElementById('isTrial') != undefined) {
        if (document.getElementById('isTrial').value == "true") {
            trial = true
        }
    }
    var campoVlTotal = document.getElementById(nomeVlTotal);
    if (!trial) {
        var campoValorUnitario = document.getElementById(nomeValorUnitario);
        if (campoQuantidade.value > parseFloat("0")) {
            if (campoValorUnitario.value != undefined)
                campoVlTotal.innerHTML = "R$ " + roundNumber(parseFloat(campoValorUnitario.value.replace(",", ".").trim().replace("R$", "")) * parseFloat(campoQuantidade.value.replace(",", ".").trim().replace("R$", "")), 2).toString().replace(".", ",")
            else
                campoVlTotal.innerHTML = "R$ " + roundNumber(parseFloat(campoValorUnitario.innerHTML.replace(",", ".").trim().replace("R$", "")) * parseFloat(campoQuantidade.value.replace(",", ".").trim().replace("R$", "")), 2).toString().replace(".", ",")

            ajustaDecimal(campoVlTotal);
        }
        else {
            campoVlTotal.innerHTML = " R$ 0,00";
        }
    }
    else
        campoVlTotal.innerHTML = " R$ 0,00";
}

function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

function ValidarQuantidadeCompra(nomeCampoQuantidade) {
    var campoQuantidade = document.getElementById(nomeCampoQuantidade);
    if (campoQuantidade.value == "0") {
        MostrarMensagem('Informe a quantidade do produto');
        return false;
    }
    return true;
}

function ValidarQuantidadeCompraTrial(nomeCampoQuantidade) {
    var campoQuantidade = document.getElementById(nomeCampoQuantidade);

    var quantidadeValidade = ValidarQuantidadeCompra(nomeCampoQuantidade);

    if (quantidadeValidade) {
        if (campoQuantidade.value > parseInt("20")) {
            MostrarMensagem('O limite de licenças em caráter de experimentação é de 20 unidades. Favor rever a quantidade informada.');
            return false;
        }
    }
    else
        return false;

    return true;
}

function ValidarZero(campo, valor) {
    if (valor == 0)
        campo.value = 1;
}

function ValidarTermo() {
    if (document.getElementById('CheckBoxTermo').checked == true)
        return true;
    else {
        MostrarMensagem("&#201; necess&#225;rio aceitar o termo de ades&#227;o.");
    }

    return false;
}

// func de tooltip
function tooltipbotao(id) {
    $("#" + id).easyTooltip({
        xOffset: 5,
        yOffset: 5
    });
}

//func de acordeon
$(function () {
    $('.acord').accordion({
        autoheight: false
    });
});

function ajustaDecimal(campoTotal) {
    var ponto = campoTotal.innerHTML.indexOf(",");

    if (campoTotal.innerHTML.substr(ponto).length == 2)
        campoTotal.innerHTML += "0";

    if (campoTotal.innerHTML.substr(ponto).length == 1)
        campoTotal.innerHTML += ",00";
    else if (ponto == -1)
        campoTotal.innerHTML += ",00";
}

function LimparQuantidadesModulos(selecionado, txt1, txt2, txt3, vl1, vl2) {
    if (selecionado.id == txt1) {
        document.getElementById(txt2).value = "0";
        document.getElementById(txt3).value = "0";
        document.getElementById(vl1).innerHTML = " R$ 0,00";
        document.getElementById(vl2).innerHTML = " R$ 0,00";
    }
}

function arrumaEnterBotao(field, event, botao, focar) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

    if (keyCode == 13 || keyCode == undefined) {
        if (focar)
            botao.focus();

        return false;
    }
    else {
        return true;
    }
}

function arrumaEnter(field, event) {
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;

    if (keyCode == 13) {
        var i;
        for (i = 0; i < field.form.elements.length; i++)
            if (field == field.form.elements[i])
                break;

    i = (i + 1) % field.form.elements.length;
    field.form.elements[i].focus();
    return false;
}
else {
    return true;
}
}

function CopiarCampo(Origem, Destino, isCopiar) {
    if (isCopiar) {
        document.getElementById(Destino).value = document.getElementById(Origem).value;
    }
}

function CopiarContato(Origem) {
    if (document.getElementById("chkCopiar").checked) {
        if (Origem == "Comercial") {
            document.getElementById("txtNomeTecnico").value = document.getElementById("txtNomeContatoCom").value;
            document.getElementById("txtDDDTecnico").value = document.getElementById("txtDDDContato").value;
            document.getElementById("txtTelefoneTecnico").value = document.getElementById("txtTelefoneContato").value;
            document.getElementById("txtEmailTecnico").value = document.getElementById("txtEmailContato").value;

            document.getElementById("txtNomeTecnico").disabled = true;
            document.getElementById("txtDDDTecnico").disabled = true;
            document.getElementById("txtTelefoneTecnico").disabled = true;
            document.getElementById("txtEmailTecnico").disabled = true;
        }
        else {
            document.getElementById("txtNomeContatoCom").value = document.getElementById("txtNomeTecnico").value;
            document.getElementById("txtDDDContato").value = document.getElementById("txtDDDTecnico").value;
            document.getElementById("txtTelefoneContato").value = document.getElementById("txtTelefoneTecnico").value;
            document.getElementById("txtEmailContato").value = document.getElementById("txtEmailTecnico").value;
        }
    }
    else {
        document.getElementById("txtNomeTecnico").disabled = false;
        document.getElementById("txtDDDTecnico").disabled = false;
        document.getElementById("txtTelefoneTecnico").disabled = false;
        document.getElementById("txtEmailTecnico").disabled = false;
    }
}

//chamar modal
$('.teste_de_banda').live('click', function () {
    var htmlModal = "<h1>Teste de banda</h1>";
    htmlModal += "<div id='modal_teste_conteudo' style='magin:10px;'>";
    htmlModal += "<p style='margin:10px;'>Para que a telefonia IP tenha qualidade perfeita, sua conexão deverá garantir, no mínimo, 30k de upload e download por canal de voz.</p>";
    htmlModal += "<div>";
    htmlModal += "<iframe id='frameTesteBanda' src='/plugins/BandwidthTest.html' runat='server' width='100%' height='504px' frameborder='0' scrolling='no'></iframe>";
    htmlModal += "</div>";
    htmlModal += "</div>";

    $("#modal_teste").html(htmlModal);
    $('#modal_teste').modal();
    $('#modal_teste_conteudo').show();
    $('.simplemodal-container').css('height', 'auto');
    $('.simplemodal-container').css('width', '550px');
    $('.simplemodal-container').css('top', '170px');
});

$(document).ready
