﻿// JavaScript Document
$(document).ready(function() {
    /*
    $('.mouseenter').mouseenter(function(){
    if ( $(this).find('.ul_list').css('display') == 'none'){
    $(this).find('.ul_list').slideDown('slow');
    } else {
    $(this).find('.ul_list').slideUp('slow');
    }
    });
    $('.mouseenter').mouseleave(function(){
    $(this).find('.ul_list').slideUp('slow');
    });
    */
	
	// recicle - ie precida de um id pra funcionar o flash.
	$('.mapRecicle').find('object').attr('id','flashMapa-chamajs');

    try {
        $('#div_detalhe_produto_new').parent().find("div").css("padding", "0px");

        var bloco1 = $('#div_detalhe_produto_new').parent().parent().parent().find("div.destaquesInferior").html();
        var bloco2 = $('#div_detalhe_produto_new').parent().parent().parent().find("div.rodape").html();

        var htmlbloco1 = $("<div></div>").addClass("destaquesInferior").html(bloco1);
        var htmlbloco2 = $("<div></div>").addClass("rodape").html(bloco2);

        $(".txtInstitucional div.destaquesInferior").remove();
        $(".txtInstitucional div.rodape").remove();


        if ($.browser.msie) {
            $('#div_detalhe_produto_new').parent().parent().parent().after(htmlbloco1).after(htmlbloco2);
        }
        else {
            $('#div_detalhe_produto_new').parent().parent().parent().after(htmlbloco2).after(htmlbloco1);
        }



        //$('#div_detalhe_produto_new').parent().parent().parent().after(htmlbloco1);

        //$('#div_detalhe_produto_new').parent().find(".disclaimers div").css("position","static");



    }
    catch (e) {

    }


    var mudarlogo = $('#div_detalhe_produto_new').length > 0;

    if (mudarlogo) {
        $('.disclaimers div ').css("position", "static");
    }

    $(".h2_titulo_sessao").css("margin-top", "0px");

    $(".navModelos a[name=anterior], .navModelos a:contains(1)").click(function(e) {
        e.preventDefault();
        $("#tab2").hide();
        $("#tab1").show();

        $(".navModelos a:contains(2)").removeClass("desativado");
        $(".navModelos a:contains(1)").addClass("desativado");

        $(".navModelos a[name=anterior]").addClass("desativado");
        $(".navModelos a[name=proximo]").removeClass("desativado");
    });

    $(".navModelos a[name=proximo], .navModelos a:contains(2)").click(function(e) {

        e.preventDefault();

        $("#tab2").show();
        $("#tab1").hide();

        $(".navModelos a:contains(2)").addClass("desativado");
        $(".navModelos a:contains(1)").removeClass("desativado");

        $(".navModelos a[name=anterior]").removeClass("desativado");
        $(".navModelos a[name=proximo]").addClass("desativado");

    });



    document.originalTitle = document.title;
    setInterval(function() {
        document.title = document.originalTitle;
    }, 1000)

    $("#cidadesSinalDigital .listasSinalDigital ul li:nth-child(odd)").addClass("itemListaOdd");

    $('.lista_produtos').each(function(x) {
        $(this).css("visibility", "visible");
        $(this).css("margin-left", ((1002 / 2) - ($(this).width() / 2)));
    });

    // toshibaFAQ - ACCORDION
    $("#toshibaFAQ").accordion({
        header: "h3",
        autoHeight: false,
        active: false
    });


    $('.div_produtos p span a').hover(function() {
        $('img', this).animate({
            width: "130px",
            height: "89px",
            top: '0px',
            left: '0px'
        }, 500);
    },
	function() {
	    $('img', this).animate({
	        width: "91px",
	        height: "62px",
	        top: '13px',
	        left: '20px'
	    }, 500);
	})

    $('.btn_limpar').click(function() {
        pageTracker._trackEvent('Botão', 'Clique_trabalhe_conosco', '', 'limpar');
    });

    $('btn_enviar2').click(function() {
        pageTracker._trackEvent('Botão', 'Clique_trabalhe_conosco', '', 'enviar');
    });

    // Lightbox Eventos
    $('.eventos .descricao .fotos ul li a').lightBox();

    $('.glossario ul').equalHeights();



    //$('.tbCompare tbody tr:nth-child(even)').find('td').addClass('par');


    //$('.tbCompare tbody tr td')
    //$('.tbCompare tbody tr:odd').addClass('par');



    /* SELECT DO SERVIÇO A CONSUMIDOR - MANUAIS */
    /* DESENVOLVER: DANILO SOARES dsoares@tv1.com.br */

    /*============ */

    var htmlSelect = '';
    htmlSelect += '<select class="selectProduto" style="border:1px solid #ccc;">';
    htmlSelect += '<option value="0" >Selecione um Produto</option>';

    //htmlSelect += '<option value="1">Televisores LCD e LED</option>';
    //htmlSelect += '<option value="2">Televisores CRT</option>';
    //htmlSelect += '<option value="3">Conversores Digitais</option>';
    //htmlSelect += '<option value="4">DVDs players e Home Theaters</option>';
    //htmlSelect += '<option value="5">Aparelhos da linha de áudio</option>';
    //htmlSelect += '<option value="6">Telefones</option>';

    var qtd = 0;
    $(".div_lojas ul li.item_1").each(function() {
        qtd++;
        htmlSelect += '<option value="' + qtd + '">' + $(this).text() + '</option>';

    });


    htmlSelect += '</select> <select class="selectModelo" style="display:none; border:1px solid #ccc;">';
    htmlSelect += '<option value="Selecione um Modelo">Selecione um Modelo</option>';
    htmlSelect += '</select>';


    $(".divSelectProduto").empty();
    $(".liResult").empty();
    $(".divSelectProduto").html(htmlSelect);

    // ESCOLHE PRODUTO
    $(".selectProduto").change(function() {

        var produto = $(this).val();


        if (produto > 0) {
            $(".selectModelo").show();
            $(".selectModelo").empty();
            var contbloco = produto - 1;

            var textoProduto = $(".div_lojas ul li.item_1:eq(" + contbloco + ")").text();


            var html = '<option>Selecione um Modelo</option>';

            $(".div_lojas ul li.item_1:eq(" + contbloco + ")").parent().find('a').each(function() {
                var texto = $(this).text();
                html += '<option value="' + texto + '">' + texto + '</option>';
            });


            $(".selectModelo").append(html);

            $(".selectModelo").change(function() {

                var modeloEscolhido = $(this).val();
                var htmlModelo = '';

                if (modeloEscolhido != "Selecione um Modelo") {
                    $(".liResult").empty();

                    $(".div_lojas ul li a").each(function() {
                        if ($(this).text() == modeloEscolhido) {
                            htmlModelo = $(this).parent().html();
                        }
                    });

                    $(".liResult").html(htmlModelo);

                }

            });


        }
        else {
            $(".selectModelo").hide();
            $(".liResult").empty();
        }

    });

    /*============ END */


    /*------ mega garantia -----*/
    $('.serieMask').blur(function() {
        ConsultaServicoModelo($('.serieMask').val());
    });

    $('.remover_espaco').blur(function() {
        $('.remover_espaco').val($('.remover_espaco').val().replace(/\s/g, ""));
    });


});

