// JavaScript Document
function flash(largura, altura, arquivo, transparencia)
{
 document.write('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="'+largura+'" height="'+altura+'" id="teste" align="middle">');
 document.write('<param name="allowScriptAccess" value="sameDomain" /><param name="wmode" value="'+transparencia+'" /><param name="menu" value="false" />');
 document.write('<param name="movie" value="'+arquivo+'" /><param name="quality" value="best" /><param name="bgcolor" value="#ffffff" /><embed src="'+arquivo+'" wmode="'+transparencia+'" menu="false" quality="best" width="'+largura+'" height="'+altura+'" name="teste" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />');
 document.write('</object>');
}


 function checkAll(id,master){
           $('#'+id+' :input[type=checkbox]').each(function(i){
            this.checked = master.checked;
         });
     }

function checkUncheckAll(theElement)
{
    var theForm = theElement.form, z = 0;
    for(z=0; z<theForm.length;z++)
    {
        if(theForm[z].type == 'checkbox' && theForm[z].name != 'master')
        {
            theForm[z].checked = theElement.checked;
        }
    }
}


function validacaoRapidaPagamento()
{
	var nosso_numero = document.getElementById("faturas_nosso_numero").value;
	
	if(nosso_numero != "")
	{
		document.getElementById("faturas_nosso_numero").value = "";
		getDados('resultados','validacoes/acoes/validar_pagamento_nosso_numero.php?faturas_nosso_numero='+nosso_numero);
	}
	else
	{
		return false;
	}
}

function statusPagamento(nValue)
{
	if(nValue == 2)
	{
		document.getElementById("conta_paga").style.display = "block";
	}
	else
	{
		document.getElementById("conta_paga").style.display = "none";
		
		document.getElementById("contas_data_pagamento_DATE").value = "";
		document.getElementById("contas_valor_pagamento_FLOAT").value = "0,00";
		
	}
}

function atualizarStatusPedido()
{
	
	var pedidos_id = document.getElementById("pedidos_id_validacao").value;
	var pedidos_status_INT = document.getElementById("select_status_pedidos").value;
	
	getDados('retorno_validacao','validacoes/acoes/atualizar_status_pedido.php?pedidos_id='+pedidos_id+'&pedidos_status_INT='+pedidos_status_INT);
}

function ActionsReceitas(nAction,excluir)
{

	if(excluir != "")
	{
		if(confirm("TEM CERTEZA QUE DESEJA EXCLUIR ESTA(S) RECEITA(S)? ESTA É UMA AÇÃO PERMANENTE"))
		{
			document.form_receitas.action = nAction;
	
			document.form_receitas.submit();
		}
		else
		{
			return false;
		}
	}
	else
	{
		document.form_receitas.action = nAction;
	
		document.form_receitas.submit();
	}
}


