// Função Popup: <a href="arquivo.ext" onclick="popup(this.href,'360','535','1'); return false;"></a>
function popup(url, w, h, s) {
    var oW = window.open(url, 'popup', 'width=' + w + ',height=' + h + ',directories=0,location=0,menubar=0,resizable=0,scrollbars=' + s + ',status=0,toolbar=0,marginleft=0,margintop=0,left=' + (((screen.availWidth - w) / 2) + -10) + ',top=' + (((screen.height - h) / 2) + -10));
}

// Funcionalidade no select do topo
$("#header select").change(function() {
    if ($(this).val() != "") {
        var url = $(this).val();
        url2 = url.split("/");

        if (url2[0] != "http:") {
            open("http://www.chevrolet.com.br/" + url);
        } else {
            open(url);
        }
    }
});

$("input").blur(function() {
    if ($(this).attr("alt") != "") {
        if ($(this).val() == "") {
            if ($(this).attr("class") == "inpSenha") {
                $(this).removeAttr("style");
            } else {
                $(this).attr("value", $(this).attr("alt"));
            }
        }
    }
});

// Impressão p/ páginas de Acessórios e Serviços
$(".btnImprimir, .btnImprimirOferta, .btnImprimirMapa").click(function() {
    popup($(this).attr("href"), "650", "750", "1");
    return false;
});

function openPopUpOfertaMaluca() {
    popup("../popup/default.aspx", "1070", "830", "1");
}

function abreBusca() {
    $(".boxProdutosBusca").show();
    return false;
}

function fechaBusca() {
    $(".boxProdutosBusca").hide();
    return false;
}

$(document).click(function() {
    $(".boxProdutosBusca").hide();
});

// Retira link do logo quando usuário está na Home
$(document).ready(function() {

    $("#ctl00_Conteudo_ImageButton1").live("click", function() {
        $("#ctl00_Conteudo_ImageButton1").parent().append("Enviando...");
        $("#ctl00_Conteudo_ImageButton1").css('display', 'none');
    });

    var endereco = document.URL;
    endereco = endereco.split("home");
    if (endereco[1]) {
        $("#logo").attr("href", "javascript:;");
        $("#logo").addClass("semLink");
    }
});

// Abre e Fecha Modal
function abreModal() {
    if (($.browser.msie) && ($.browser.version == '6.0')) {
        var alturaBody = $(document).height() + "px";
        $(".bgrModal").css("height", alturaBody);
    }
    $(".bgrModal").fadeIn("last");
}

// Apaga e põe conteúdo nos inputs
$(document).ready(function() {
    if ($(".inpSenha").val() != "") {
        $(".inpSenha").css("background-image", "none");
        $(".inpSenha").css("background", "#FFFFFF");
    }
});

$("input").focus(function() {
    if ($(this).attr("alt") != "") {
        if ($(this).val() == "" || $(this).val() == $(this).attr("alt")) {
            if ($(this).attr("class") == "inpSenha") {
                $(this).css("background-image", "none");
                $(this).css("background", "#FFFFFF");
            } else {
                $(this).attr("value", "");
            }
        }
    }
});

function pageLoad() {
    $(".btnSelecioneOferta").click(function() {
        $(this).addClass("btnSelecionada");
    });

    // Apaga e põe conteúdo nos inputs
    $(document).ready(function() {
        if ($(".inpSenha").val() != "") {
            $(".inpSenha").css("background-image", "none");
            $(".inpSenha").css("background", "#FFFFFF");
        }
    });

    $("input").focus(function() {
        if ($(this).attr("alt") != "") {
            if ($(this).val() == "" || $(this).val() == $(this).attr("alt")) {
                if ($(this).attr("class") == "inpSenha") {
                    $(this).css("background-image", "none");
                    $(this).css("background", "#FFFFFF");
                } else {
                    $(this).attr("value", "");
                }
            }
        }
    });

    // Após preencher o campo com o máximo permitido, passa o foco para o próximo campo
    $(".input_1").keypress(function() {
        var tamanho = $(this).attr("maxlength");
        var texto = $(this).val();

        if (($.browser.msie)) {
            if (texto.length == (tamanho)) {
                $(this).next().focus();
            }
        } else {
            if (texto.length == (tamanho - 1)) {
                $(this).next().focus();
            }
        }
    });

    if (($.browser.msie) && ($.browser.version == '6.0')) {
        var alturaBody = $(document).height() + "px";
        $(".bgrModal").css("height", alturaBody);
    }

    $(".btnFecharModal, .bgrModal").click(function() {
        fechaModal();
        $(".boxErro").hide();
        $(".boxSemResultado").hide();
        $(".divGridScroll, .boxConsultarCep table").hide();
    });

    //$(".cep_1").mask("99999");
    //$(".cep_2").mask("999");


}


