$(document).ready(function() {
    if ($.browser.msie && ($.browser.version < 7)) {
        $(".png").ifixpng();
    }

    /*Flash*/
    $("#flashHome").each(function() {
        $id = $(document).getUrlParam("id");
        $(this).flash({ src: '/swf/flashHome.swf', width: 972, height: 600, wmode: 'transparent', flashvars: { id: [$id].join(' ')} }, { version: 9 });
    });
    $('#flashHomeFase2').flash({ src: '/swf/flashHomeFase2.swf', width: 972, height: 581, wmode: 'transparent' }, { version: 9 });
    $('#flashHomeFase3').flash({ src: '/swf/flashHomeFase3.swf', width: 972, height: 581, wmode: 'transparent' }, { version: 9 });
    $('#flashRecompensa').flash({ src: '/swf/flashRecompensa.swf', width: 882, height: 458, wmode: 'transparent' }, { version: 9 });

    /*botao compartilhe*/
    $("#container a#btnCompatilhe, a.divulgarFinalistas").each(function() {
        $url = document.location;
        $msg = $("title").html();
        $href = $(this).attr("href").replace(/(#URL#)/gi, $url).replace(/(#MSG#)/gi, $msg);
        $(this).attr("href", $href);
    });

    /*tickbox regulamento*/
    $("a#btnRegulamento, a.regulamento").click(function() {
        tb_show('', '../tb/regulamento.aspx?keepThis=true&TB_iframe=true&width=702&height=470&modal=true', false);
        return false;
    });

    //tickbox dicas
    $("a#btnDicasContarSuaIdeia, a#btnDicasContarSuaIdeia2").click(function() {
        tb_show('', '../tb/dicas.aspx?keepThis=true&TB_iframe=true&width=441&height=370&modal=true', false);
        return false;
    });

    //tickbox esqueci minha senha
    $("a.esqueciSenha").click(function() {
        tb_show('', '../tb/esqueceuSenha.aspx?keepThis=true&TB_iframe=true&width=461&height=228&modal=true', false);
        return false;
    });

    /*chamada scroll regulamento*/
    $scrollReg = setTimeout('$("#boxScrollRegulamento").jScrollPane({ scrollbarWidth: 18, scrollbarMargin: 10, showArrows: true })', 100);

    /*valida form de quero me cadastrar*/
    $("#formQueroCadastrar").validate({ errorContainer: $('.msgVerifique'), //validacao form de cadastro.
        submitHandler: function() {//enviar dados do cadastro, abre tickbox de sucesso.
            $.ajax({
                data: $("#formQueroCadastrar").serialize(),
                dataType: "json",
                url: '/Site/SalvarCadastro.ashx',
                type: 'post',
                success: function(json) {
                    if (json.msg == "OK") {
                        tb_show('', '../tb/cadastroSucesso.aspx?keepThis=true&TB_iframe=true&width=461&height=228&modal=true', false);
                        setTimeout('window.location = "/MeuEspaco.aspx"', 5000);
                    } else {
                        $(".msgVerifique").html(json.erros)
                        $(".msgVerifique").fadeIn();
                    }
                }
            });
        }
    });

    /*valida form de ja sou cadastrado*/
    $("#formSouCadastrado").validate({ errorContainer: $('.msgVerifiqueSenha'), //validacao form de cadastro.
        submitHandler: function() {//enviar dados do cadastro, abre tickbox de sucesso.
            $.ajax({
                data: $("#formSouCadastrado").serialize(),
                dataType: "json",
                url: '/Site/FazerLogin.ashx',
                type: 'post',
                success: function(json) {
                    if (json.msg == "OK") {
                        //$(".msgSucces").fadeIn(); //Programar Libera o acesso
                        window.location = "/meuEspaco.aspx";
                    } else {
                        $(".msgVerifiqueSenha").fadeIn();
                    }
                }
            });
        }
    });

    /*valida form de envie sua ideia*/
    $("#formCadastrarIdeia").validate({ errorContainer: $('.msgVerifique'), //validacao form de cadastro.
        submitHandler: function() {//enviar dados do cadastro, abre tickbox de sucesso.
            $.ajax({
                data: $("#formCadastrarIdeia").serialize(),
                dataType: "json",
                url: '/Site/SalvarIdeia.ashx',
                type: 'post',
                success: function(json) {
                    if (json.msg == "NaoLogado") {
                        window.location = "/login.aspx";
                    }
                    if (json.msg == "OK") {
                        $(".msgSucces").fadeIn();
                    } else {
                        $(".msgVerifique").fadeIn();
                    }
                }
            });
        }
    });

    /*valida form de envie sua ideia*/
    $("#formMandarIdeia").validate({ errorContainer: $('.msgVerifique'), //validacao form de cadastro.
        submitHandler: function() {//enviar dados do cadastro, abre tickbox de sucesso.
            $.ajax({
                data: $("#formMandarIdeia").serialize(),
                dataType: "json",
                url: '/Site/MandarIdeia.ashx',
                type: 'post',
                success: function(json) {
                    if (json.msg == "NaoLogado") {
                        window.location = "/login.aspx";
                    }
                    else if (json.msg == "OK") {
                        //$(".msgSucces").fadeIn();
                        window.location = "/meuEspaco.aspx";
                    } else {
                        $(".msgVerifique").fadeIn();
                    }
                }
            });
        }
    });

    /*valida form de envie sua ideia Logado*/
    $("#formCadastrarIdeiaLogado").validate({ errorContainer: $('.msgVerifique'), //validacao form de cadastro.
        submitHandler: function() {//enviar dados do cadastro, abre tickbox de sucesso.
            $.ajax({
                data: $("#formCadastrarIdeiaLogado").serialize(),
                dataType: "json",
                url: '/Site/SalvarIdeia.ashx',
                type: 'post',
                success: function(json) {
                    if (json.msg == "OK") {
                        tb_show('', '../tb/cadastroIdeia.aspx?keepThis=true&TB_iframe=true&width=461&height=228&modal=true', false);
                        setTimeout('window.location = "/MeuEspaco.aspx"', 5000);
                        //window.location = "/meuEspaco.aspx";
                    } else {
                        $(".msgVerifique").html(json.erros)
                        $(".msgVerifique").fadeIn();
                    }
                }
            });
        }
    });

    /*valida form de esqueci minha senha*/
    $("#formEsqueciSenha").validate({ errorContainer: $('.msgVerifique'),
        submitHandler: function() {//enviar dados do cadastro, abre tickbox de sucesso.
            $.ajax({
                data: $("#formEsqueciSenha").serialize(),
                dataType: "json",
                url: '/Site/EnviarSenha.ashx',
                type: 'post',
                success: function(json) {
                    if (json.msg == "OK") {
                        $(".msgSucces").fadeIn();
                    } else {
                        $(".msgVerifiqueSenha").fadeIn();
                    }
                }
            });
        }
    });

    /*label + input*/
    $("input + label").click(function() {
        if ($(this).prev().attr("type") == 'checkbox') {
            if ($(this).prev().is(":checked")) {
                $(this).prev().attr("checked", false);
            } else {
                $(this).prev().attr("checked", true);
            }
        } else {
            $(this).prev().attr("checked", true);
        }
    });

    $('#formFinalistas li input').click(function() {
        $valor = $('#formFinalistas li input:checked').val();
        $('#formFinalistas li').removeClass('hover');
        $(this).parent().addClass('hover');
        $('#finalistasRight').fadeIn('fast');
        $('#finalistasRight .boxFinalistas').hide();
        $('#finalistasRight .finalista' + $valor).fadeIn('fast');
        $('#avisoFinalistasRight').hide();
    });


    $("#captcha").each(function() {
        Recaptcha.create("6LeNIgsAAAAAAKlU3Xw0emGeAmtC-xWZiQaPj2dC", 'captcha', {
            theme: 'white',
            tabindex: 0,
            callback: Recaptcha.focus_response_field
        });
    });

    /*valida form de votar Finalistas*/
    $("#formFinalistas").validate({ errorContainer: $('.msgVerifique'), errorLabelContainer: $('.msgError'), //validacao form de cadastro.
        submitHandler: function() {//enviar dados do voto, abre tickbox de sucesso.
            $id = $('#formFinalistas li input:checked').val();
            challengeField = $("input#recaptcha_challenge_field").val();
            responseField = $("input#recaptcha_response_field").val();
            $.ajax({
                type: 'GET',
                data: "recaptcha_challenge_field=" + challengeField + "&recaptcha_response_field=" + responseField,
                dataType: "html",
                url: "/Site/ValidarCaptcha.ashx",
                async: false,
                success: function(html) {
                    if (html == "success") {
                        $.ajax({
                            dataType: "json",
                            url: '/Site/Votar.ashx?id=' + $id,
                            type: 'post',
                            success: function(json) {
                                if (json.msg == "OK") {
                                    tb_show('', '../tb/votoSucesso.aspx?keepThis=true&TB_iframe=true&width=461&height=228&modal=true', false);
                                    setTimeout('window.location = "/finalistas.aspx"', 5000);
                                } else {
                                    $(".msgVerifique").html(json.erros)
                                    $(".msgVerifique").fadeIn();
                                }
                            }
                        });
                    } else if (html == "null") {
                        Recaptcha.reload();
                        $(".msgVerifiqueNull").show();
                        $(".msgVerifiqueErro").hide();
                        $(".msgVerifique").hide();
                        //alert("nova mensagem de Erro no captcha!");
                    } else if (html == "error") {
                        Recaptcha.reload();
                        $(".msgVerifiqueErro").show();
                        $(".msgVerifiqueNull").hide();
                        $(".msgVerifique").hide();
                        //alert("nova mensagem de Erro no captcha!");
                    
                    } else {
                        Recaptcha.reload();
                        $(".msgVerifique").show();
                        $(".msgVerifiqueNull").hide();
                        $(".msgVerifiqueErro").hide();
                        //alert("nova mensagem de Erro no captcha!");
                    }
                }
            });
        }
    });

    /* Checkbox e radio personalizados */
    $('#formFinalistas input[type="checkbox"], #formFinalistas input[type="radio"]').each(function() {
        $(this).hasClass('check') ? $(this).next().addClass('check') : $(this).next().addClass('radio');
        if ($(this).attr('checked')) {
            $(this).parent().addClass('selected');
        }
    });
    $('label').hover(function() {
        $('label').removeClass('hover');
        $(this).addClass('hover');
    }, function() {
        $('label').removeClass('hover');
    }).click(function() {
        if ($(this).hasClass('radio')) {
            $('label.radio').removeClass('selected');
        }
        if ($(this).prev().attr('checked') && !($(this).hasClass('radio'))) {
            $(this).removeClass('selected').prev().trigger("click");
        }
        else {
            $(this).addClass('selected').prev().trigger("click");
        }
    });

	setTimeout("$('ul.jcarousel').removeClass('hide').jcarousel({ vertical: false, scroll: 1 })", 500);
    $('ul#listNavReferencias').removeClass('hide').jcarousel({ vertical: false, scroll: 1 });
    $('ul.twittList').removeClass('hide').find('li').each(function() {
        $distance = ($(this).height() - $(this).find('span').height()) / 2;
        $(this).find('span').css({ paddingTop: $distance + 'px' });
    });

    /*Mascara input*/
    $("input.data").mask("99/99/9999");
    $("input.tel").mask("99-99999999");
    $("input.cep").mask("99999-999");
    $("input.cpf").mask("999.999.999-99");
    $("input.cnpj").mask("99.999.999/9999-99");

    /*accordion*/
    $('.titAccor').click(function() {
        $('.titAccor').removeClass('hover').next().slideUp();
        if ($(this).next().is(':visible')) {
            $(this).removeClass('hover').next().slideUp();
        } else {
            $(this).addClass('hover').next().slideDown();
        }
        return false;
    });

    //scroll twitter
    $('#boxScroll').jScrollPane({ scrollbarWidth: 18, scrollbarMargin: 10, showArrows: true });

    //limita caracteres
    /*
    $("#descrIdeia").keydown(function() {
    limitChars("#descrIdeia", 1400);
    })
    */

    //maxlengh
    $("textarea.maxlength").maxlength({
        'feedback': '.charsLeft'
    });

    //valida select box aplicativo
    $(".opcaoAplicativo").change(function() {
        if ($(this).val() == "outros") {
            $(this).parents(".boxOpcao").find(".boxOpcaoOutros").show().find("input").focus().addClass("required").val("");
        }
        else {
            $(this).parents(".boxOpcao").find(".boxOpcaoOutros").hide().find("input").removeClass("required error").val($(this).val());
        }
    });

    //remove required box aplicativo sim
    $(".interacaoSim").click(function() {
        $(this).parents(".boxOpcao").find(".opcaoAplicativo").addClass("required");
        $(this).parents(".item").find(".opcaoAplicativo").attr("disabled", false);
    });

    //remove required box aplicativo nao
    $(".interacaoNao").click(function() {
        $(this).parents(".item").find(".opcaoAplicativo").removeClass("required error");
        $(this).parents(".item").find(".boxOpcaoOutros").hide().find("input").val("Nao").removeClass("required error");
        $(this).parents(".item").find(".opcaoAplicativo").attr("disabled", true);
    });

    //mostra div compartilhe desativado
    /*
    $(".showCompartilhe").click(function() {
    $(".compartilhe").slideToggle("fast");
    return false;
    });
    */

    /*botoes navegacao compartilhe*/
    $("#share a").each(function() {
        $url = document.location;
        $msg = $(".printTitle").text();
        $href = $(this).attr("href").replace(/(#URL#)/gi, $url).replace(/(#MSG#)/gi, $msg);
        $(this).attr("href", $href);
    });

    /*GA*/
    $(".ga").click(function() {
        pageTracker._trackPageview($(this).attr("rel"));
    });

});

//funcao limite caractere
function limitChars(textid, limit, infodiv) {
    var text = $(textid).val();
    var textlength = text.length;
    $(textid).removeClass("error");
    if (textlength > limit) {
        if(infodiv){
   			infodiv.html('0');
        }
  		$(textid).val(text.substr(0, limit));
        return false;
    } else {
  		if(infodiv){
        	infodiv.html((limit - textlength));
        }
  	return true;
    }
}

function openLightBox(){
	tb_show("", "/tb/app.aspx?KeepThis=true&TB_iframe=true&height=460&width=261", false);
}