/*
	função para fazer as máscaras da entrada do formulário de acordo com o algaritimo que você quiser
	usar a função desta maneira, colocar o nome do formulario e o nome do campo
	onkeypress="return mascara(this, '999-999999', event);"
*/
function mascara(objForm, sMask, evtKeyPress)
{
     var i, nCount, sValue, fldLen, mskLen, bolMask, sCod, nTecla;

     if (evtKeyPress.keyCode) nTecla = evtKeyPress.keyCode; //internet explorer
	 else if (evtKeyPress.which) nTecla = evtKeyPress.which; // mozilla firefox

     sValue = objForm.value;

     // Limpa todos os caracteres de formatação que
     // já estiverem no campo.
     sValue = sValue.toString().replace( "-", "" );
     sValue = sValue.toString().replace( "-", "" );
     sValue = sValue.toString().replace( ".", "" );
     sValue = sValue.toString().replace( ".", "" );
     sValue = sValue.toString().replace( "/", "" );
     sValue = sValue.toString().replace( "/", "" );
     sValue = sValue.toString().replace( "(", "" );
     sValue = sValue.toString().replace( "(", "" );
     sValue = sValue.toString().replace( ")", "" );
     sValue = sValue.toString().replace( ")", "" );
     sValue = sValue.toString().replace( " ", "" );
     sValue = sValue.toString().replace( " ", "" );
     fldLen = sValue.length;
     mskLen = sMask.length;

	i = 0;
	nCount = 0;
	sCod = "";
	mskLen = fldLen;
	
	while (i <= mskLen)
	{
		bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
		bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))
		
		if (bolMask)
		{
			sCod += sMask.charAt(i);
			mskLen++;
		}
		else
		{
			sCod += sValue.charAt(nCount);
			nCount++;
		}
		i++;
	}

	if (sCod.charAt(sCod.length-1) ==
	    objForm.value.charAt(objForm.value.length-1))
	objForm.value = sCod;

	if (nTecla != 8) { // backspace
		if (sMask.charAt(i-1) == "9") // apenas números...
		{
			return ((nTecla > 47) && (nTecla < 58)); // números de 0 a 9
		} 
		else // qualquer caracter...
		{
			return false;
		} 
	}
	else
	{
		return true;
	}
}

function SomenteNumero(e){
    var tecla=(window.event)?event.keyCode:e.which;
    if((tecla > 47 && tecla < 58)) return true;
    else{
    if (tecla != 8) return false;
    else return true;
    }
}

function login(nform){

	if(nform.txtEmail.value=="" || nform.txtSenha.value==""){

		alert("ERRO: Preencha todos os campos");

		return false;
	}
}


function excluirContents(url,MSG){
    if(confirm(MSG)){
        location.href=url;
    }
    else{
        return false;   
    }
}

function validaTodos(nform){
    for(var i = 0; i < nform.elements.length; i++){
        if(nform.elements[i].value == "" && nform.elements[i].type != "hidden" && nform.elements[i].type != "checkbox" && nform.elements[i].type != "file"){
            alert("Preencha todos os campos");
            nform.elements[i].focus();
            return false;
        }
    }   
}

function maiusculo(nField){
	nField.value = nField.value.toUpperCase();
}

function minusculo(nField){
    nField.value = nField.value.toLowerCase();
}



/*
    Função para não deixar inserir mais de um determinado N° de caracteres no textarea
*/

var timer;

function limitarTamanho(campo,tamanho)
{
//ta = TextArea
//tamanho = maximo de caracteres permitidos
	
	var ta = document.getElementById(campo);
	
    if(ta.value.length > tamanho)
        ta.value = ta.value.substring(0, tamanho);
    timer = setTimeout("limitarTamanho(" + tamanho + ")", 100);
    return;
}

function pararLimitacao() {
    clearTimeout(timer);
    return;
}

function setAdministrador(){
    preencheu = false;
	
	var radio = document.forms[0].funcionarios_administrador_INT;
    
	var botoes = document.forms[0].funcionarios_administrador_INT.length;
    
	for (i=0; i < botoes; i++) {
        if (radio[i].checked){
            if(radio[i].value == 0){
                document.getElementById('permissoes').style.display = "none";
				document.getElementById('separador').style.display = "none";
				document.getElementById('tr1Cadastro').style.display = "block";
				document.getElementById('tr2Cadastro').style.display = "block";
			}
			else{
				document.getElementById('tr1Cadastro').style.display = "none";
                document.getElementById('tr2Cadastro').style.display = "none";
				document.getElementById('permissoes').style.display = "block";
                document.getElementById('separador').style.display = "block";
			}
        }
    }
}


function jumpMenu(targ,selObj,restore)
{
    /*
    <select onchange="jumpMenu('parent',this,0)">
	   <option value='?page=vitrine&idDep=".$linhaDep["departamentos_id"]."'>".$linhaDep["departamentos_nom"]."</option>";
	</select>
	*/
	
    eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
    if (restore) selObj.selectedIndex=0;
}