function fechaModal() {
    $(".painel").hide();
    $(".boxSucesso").hide();
    $(".modal").fadeOut("last");
    $(".modal").removeAttr("style");
    $(".bgrModal").fadeOut("last");
    $(".jScrollPaneTrack, #painelRegulamento").hide();
}

$(document).keyup(function(event) {
    if (event.keyCode == "27") {
        fechaModal();
        $(".boxErro").hide();
        $(".boxSemResultado").hide();
        $(".divGridScroll, .boxConsultarCep table").hide();
        $(".jScrollPaneTrack, #painelRegulamento").hide();
    }
});


// Mensagens Modal
function sucesso(msg) {
    $(".boxErro").hide();
    $(".boxSucesso").html(msg);
    $(".boxSucesso").slideDown("last");
}

function abreErro(id, idExterno) {
    $(".boxSucesso").hide();
    setTimeout("abreErroTemp('" + id + "','" + idExterno + "')", 400);
    return false;
}

function abreErroTemp(id, idExterno) {

    if (document.getElementById(id).style.display != "none")
        $("#" + idExterno).slideDown("last");
    else
        $("#" + idExterno).hide();

    return false;
}

function abreErro2(msg, idDivErro) {
    $("#" + idDivErro).html(msg);
    $("#" + idDivErro).slideDown("last");
}

function consultaCep() {
    abreModal();
    $(".boxConsultarCep").animate({
        width: "460px",
        height: "155px"
    }, 200);
    setTimeout("$('.painel').show(); $('.boxConsultarCep').css('height', 'auto')", 500);
}


/*$(".boxConsultarCep .btn").click(function(){
// Se houver erros ou não houver registros...
//$(".boxErro").slideDown("last");
//$(".boxSemResultado").slideDown("last");
    
// Se vier resultado da Busca...
$(".divGridScroll, .boxConsultarCep table").show();
$(".boxConsultarCep").animate({ 
marginTop: "-210px"
}, 200);

});*/

// Seção - Eventos
$(".boxDadosEventos a").click(function() {
    abreModal();
    $(".boxModalLocalEvento").animate({
        width: "460px",
        height: "377px"
    }, 200);
    setTimeout("$('.painel').show(); $('.boxModalLocalEvento').css('height', 'auto')", 500);
});

$(".btnFecharModal, .bgrModal").click(function() {
    fechaModal();
    $(".boxErro").hide();
    $(".boxSucesso").hide();
    $(".boxSemResultado").hide();
    $(".divGridScroll, .boxConsultarCep table").hide();
});



function indiqueClick() {
    abreModal();
    $(".boxIndiqueAmigo").animate({
        width: "460px",
        height: "400px"
    }, 200);
    setTimeout("$('.painel').show(); $('.boxIndiqueAmigo').css('height', 'auto')", 500);
}

function abreMaisConcessionarias() {
    abreModal();
    $(".modalConcessionarias").show();
    $(".modalConcessionarias").animate({
        width: "860px",
        height: "387px"
    }, 200);
    setTimeout("$('.painel').show(); $('.modalConcessionarias').css('height', 'auto')", 500);
}

function receberOfertas() {
    abreModal();
    $(".boxRecebaOfertas").animate({
        width: "320px",
        height: "314px"
    }, 200);
    setTimeout("$('.boxRecebaOfertas .painel').show(); $('.boxRecebaOfertas').css('height', 'auto')", 500);
}

/*$(".boxSms .btn").click(function(){
$(".boxSucesso").hide();
$(".boxErro").html("Preencha corretamente o seu celular.");
$(".boxErro").slideDown("last");
$(".boxSms label, .boxSms input").addClass("erro");
$(".boxEmail label, .boxEmail input").removeClass("erro");
return false;

});*/

/*$("#widgets").click(function(){
abreModal();
$(".boxWidgets").animate({
width:"520px",
height:"270px"
}, 200);
setTimeout("$('.boxWidgets .painel').show(); $('.boxWidgets').css('height', 'auto')",500);  
});*/

