//////////////////////////////
// ON DOCUMENT READY JQUERY
//////////////////////////////
$(document).ready(function(){
    // mascara de telefone
    $(".phone").mask("(99) 9999-9999");
    $(".cep").mask("99999-999");
    //////////////////////////////
    // Validacao de formularios
    //////////////////////////////
    // coloca as tags dentro de #erro
    $("#erro").prepend('<div id="erro-msg" class="ui-widget"><div class="ui-state-error ui-corner-all" style="padding: 0 .7em;"><p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;" /><h4>Corrija os erros da página:</h4><ul>   </ul></p></div></div><br />');
    var container = $('#erro-msg');
    $(".validate-dcms").validate({
        errorContainer: container,
        errorLabelContainer: $("ul", container),
        wrapper: 'li',
        rules:{
            senha:{
                rangelength:[4,10]
            },
            no_senha2:{
                required:true,
                rangelength:[4,10],
                equalTo:"#senha"
            }
        },
        messages:{
            senha: "Informe uma senha."
        }
    });
    // ajax para verificar se email ja esta cadastrado
    $("#email").blur(function()
    {
        //remove all the class add the messagebox classes and start fading
        $("#msgbox").removeClass().html('<img src="/dcms4/imagens/ajax-loader.gif" />').fadeIn("slow");
        //check the username exists or not from ajax
        $.post("?usuario=check_email",{
            email:$(this).val()
        } ,function(data)
        {
            if(data=='no') //if username not avaiable
            {
                $("#msgbox").fadeTo(200,0.1,function() //start fading the messagebox
                {
                    //add message and change the class of the box and start fading
                    $(this).html('Este email já está cadastrado').addClass('messageboxerror').fadeTo(900,1);
                    $('#email').css('background-color','#fed4d4');
                });
            }
            else
            {
                $("#msgbox").fadeTo(200,0.1,function()  //start fading the messagebox
                {
                    //add message and change the class of the box and start fading
                    //$(this).html('ok').addClass('messageboxok').fadeTo(900,1);
                    $(this).html('ok').fadeTo(900,1).hide();
                    $('#email').css('background-color','#e2f7cd');
                });
            }
        });
    });
});


//////////////////////////////
// CHANGE ANY URL PARAMETER
// troca qualquer parametro e acrescenta se não tiver
function caup(key, value, page) {
    var wlh = page.split("?");
    var param = wlh[1].split("&");
    var tmp;
    var url   = wlh[0];
    var KEY   = new Array();
    var VALUE = new Array();
    // passa params para KEY & VALUE
    for(var i=0;i<param.length;i++) {
        tmp      = param[i].split("/");
        KEY[i]   = tmp[0];
        VALUE[i] = tmp[1];
    }
    var cont = 0;
    // muda o parametro desejado e monda a URL
    for(var i=0;i<KEY.length;i++) {
        if(key == KEY[i]){
            VALUE[i] = value;
            cont++;
        }
        if(i==0){
            url += '?' + KEY[i] + '/' + VALUE[i];
        }else{
            url += '/' + KEY[i] + '/' + VALUE[i];
        }
    }
    if(cont == 0){
        url += '/' + key + '/' + value;
    }
    return url;
}
//////////////////////////////
// GET URL PARAMETERS
function gup( name ) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if( results == null )
        return false;
    else
        return results[1];
}
///////////////////////////////////
function checkIndicar(f) {
    var erro   = false;
    var notice = 'Por favor corrija os campos abaixo:\n\n';
    if(f.nome.value == '') {
        notice += 'Seu nome\n';
        erro   = true;
    }
    if(!isValidEmail(f.email.value)) {
        notice += 'Email destinatário\n';
        erro   = true;
    }

    if(erro==true) {
        alert(notice);
        return false;
    } else {
        return true;
    }
}
//////////////////////////////
function Paginacao(pag, num) {
    window.location.href = caup(pag,num,window.location.href);
}
//////////////////////////////
function FiltroAno(ano) {
    var page = caup('ano',ano,window.location.href);
    window.location.href = page;
    return false;
}
//////////////////////////////
function FiltroVideoTipo(tipo) {
    var page = caup('tipo',tipo,window.location.href);
    window.location.href = page;
    return false;
}
//////////////////////////////
function FiltroImprensaTipo(tipo) {
    var page = caup('tipo',tipo,window.location.href);
    window.location.href = page;
    return false;
}