//Função usada no arquivo de alterar senha
function alterar_senha(nform)
{
	if(nform.funcionarios_senha.value == "" || nform.txtSenhaNovaConfirm.value == "")
	{
		alert("Preencha os dois campos");
		nform.funcionarios_senha.value = "";
		nform.txtSenhaNovaConfirm.value = "";
		nform.funcionarios_senha.focus();
		return false;
	}
	
	else if(nform.funcionarios_senha.value.length < 5)
	{
		alert("A senha deve ter no mínimo 5 caracteres");
		nform.funcionarios_senha.value = "";
		nform.funcionarios_senha.maxlength = 15;
		nform.txtSenhaNovaConfirm.value = "";
		nform.funcionarios_senha.focus();
		return false;
	}
	
	else if(nform.funcionarios_senha.value != nform.txtSenhaNovaConfirm.value)
	{
		alert("As senha informadas não são iguais");
		nform.funcionarios_senha.value = "";
		nform.txtSenhaNovaConfirm.value = "";
		nform.funcionarios_senha.focus();
		return false;
	}
	
	else
	{
		return true;
	}
}
//Fim alterar senha


function popup(URL, largura, altura) 
{

	var top = (screen.height - altura) / 2;
	
	var left = (screen.width - largura) / 2;    
	
	
	day = new Date();
	
	id = day.getTime();
	
	eval("page" + id + " = window.open(URL, '" + id + "', 'scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=" + largura + ",height=" + altura + ",top=" + top + ",left=" +  left + "');");

}

function fecharPopUp(msg)
{
	window.opener.location.reload();
	alert(msg);
	window.close();
}


function alturaFlash(nValue)
{
	
	var titulo = document.getElementById("altura_arquivo");
	var inputAltura = document.getElementById("altura_arquivo_valor");
	
	if(nValue == "flash")
	{
		titulo.innerHTML = "ALTURA ARQUIVO(px):";
		inputAltura.innerHTML = "<input type='text' name='banners_altura_INT' value='' onfocus=\"this.className='input_focus';\" class=\"form_campo1\" onblur=\"this.className='form_campo1';\"/>";
	}
	else
	{
		titulo.innerHTML = "&nbsp;";
		inputAltura.innerHTML = "&nbsp;";
	}
}


function validaTodosBanners(nform)
{
    for(var i = 0; i < nform.elements.length; i++)
	{
		if(nform.elements[i].value == "" && nform.elements[i].type != "hidden" && nform.elements[i].type != "checkbox" && nform.elements[i].name != "banners_link" && nform.elements[i].type != "file")
		{
			alert("Preencha todos os campos");
	        nform.elements[i].focus();
	        return false;
        }
		
		if(document.getElementById("banners_id").value == "")
		{
			if(nform.elements[i].type == "file" && nform.elements[i].value == "")
			{
				alert("Preencha todos os campos - aqui");
		        nform.elements[i].focus();
		        return false;
			}	
		}
		
    }   
}


function abreFechaMenu(id)
{

	if(document.getElementById(id).style.display == "none")
	{
		Effect.BlindDown(id, { duration: 1.0 });
		//Effect.SlideDown(id, { duration: 1.0 });
		return false;
	}
	else
	{
		Effect.BlindUp(id, { duration: 1.0 });
		//Effect.SlideUp(id, { duration: 1.0 });		
		return false;
	}
		 
}

function define_parcelamento(nValue)
{
	
	var parcelamentos = document.getElementById("parcelamentos");
	
	if(nValue == 1)
	{
		parcelamentos.style.display = "block";
		//Effect.BlindDown("parcelamentos", { duration: 0.5 });
	}
	else
	{
		parcelamentos.style.display = "none";
		//Effect.BlindUp("parcelamentos", { duration: 0.5 });
	}
}


