//Onload da Pagina
//href="#TB_inline?height=155&width=300&inlineId=hiddenModalContent&modal=true" class="thickbox"
//

$(document).ready(
	function() {
		//adm
		$("#form_post").submit(
			function()
			{
				$("#opcoes_cadastradas option").attr("selected","selected");
				return ValidaForm("form_post");
			}
		);
		$("#add").click(
			function()
			{
				troca("opcoes_nao_cadastradas","opcoes_cadastradas");
			}
		);
		$("#rem").click(
			function()
			{
				troca("opcoes_cadastradas","opcoes_nao_cadastradas");
			}
		)
		$("#mais").click(
			function()
			{
				$("#arquivos").append($("#file input").clone());
			}
		);


		//Modal Login
		$("#menu-bt-restrita").attr("href","#TB_inline?height=155&width=300&inlineId=box_login&modal=true");
		$("#menu-bt-restrita").attr("class","thickbox");

		$("#box_login a").click(function(){tb_remove()});
		$("#box_login form").attr("action", "/login/");

		//Limpa campo de busco após ser cliclado
		$("#txt_busca").click(function(){$("#txt_busca").attr("value","");});
		$("#searchsubmit").click(function(){document.location = "/busca/" + $("#txt_busca").val();});
		//tava anexando 127351273512 eventos no botão abaixo !
		$("#bt_box_login").hover(
			function(){
				$("#bt_box_login").attr("disabled",false);
			}
		);
		$("#bt_box_login").blur(
			function(){
				$("#bt_box_login").attr("disabled",true);
			}
		);
		$("#bt_box_login").click(
			function(){
				if( $("#txt_login").val().trim() != "" &&
					$("#txt_senha").val().trim() != ""){
					return true;
				}else{
					alert("preencha os dados corretamente");
					return false;
				}
			}
		)

		$("body").fadeIn("slow");
		if($("#txt_mensagem").val()!="")
		{
			$.notifyBar(
				{
					html: $("#txt_mensagem").val(),
					delay: 2500,
					animationSpeed: "normal"
				}
			);  
		}
		


	}
);
/**
 * Função para Validar Formularios (Generica)
 * campos marcados com rel=1 serão validados
 */
function ValidaForm(form_id)
{
	ok = true;
	if($("#" + form_id))
	{
		$("#" + form_id + " input").each(
			function(){
				if($(this).attr("rel") == "1" && jQuery.trim($(this).attr("value")) == "" )
				{
					ok = false;
					$(this).focus(
						function(){
							$(this).css("border","1px solid #CCCCCC");
							$(this).next().text("");
							$(this).val("");
						}
					);
					$(this).css("border","1px solid red");
					if($(this).next())
						$(this).next().text("campo obrigatório");
				}
			}
		)
		$("#" + form_id + " select").each(
			function(){
				if($(this).attr("rel") == "1" && jQuery.trim($(this).attr("value")) == "" )
				{
					ok = false;
					$(this).focus(
						function(){
							$(this).css("border","1px solid #CCCCCC");
							$(this).next().text("");
							$(this).val("");
						}
					);
					$(this).css("border","1px solid red");
					if($(this).next())
						$(this).next().text("campo obrigatório");
				}
			}
		)		
	}
	if(ok)
		return true; 
	else
		return false;
} 

function include(arquivo)
{
	var novo = document.createElement('script');
	novo.setAttribute('type', 'text/javascript');
	novo.setAttribute('src', arquivo);
	document.getElementsByTagName('head')[0].appendChild(novo);
}



function formatar(mascara, documento){
 var i = documento.value.length;
 var saida = mascara.substring(0,1);
 var texto = mascara.substring(i)

 if (texto.substring(0,1) != saida){documento.value += texto.substring(0,1);}

}