/*-------------------------------------------------------------------- 
* JQuery Plugin: "EqualHeights"
* by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
*
* Copyright (c) 2008 Filament Group
* Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
*
* Description: Compares the heights or widths of the top-level children of a provided element 
and sets their min-height to the tallest height (or width to widest width). Sets in em units 
by default if pxToEm() method is available.
* Dependencies: jQuery library, pxToEm method	(article: 
http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)							  
* Usage Example: $(element).equalHeights();
Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
* Version: 2.0, 08.01.2008
--------------------------------------------------------------------*/

$.fn.equalHeights = function(px) {
    $(this).each(function() {
        var currentTallest = 0;
        $(this).children().each(function(i) {
            if ($(this).height() > currentTallest) { currentTallest = $(this).height() + 1; }
        });
        //if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
        // for ie6, set height since min-height isn't supported
        if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({ 'height': currentTallest }); }
        $(this).children().css({ 'min-height': currentTallest });
    });
    return this;
};

function trocarConteudo(id, total) {
    var objLi = $("#item_" + id);
    var objcont = $("#cont_" + id);

    for (var i = 1; i <= total; i++) {
        $("#item_" + i).removeClass("li_active");
        $("#cont_" + i).css("display", "none");
    }

    objLi.addClass("li_active");
    objcont.css("display", "inline");
    if (id != 1) {
        $("#menusessao").css("display", "none");
    }
    else {
        $("#menusessao").css("display", "inline");
    }
}