function tipo_parcelamento(nValue)
{
	if(nValue == 1)
	{
		//Effect.BlindDown("tipo_parcelamento", { duration: 0.5 });
		//Effect.BlindDown("condicoes_parcelamento", { duration: 0.5 });
		document.getElementById("tipo_parcelamento").style.display = "block";
		document.getElementById("condicoes_parcelamento").style.display = "block";
	}
	else
	{
		//Effect.BlindUp("tipo_parcelamento", { duration: 0.5 });
		//Effect.BlindUp("condicoes_parcelamento", { duration: 0.5 });
		document.getElementById("tipo_parcelamento").style.display = "none";
		document.getElementById("condicoes_parcelamento").style.display = "none";
	}
}


function parcelas_cartao_visa(nValue)
{
	var condicoes;
		
	for(var i = 1; i <= nValue; i++)
	{
		if(!condicoes)
		{
			condicoes = i+"X <select name=\"condicoes_parcelas_INT_"+i+"\" class=\"form_campo1\" onfocus=\"this.className='input_focus1';\" onblur=\"this.className='form_campo1';\"><option value=\"1\">Desconto</option><option value=\"2\">Sem Juros</option><option value=\"3\">Com Juros</option></select><br/><br/>";			
		}
		else
		{
			condicoes+= i+"X <select name=\"condicoes_parcelas_INT_"+i+"\" class=\"form_campo1\" onfocus=\"this.className='input_focus1';\" onblur=\"this.className='form_campo1';\"><option value=\"1\">Desconto</option><option value=\"2\">Sem Juros</option><option value=\"3\">Com Juros</option></select><br/><br/>";
		}	
	}
	
	document.getElementById("condicoes_parcelas_visa").innerHTML = condicoes;
	
}


function parcelas_cartao_master(nValue)
{
	var condicoes;
		
	for(var i = 1; i <= nValue; i++)
	{
		if(!condicoes)
		{
			condicoes = i+"X <select name=\"condicoes_parcelas_INT_"+i+"\" class=\"form_campo1\" onfocus=\"this.className='input_focus1';\" onblur=\"this.className='form_campo1';\"><option value=\"1\">Desconto</option><option value=\"2\">Sem Juros</option><option value=\"3\">Com Juros</option></select><br/><br/>";			
		}
		else
		{
			condicoes+= i+"X <select name=\"condicoes_parcelas_INT_"+i+"\" class=\"form_campo1\" onfocus=\"this.className='input_focus1';\" onblur=\"this.className='form_campo1';\"><option value=\"1\">Desconto</option><option value=\"2\">Sem Juros</option><option value=\"3\">Com Juros</option></select><br/><br/>";
		}	
	}
	
	document.getElementById("condicoes_parcelas_master").innerHTML = condicoes;
	
}

function is_numeric(sText)
{
		
	var CaracteresValidos = "0123456789.";
	
	var Caracter;
 
	for (i = 0; i < sText.length; i++) 
	{ 
		if (CaracteresValidos.indexOf(sText.charAt(i)) == -1) 
		{
			return false;
		}
	}
	return true;
}

function so_numeros(sText)
{
		
	var CaracteresValidos = "0123456789";
	
	var Caracter;
 
	for (i = 0; i < sText.length; i++) 
	{ 
		if (CaracteresValidos.indexOf(sText.charAt(i)) == -1) 
		{
			return false;
		}
	}
	return true;
}

function validaPorcentagem(nField)
{
	var nValue = nField.value;
	
	nValue = nValue.replace(",",".");
	
	if(nValue.indexOf(".") > 1)
	{
		alert("Coloque somente 1 dígito separador para casas decimais");
		nField.value = "";
		nField.focus();
		return false;
	}
	
	if(is_numeric(nValue) === false)
	{
		alert("Digite somente números");
		nField.value = "";
		nField.focus();
		return false;
	}
	else
	{
		if(nValue > 100)
		{
			alert("Valor máximo permitido é 100");
			nField.value = "";
			nField.focus();
			return false;	
		}
	}	
}