function validaMail(idmail){
	var emailva,emailar, emailpt, emailln;
	emailva = document.getElementById(idmail).value
	with(document.cadastro){
		emailar = emailva.indexOf('@',0);
		emailpt = emailva.indexOf('.',emailar);
		emailln = emailva.length;
		if(emailva == ""){
			document.getElementById(idmail).focus();
			document.getElementById(idmail).value = "";
			/*alert('O Campo e-mail deve ser preenchido !');*/
			return false;
		}
		if((emailln<12) || (emailar==-1) || (emailpt==-1) || (emailar<1) || (emailpt-emailar<2) || (emailln-emailpt<3)){
			document.getElementById(idmail).focus();
			document.getElementById(idmail).value = "";
			/*alert('E-mail invalido !');*/
			return false;
		}
		if (emailva.split('@').length > 2){
			document.getElementById(idmail).focus();
			document.getElementById(idmail).value = "";
			/*alert('E-mail invalido !');*/
			return false;
		}
		return true;
	}
}
function SelectToHidden(id_origem,id_destino)
{
	var conteudo = "";
	for (i=0;i<document.getElementById(id_origem).options.length;i++){ 
		conteudo+= document.getElementById(id_origem).options[i].value + ',';	
	}
	document.getElementById(id_destino).value = conteudo;	
}
function ValidaCadastro()
{
	var msg = "";
	var conteudo = "";
	var i = 0;
	if (document.getElementById('nome').value == ""){
		msg+= 'Digite corretamente o nome !\n';
		document.getElementById('nome').className = 'atencao';
	}

	if (!validaMail('email')){
		msg+= 'Digite um e-mail valido !\n';
		document.getElementById('email').className = 'atencao';
	}

	if(msg != ""){
		alert(msg);
		return false;
	}
	return true;	
}
function ValidaContato()
{
	var msg = "";
	var conteudo = "";
	var i = 0;
	if (document.getElementById('nome').value == ""){
		msg+= 'Digite corretamente o nome !\n';
		document.getElementById('nome').className = 'atencao';
	}
	if (document.getElementById('mensagem').value == ""){
		msg+= 'Digite corretamente sua mensagem !\n';
		document.getElementById('mensagem').className = 'atencao';
	}
	if (!validaMail('email')){
		msg+= 'Digite um e-mail valido !\n';
		document.getElementById('email').className = 'atencao';
	}

	if(msg != ""){
		alert(msg);
		return false;
	}
	return true;	
}
function ValidaEvento()
{
	var msg = "";
	var conteudo = "";
	var i = 0;
	if (document.getElementById('titulo').value == ""){
		msg+= 'Digite corretamente o titulo !\n';
		document.getElementById('titulo').className = 'atencao';
	}
	if (document.getElementById('descricao').value == ""){
		msg+= 'Digite corretamente a descricao !\n';
		document.getElementById('descricao').className = 'atencao';
	}
	if (document.getElementById('data_inicio').value.length < 16){
		msg+= 'A data deve conter no minimo 16 caracteres !\n';
		document.getElementById('data_inicio').className = 'atencao';
	}
	if (document.getElementById('data_fim').value.length < 16){
		msg+= 'A data deve conter no minimo 16 caracteres !\n';
		document.getElementById('data_fim').className = 'atencao';
	}	
	if(msg != ""){
		alert(msg);
		return false;
	}
	return true;	
}
function ValidaAutor()
{
	var msg = "";
	var conteudo = "";
	var i = 0;
	if (document.getElementById('nome').value == ""){
		msg+= 'Digite corretamente o nome !\n';
		document.getElementById('nome').className = 'atencao';
	}
	if (document.getElementById('descricao').value == ""){
		msg+= 'Digite corretamente a descricao !\n';
		document.getElementById('descricao').className = 'atencao';
	}
	if(msg != ""){
		alert(msg);
		return false;
	}
	return true;	
}
function troca(Origem,Destino)
{
	var i;
	for (i = 0; i < document.getElementById(Origem).options.length ; i++)
	{
		if (document.getElementById(Origem).options[i].selected == true)
		{
			var Op = document.createElement("OPTION");
			Op.text = document.getElementById(Origem).options[i].text;
			Op.value = document.getElementById(Origem).options[i].value;
			document.getElementById(Destino).options.add(Op);
			document.getElementById(Origem).remove(document.getElementById(Origem).selectedIndex);
			i--;
		}
	}
}
function limpa(id)
{
	document.getElementById(id).className = '';	
}
function CheckServico()
{
	var msg = '';
	if(document.getElementById('nome').value == "")
	{
		msg += 'é necessário escolher um nome !!!\n';
		document.getElementById('nome').className = 'atencao';
	}	
	if(document.getElementById('valor').value == "")
	{
		msg += 'é necessário escolher o valor !!!\n';
		document.getElementById('valor').className = 'atencao';
	}	
	if(msg != '')
	{
		alert(msg);
		return false
	}
	return true;
}
function valida(){
	var f=document.login;
	var msg="";	
	
	if(f.login.value == '') msg=msg + "\n Digite um usuário.";
	if(f.senha.value == '') msg=msg + "\n Digite uma senha";
		
	if(msg != ""){
		msg="Erro no preenchimento dos campos:\n" + msg;
		alert(msg);
		return false;
	} else {
		return true;
	}
}

function inicia(){
	document.login.login.focus();
}
function SoNumeros(e)
{
	car=(navigator.appName == "Netscape" ) ? e.which : e.keyCode;
	//alert(car);
	if (car>31 && (car<48 || car >57))
		return false;
	else
		return true;
}
function Certeza(){
	return confirm('Tem certeza que deseja excluir esse registro ?');
}
function sortSelect(selectToSort) 
{

	var myOptions = [];
        for (var i=0; i<selectToSort.options.length; i++)
		{
        	myOptions[i] = { optText:selectToSort.options[i].text, optValue:selectToSort.options[i].value };
        }
        myOptions.sort(sortFuncAsc);
        selectToSort.options.length = 0;
        for (var i=0; i<myOptions.length; i++) 
		{
        	var optObj = document.createElement('option');
                optObj.text = myOptions[i].optText;
                optObj.value = myOptions[i].optValue;
                selectToSort.options.add(optObj);
         }
}

function Excluir(selectId){
	document.getElementById(selectId).remove(document.getElementById(selectId).selectedIndex);
}
function Abre(theURL,winName,features) {
	window.open(theURL,winName,features);
}
//-----------------------------------------------------
//Funcao: MascaraMoeda
//Sinopse: Mascara de preenchimento de moeda
//Parametro:
//   objTextBox : Objeto (TextBox)
//   SeparadorMilesimo : Caracter separador de milésimos
//   SeparadorDecimal : Caracter separador de decimais
//   e : Evento
//Retorno: Booleano
//Autor: Gabriel Fróes - www.codigofonte.com.br
//onKeyPress="return(MascaraMoeda(this,'.',',',event))"
//-----------------------------------------------------
function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e){
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    //alert(whichCode);
    if (whichCode == 13 || whichCode == 8) return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave
    if (strCheck.indexOf(key) == -1) return false; // Chave inválida
    len = objTextBox.value.length;
    for(i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal)) break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i))!=-1) aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) objTextBox.value = '';
    if (len == 1) objTextBox.value = '0'+ SeparadorDecimal + '0' + aux;
    if (len == 2) objTextBox.value = '0'+ SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
        objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}