function mostraSubConteudo(id, total) {
    var objLi = $("#link_" + id);
    var objcont = $("#box_" + id);

    for (var i = 1; i <= total; i++) {
        $("#link_" + i).removeClass("ativo");
        $("#box_" + i).css("display", "none");
    }

    objLi.addClass("ativo");
    objcont.css("display", "inline");
}


//LightBox
$(document).ready(function() {



    /* EVENTO DE ABRIR O LIGHTBOX */
    $('.lista_produtos a, .div_box_tipoCeltvSti a, .div_box_tipoDestaque a').click(function() {

        var urlItem = $(this).attr("href");
        var urlTarget = $(this).attr("target");
        var classItem = $(this).attr("class");

        if (classItem != "ExibirLightBox") {
            urlTarget = "MesmaJanela";
        }

        if ((urlTarget == "LightBox") || (urlTarget == "")) {
            startLightBox(urlItem);
        }

        else if (urlTarget == "MesmaJanela") {
            window.open(urlItem, '_self');
        }

        else {
            window.open(urlItem, '_blank');
        }


        return false;
    });


    $('.lightbox').click(function() {
        fecharLightBox();
    });
});
var lastlightboxopenhrl;
var bodyheight = 0;
function startLightBox(urlProduto) {
    lastlightboxopenhrl = urlProduto;
    $('.lightbox').animate({ height: $(document).height() }, 0);
    $('.alinhamento').fadeOut(1000);
    bodyheight = $(document).height();
    abrirCarregando();


    /*$.ajax({
    type: "POST",
    url: urlProduto,
    success: function(msg){
		 
    $('.alinhamento').html(msg);
    abrirLightBox();
    }
    });
    */
    //alert(urlProduto);
    /* CARREGA NA DIV .alinhamento, O CONTEUDO */

    $('.alinhamento').load(urlProduto + " #detalheProduto", abrirLightBox);
    /*  UTILIZADO PARA SUBIR O SCROLL DA PÁGINA PARA O TOPO */
    window.scroll(0, 0);
}

function abrirCarregando() {
    /* APLICA A OPACIDADE NA DIV, PARA VALIDAR NO W3C */
    $('.lightbox').animate({ opacity: '0.5' }, 0);

    /* APLICA A ALTURA NO LIGHTBOX */
    $('.lightbox').fadeIn(1000, function() {
        $("body, .lightbox").height($(document).height());
        var alturaContainer = $('body').height();
        $('.lightbox').animate({ height: alturaContainer }, 0);
    });

    /* MOSTRA A DIV CARREGANDO */
    $('.carregando').css('display', 'block').fadeIn(1000);

    var browser = navigator.appName;
    var b_version = navigator.appVersion;
    b_version = b_version.substring(22, 23);

    if (browser.indexOf("Microsoft Internet Explorer") !== -1 && b_version == 6) {
        $("select").css("visibility", "hidden");
    }
}
function abrirLightBox() {
    /* ESCONDE A DIV CARREGANDO */
    $('.carregando').fadeOut(1000);

    /* APLICA A OPACIDADE NA DIV, PARA VALIDAR NO W3C */
    $('.lightbox').animate({ opacity: '0.5' }, 0);

    /* APLICA A ALTURA NO LIGHTBOX */
    $('.lightbox').fadeIn(1000, function() {
        $("body, .lightbox").height($(document).height());
        var alturaContainer = $(document).height();
        $('.lightbox').animate({ height: alturaContainer }, 0);
        addListenerInTollTips();
    });

    $('.alinhamento').fadeIn(1000, function() {
        $("body, .lightbox").height($(document).height());
        var alturaContainer = $(document).height();
        if (bodyheight + 40 < alturaContainer) {
            $('.lightbox').animate({ height: alturaContainer + 40 }, 0);
        } else {
            $('.lightbox').animate({ height: alturaContainer }, 0);
        }


    });

    var browser = navigator.appName;
    var b_version = navigator.appVersion;
    b_version = b_version.substring(22, 23);

    if (browser.indexOf("Microsoft Internet Explorer") !== -1 && b_version == 6) {
        $("select").css("visibility", "hidden");
    }


    $('.tbCompare tbody tr:nth-child(even)').addClass('par');


    stickytooltip.init("*[alt=sticky1]", "mystickytooltip");


}