function widgetClick() {
    abreModal();
    $(".boxWidgets").animate({
        width: "520px",
        height: "270px"
    }, 200);
    setTimeout("$('.boxWidgets .painel').show(); $('.boxWidgets').css('height', 'auto')", 500);
}


// Seção - Área de Vendas
$(".localizeConcessionaria, .modalConcessionarias .btnFecharModal").click(function() {
    if (($.browser.msie) && ($.browser.version == '6.0')) {
        if ($(this).attr("class") == "localizeConcessionaria") {
            $("select").hide();
        } else {
            $("select").show();
        }
    }

});

function marcaOfertaSelecionada() {
    $("#ctl00_Conteudo_lnkSelecionaItem").addClass("btnSelecionada");
}

// MASCARAS
function mascara(o, f) {
    v_obj = o;
    v_fun = f;
    setTimeout("execmascara()", 1);
}

function execmascara() {
    v_obj.value = v_fun(v_obj.value);
}

function soNumeros(v) {
    v = v.replace(/\D/g, "");
    return v;
}

function cep(v) {
    v = v.replace(/\D/g, "");                //Remove tudo o que não é dígito
    v = v.replace(/(\d{5})(\d)/, "$1-$2"); //Esse é tão fácil que não merece explicações
    return v;
}

function telefone(v) {
    v = v.replace(/\D/g, "");                 //Remove tudo o que não é dígito
    v = v.replace(/^(\d\d)(\d)/g, "($1) $2"); //Coloca parênteses em volta dos dois primeiros dígitos
    v = v.replace(/(\d{4})(\d)/, "$1-$2");    //Coloca hífen entre o quarto e o quinto dígitos
    return v;
}

function data(v) {
    v = v.replace(/\D/g, "");                    //Remove tudo o que não é dígito
    v = v.replace(/(\d{2})(\d)/, "$1/$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
    v = v.replace(/(\d{2})(\d)/, "$1/$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
    return v;
}

function cpf(v) {
    v = v.replace(/\D/g, "");                    //Remove tudo o que não é dígito
    v = v.replace(/(\d{3})(\d)/, "$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
    v = v.replace(/(\d{3})(\d)/, "$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
    //de novo (para o segundo bloco de números)
    v = v.replace(/(\d{3})(\d{1,2})$/, "$1-$2"); //Coloca um hífen entre o terceiro e o quarto dígitos
    return v;
}

function cnpj(v) {
    v = v.replace(/\D/g, "");                    //Remove tudo o que não é dígito
    v = v.replace(/(\d{2})(\d)/, "$1.$2");       //Coloca um ponto entre o segundo e o quarto dígitos
    v = v.replace(/(\d{3})(\d)/, "$1.$2");       //Coloca um ponto entre o terceiro e o quarto dígitos
    v = v.replace(/(\d{3})(\d)/, "$1/$2");       //Coloca uma barra entre o terceiro e o quarto dígitos
    //de novo (para o segundo bloco de números)
    v = v.replace(/(\d{4})(\d{1,2})$/, "$1-$2"); //Coloca um hífen entre o quarto e o quinto dígitos
    return v;
}

function fechaBanner(obj) {
    $("#" + obj).hide();
}


/*
	Funções para trabalho com Cookie
*/

function setCookie(name,value,days,path) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";

	if (path) {
		var path= "; path="+ path;
	}
	else var path = "";
	document.cookie = name+"="+value+expires+path;
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function getOmniEvents(){
	//event4 contabiliza os "page view", toda paginá acessada deve passar esse parametro;
	//event19 contabiliza os "entries", ou seja, a página em que o úsuario começou a navegação pelo site;
	//event20 contabiliza os "no exits", ou seja, se o úsuario acesssar uma segunda página, event8 deve ser contabilizado;
	
	var eventos;
	
	test_visits = getCookie('visits');
	
	if(!test_visits)
	{
		eventos = "event4,event19";
		visits = "1aPagina";
	}
	else if (test_visits == "1aPagina")
	{
		eventos = "event4,event20";
		visits = "2aPagina";
	}
	else
	{
		eventos = "event4";
		visits = "outraPagina";
	}
	setCookie('visits',visits, null, "/");
	
	return eventos;
}