function enviarDadosRepresentante(nValue)
{
	getDados('retorno_ajax','ajax/enviar_dados_representantes.php?representantes_id='+nValue);
}


function configPromocao(nCheck,tipo)
{
	
	var promocaoPf 	= document.getElementById("produtos_promocao_pf_INT");
	var divPf 		= document.getElementById("div_promocao_pf");
	var precoPf 	= document.getElementById("produtos_preco_promocional_pf_FLOAT");
	var dataIniPf 	= document.getElementById("inicio_pf");
	var dataFimPf 	= document.getElementById("fim_pf");
	
	var promocaoPj	= document.getElementById("produtos_promocao_pj_INT");
	var divPj 		= document.getElementById("div_promocao_pj");
	var precoPj 	= document.getElementById("produtos_preco_promocional_pj_FLOAT");
	var dataIniPj 	= document.getElementById("inicio_pj");
	var dataFimPj 	= document.getElementById("fim_pj");
	
	
	if(tipo == "pf")
	{
		if(nCheck.checked == true)
		{
			promocaoPf.value = 1;
			divPf.style.display = "block";
		}
		else
		{
			promocaoPf.value = 2;
			divPf.style.display = "none";
			precoPf.value = "0,00";
			dataIniPf.value = "";
			dataFimPf.value = "";
		}
	}
	else
	{
		if(nCheck.checked == true)
		{
			divPj.style.display = "block";
			promocaoPj.value = 1;
		}
		else
		{
			divPj.style.display = "none";
			promocaoPj.value = 2;
			precoPj.value = "0,00";
			dataIniPj.value = "";
			dataFimPj.value = "";
		}
	}
	
		
}


function validaProdutos(nform)
{
    
	for(var i = 0; i < nform.elements.length; i++)
	{
        if(nform.elements[i].value == "" && nform.elements[i].type != "hidden" && nform.elements[i].type != "checkbox" && nform.elements[i].type != "file" && nform.elements[i].name != "produtos_preco_promocional_pf_FLOAT" && nform.elements[i].name != "produtos_promocao_pf_data_de_DATE" && nform.elements[i].name != "produtos_promocao_pf_data_ate_DATE" && nform.elements[i].name != "produtos_preco_promocional_pj_FLOAT" && nform.elements[i].name != "produtos_promocao_pj_data_de_DATE" && nform.elements[i].name != "produtos_promocao_pj_data_ate_DATE")
		{
            alert("Preencha todos os campos");
            nform.elements[i].focus();
            return false;
        }
    }   
}

function focus(element)
{
    document.getElementById(element).focus();
}

Youtube = {
    width:300,
    height:210,
    showPlayer:function(url,id){
      url = this.parseUrl(url);
      if(!url)return;
      var container = document.getElementById(id);
      try{
        var urlatual = container.getElementsByTagName('embed').item(0);
        urlatual = urlatual.src;
        if(urlatual == url)return;
      }catch(e){

      }
      container.innerHTML = this._showPlayer(url);
    },
    _showPlayer:function(url){
      var ret= '<object width="'+this.width+'" height="'+this.height+'">'+
                '<param name="movie" value='+url+'>'+
                '</param><param name="allowFullScreen" value="true"></param>'+
                '<param name="wmode" value="transparent" />'+
                '<param name="allowscriptaccess" value="always"></param>'+
                '<embed wmode="transparent" src="'+url+'" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="'+this.width+'" height="'+this.height+'">'+
            '</embed>'+
         '</object>  ';
     return ret;
    }
    ,
    parseUrl:function(url){
       var reg = /http:\/\/[^\"\']+/;
       var url = reg.exec(url);
       url = url?url[0]:'';
       url = url.replace('watch?v=', 'v/');
       url = url.split('&');
       url = url[0];
       url = url?url + "&hl=pt-BR&fs=1":null;

       return url;
    }

}