/* EVENTO DE FECHAR O LIGHTBOX */
function fecharLightBox() {
    $('#autentico').hide();
    $('.alinhamento').fadeOut('slow');
    $('.lightbox').fadeOut('slow');

    var browser = navigator.appName;
    var b_version = navigator.appVersion;
    if (browser.indexOf("Microsoft Internet Explorer") !== -1 && b_version == 6) {
        $("select").css("visibility", "visible");
    }
    $("body").height("");
    return false;
}



function imprimirLightBox() {
    winPrint = window.open(lastlightboxopenhrl, "Print", "width=20,height=20,scrollbars=no");
    if (winPrint.focus) { window.focus() }
    if (winPrint.attachEvent) {
        setTimeout("winPrint.print()", 3000);
        setTimeout("winPrint.close()", 6000);
        /*
        winPrint.attachEvent('onload',function(){
        winPrint.print();
        if (winPrint.focus) {winPrint.opener.focus()}
        winPrint.close();
        });
        */
    }
    else {
        winPrint.onload = function() {
            winPrint.print();
            if (winPrint.focus) { winPrint.opener.focus() }
            winPrint.close();
        }
    }
}

document.tooltipAutentico = false;
function addListenerInTollTips() {



    $('.lista_modelos dl dt').prev().prev().css('border', 'none');
    $('.lista_modelos dl dd:last').css('border', 'none');

    $('.recomendados ul li:last').css('border', 'none');



    $('#autentico').prependTo($('body'), 'top');
    $('#image_display').prependTo($('body'), 'top');

    $('.especificacoes ul li:contains("Windows")').each(function() {
        var b = this.innerHTML.replace(/ Aut(.*)ntico /gi, ' <a href="#autentico">Aut&ecirc;ntico</a> ');
        b = b.replace(/ Aut(.*)ntico /gi, ' <a href="#autentico">Aut&ecirc;ntico</a> ');
        b = b.replace(/ Aut(.*)ntico/gi, ' <a href="#autentico">Aut&ecirc;ntico</a>');
        b = b.replace(/ Aut(.*)ntico/gi, ' <a href="#autentico">Aut&ecirc;ntico</a>');
        b = b.replace(/Aut(.*)ntico /gi, '<a href="#autentico">Aut&ecirc;ntico</a> ');
        b = b.replace(/Aut(.*)ntico /gi, '<a href="#autentico">Aut&ecirc;ntico</a> ');
        b = b.replace(/<span>Aut(.*)ntico/gi, '<span><a href="#autentico">Aut&ecirc;ntico</a>');
        b = b.replace(/<span>Aut(.*)ntico/gi, '<span><a href="#autentico">Aut&ecirc;ntico</a>');
        b = b.replace(/<span> Aut(.*)ntico/gi, ' <span><a href="#autentico">Aut&ecirc;ntico</a>');
        b = b.replace(/<span> Aut(.*)ntico/gi, ' <span><a href="#autentico">Aut&ecirc;ntico</a>');
        this.innerHTML = b;
    });

    setTimeout(function() {
        $('a[href$=autentico]').click(function(e) {

            ttop = ((e.clientY + $(window).scrollTop()) - $('#autentico').height()) + 15;
            lleft = (e.clientX + 25);

            if ((lleft + $('#autentico').width()) >= $(document.body).width()) {
                lleft = ($(document.body).width() - $('#autentico').width()) - 10;
            }

            $('#autentico').css('top', ttop + 'px');
            $('#autentico').css('left', lleft + 'px');


            $('#autentico').css('display', 'block');
            $('.close', '#autentico').click(function() {
                $('#autentico').css('display', 'none');
            });
            return false;
        }).hover(
			function(e) {
			    ttop = ((e.clientY + $(window).scrollTop()) - $('#autentico').height()) + 15;
			    lleft = (e.clientX + 25);

			    if ((lleft + $('#autentico').width()) >= $(document.body).width()) {
			        lleft = ($(document.body).width() - $('#autentico').width()) - 10;
			    }

			    $('#autentico').css('top', ttop + 'px');
			    $('#autentico').css('left', lleft + 'px');


			    $('#autentico').css('display', 'block');

			    $('#autentico').click(
					function() {
					    $('#autentico').css('display', 'none');
					}
				).hover(
					function() {
					    //clearTimeout(document.tooltipAutentico);
					},
					function() {
					    $('#autentico').css('display', 'none');
					}
				);
			    return false;
			},
			function() {
			    //document.tooltipAutentico = setTimeout(function(){
			    //	$('#autentico').css('display','none');
			    //},6000);
			}
		);
    }, 200);

    var tooltip_image_time = false;
    $('.recomendados ul li a').click(function() { return false; });
    $('.recomendados ul li a').hover(
		function(e) {
		    clearTimeout(tooltip_image_time);
		    $(this).addClass('hover');

		    $('img', '#image_display').attr('src', $(this).attr('rel'));

		    pos = $(this).offset();
		    ttop = (pos.top - $('#image_display').height());
		    lleft = (pos.left - 34);

		    if ((lleft + $('#image_display').width()) >= $(document.body).width()) {
		        lleft = ($(document.body).width() - $('#image_display').width()) - 10;
		    }

		    $('#image_display').css('top', ttop + 'px');
		    $('#image_display').css('left', lleft + 'px');


		    $('#image_display').css('display', 'block');
		},
		function() {
		    $(this).removeClass('hover');
		    tooltip_image_time = setTimeout(function() {
		        $('#image_display').css('display', 'none');
		    }, 500);
		}
	);
}

function CarregarDadosLoja(urlRedirect, height)
{ 
  var width = "100%";
  var height = height;

  var style = "width: " + width + "; height:" + height + ";";

  $("#ifDetalheProdutoLoja").attr("src", urlRedirect);
  $("#ifDetalheProdutoLoja").attr("style", style);
}


function ConsultaServicoCEP(txtCep, txtEndereco, txtCidade, ddlEstado ) {

    p_Cep = $('.' + txtCep).val(); 
   
    //alert('Entrei');
    $.ajax({
        type: "GET",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        url: "/consultacep?cep=" + p_Cep,
        cache: false,
        success: function(data) {
            var xml;

            if (typeof data == "string" && $.browser.msie) {
                xml = new ActiveXObject("Microsoft.XMLDOM");
                xml.async = false;
                xml.loadXML(data);
            } else {
                xml = data;
            }

            xmlObj = xml
            $('.' + txtEndereco).val($(xmlObj).find("Endereco").text());
            $('.' + txtCidade).val($(xmlObj).find("Cidade").text());

            var estado = $(xmlObj).find("Estado").text()
            $('.' + ddlEstado + ' option').each(function() {
                if ($(this).val().toLowerCase() == estado.toLowerCase()) {
                    $(this).attr("selected", true);
                }
            });

            //$('.' + Estado).val($(xmlObj).find("Estado").text());

        }
    }); 
}


function ConsultaServicoModelo(txtSerie) {

    if (txtSerie.length == 20) {
        txtSerie = jQuery.trim(txtSerie).substring(0, 6);

        $.get("/consultamodelo?codigo=" + txtSerie, function(response) {
            if (response == "") {
                if ($('span#erro_consulta_modelo').length == 0) {
                    $('input[id$="txtNumeroSerie"]').after('<span id="erro_consulta_modelo" style="color:Red;">N° de série inválido</span>');
                }
                $('.modelo_aparelho').val('');
            }
            else {
                $('.modelo_aparelho').val(response);
                $('span#erro_consulta_modelo').remove();
            }

            //se exister error de modelo nao inserido, remover
            if ($('span[id$="rfvModelo"]').length != 0) {
                $('span[id$="rfvModelo"]').remove();
            }

            //se exister error de numero de serie nao inserido, remover
            if ($('span[id$="rfvNumeroSerie"]').length != 0) {
                $('span[id$="rfvNumeroSerie"]').remove();
            }
        });
    }
    else {
        $('.modelo_aparelho').val('');
    }
}

function CarregaCEPCliente(xmlObj) {
   
    xxx = $(xmlObj).find("Endereco").text();
    alert(xxx);
   
}

function trocaEstado(estado)
{
	$(".mapRecicle .div_lojas ul").hide();
	$(".mapRecicle .div_lojas ." + estado).show();
}

