///////////////////////////////////////////
//    CONTA   -  VALIDA CAMPOS  OK
///////////////////////////////////////////
function submitConta()
{
   var nome_mensagem = "";
   var email_mensagem = "";
   var senha_mensagem = "";
   var nova_mensagem = "";
   var confirma_mensagem = "";
   var validado = true;

   if(document.forms['conta'].nome.value == "")
   {
      validado = "false";
      nome_mensagem = '- O campo "Nome" deve estar selecionado!\n';
   }

   if(document.forms['conta'].email.value == "")
   {
      validado = "false";
      email_mensagem = '- O campo "E-mail" deve estar preenchido!\n';
   }

   if(document.forms['conta'].senha.value == "" || document.forms['conta'].senha.value.length < 5)
   {
      validado = "false";
      senha_mensagem = '- O campo "Senha Atual" deve estar preenchido e possuir mais que 5 caracteres!\n';
   }

   if(document.forms['conta'].nova.value != "" || document.forms['conta'].confirma.value !="" )
   {
      if(document.forms['conta'].nova.value.length < 5 || document.forms['conta'].confirma.value.length < 5)
      {
         validado = "false";
         nova_mensagem = '- Os campos "Nova Senha" e "Repetir Nova Senha" devem possuir no mínimo 5 caracteres!\n';
      }
      
      if(document.forms['conta'].nova.value != document.forms['conta'].confirma.value)
      {
         validado = "false";
         confirma_mensagem = '- Os campos "Nova Senha" e "Repetir Nova Senha" devem estar preenchidos com a mesma senha!\n';
      }
   }

   if(validado=="false")
   {
      alert("Atenção:\n"+nome_mensagem+email_mensagem+senha_mensagem+nova_mensagem+confirma_mensagem);
      return false
   }
   else
   {
      return true;
   }
}

///////////////////////////////////////////
//    MUDA CATEGORIA  - VALIDA CAMPOS
///////////////////////////////////////////
function submitCategoria()
{
   if(document.forms['categoria'].categoria_id.selectedIndex != "")
   {
      document.forms['categoria'].submit();
   }
}


/////////////////////////////////////////// ////
//    CATEGORIA CADASTRO     - VALIDA CAMPOS OK
////////////////////////////////////////////////
function submitFormCadastrarCategoria()
{
   var nome_mensagem = "";
   var validado = true;

   updateRTE('tabela');

   if(document.forms['cadastrar_categoria'].nome.value == "")
   {
      validado = "false";
      nome_mensagem = '- O campo "Nome da Categoria" deve estar preenchido!\n';
   }
   
   if(validado=="false")
   {
      alert("Atenção:\n"+nome_mensagem);
      return false
   }
   else
   {
      escapeVal(document.forms['cadastrar_categoria'].tabela,'');
      return true;
   }
}

///////////////////////////////////////////
//    CATEGORIA ALTERAR     - VALIDA CAMPOS
///////////////////////////////////////////
function submitFormAlterarCategoria()
{
   var nome_mensagem = "";
   var validado = true;

   updateRTE('tabela');

   if(document.forms['alterar_categoria'].nome.value == "")
   {
      validado = "false";
      nome_mensagem = '- O campo "Nome da Categoria" deve estar preenchido!\n';
   }

   if(validado=="false")
   {
      alert("Atenção:\n"+nome_mensagem);
      return false
   }
   else
   {
      escapeVal(document.forms['alterar_categoria'].tabela,'');
      return true;
   }
}

///////////////////////////////////////////
//    SUB-CATEGORIA ALTERAR     - VALIDA CAMPOS
///////////////////////////////////////////
function submitFormAlterarSubCategoria()
{
   var nome_mensagem = "";
   var validado = true;

   if(document.forms['alterar_subcategoria'].nome.value == "")
   {
      validado = "false";
      nome_mensagem = '- O campo "Sub-Categoria" deve estar preenchido!\n';
   }

   if(validado=="false")
   {
      alert("Atenção:\n"+nome_mensagem);
      return false
   }
   else
   {
      return true;
   }
}

//##########################################################################################################
///////////////////////////////////////////
//    PRODUTO CADASTRAR     - VALIDA CAMPOS
///////////////////////////////////////////
function submitFormCadastrarProduto()
{
   var nome_mensagem = "";
   var categoria_mensagem = "";
   var subcategoria_mensagem = "";
   var imagem1_mensagem = "";
   var imagem2_mensagem = "";
   var imagem3_mensagem = "";
   var imagem4_mensagem = "";
   var validado = true;

   updateRTE('tabela');

   if(document.forms['cadastrar_produto'].nome.value == "")
   {
      validado = "false";
      nome_mensagem = '- O campo "Nome" deve estar preenchido!\n';
   }

   if(document.forms['cadastrar_produto'].categoria.selectedIndex == "")
   {
      validado = "false";
      categoria_mensagem = '- O campo "Categoria" deve estar selecionado!\n';
   }

   if(document.forms['cadastrar_produto'].subcategoria.selectedIndex == "")
   {
      validado = "false";
      subcategoria_mensagem = '- O campo "Sub-Categoria" deve estar selecionado!\n';
   }
   
   if(document.forms['cadastrar_produto'].descricao1.value != "" && document.forms['cadastrar_produto'].imagem1.value == "")
   {
      validado = "false";
      imagem1_mensagem = '- O campo "Imagem 1" deve estar preenchido! \n';
   }
   
   if(document.forms['cadastrar_produto'].descricao2.value != "" && document.forms['cadastrar_produto'].imagem2.value == "")
   {
      validado = "false";
      imagem2_mensagem = '- O campo "Imagem 2" deve estar preenchido! \n';
   }
   
   if(document.forms['cadastrar_produto'].descricao3.value != "" && document.forms['cadastrar_produto'].imagem3.value == "")
   {
      validado = "false";
      imagem3_mensagem = '- O campo "Imagem 3" deve estar preenchido! \n';
   }
   
   if(document.forms['cadastrar_produto'].descricao_tecnica.value != "" && document.forms['cadastrar_produto'].imagem_tecnica.value == "")
   {
      validado = "false";
      imagem4_mensagem = '- O campo "Imagem 4" deve estar preenchido! \n';
   }

   if(validado=="false")
   {
      alert("Atenção:\n"+nome_mensagem+categoria_mensagem+subcategoria_mensagem+imagem1_mensagem+imagem2_mensagem+imagem3_mensagem+imagem4_mensagem);
      return false
   }
   else
   {
      escapeVal(document.forms['cadastrar_produto'].tabela,'');
      return true;
   }
}

//##########################################################################################################
///////////////////////////////////////////
//    PRODUTO ALTERAR     - VALIDA CAMPOS
///////////////////////////////////////////
function submitFormAlterarProduto()
{
   var nome_mensagem = "";
   var categoria_mensagem = "";
   var subcategoria_mensagem = "";
   var imagem_mensagem = "";
   var validado = true;

   updateRTE('tabela');

   if(document.forms['alterar_produto'].nome.value == "")
   {
      validado = "false";
      nome_mensagem = '- O campo "Nome" deve estar preenchido!\n';
   }

   if(document.forms['alterar_produto'].categoria.selectedIndex == "")
   {
      validado = "false";
      categoria_mensagem = '- O campo "Categoria" deve estar selecionado!\n';
   }

   if(document.forms['alterar_produto'].subcategoria.selectedIndex == "")
   {
      validado = "false";
      subcategoria_mensagem = '- O campo "Sub-Categoria" deve estar selecionado!\n';
   }

   //if((document.forms['alterar_produto'].descricao_tecnica.value != "" || document.forms['alterar_produto'].verifica.value == "") && document.forms['alterar_produto'].imagem_tencica.value == "")
   //{
   //   validado = "false";
   //   imagem_mensagem = '- O campo "Imagem 4" deve estar preenchido! \n';
   //}

   if(validado=="false")
   {
      alert("Atenção:\n"+nome_mensagem+categoria_mensagem+subcategoria_mensagem+imagem_mensagem);
      return false
   }
   else
   {
      escapeVal(document.forms['alterar_produto'].tabela,'');
      return true;
   }
}

////////////////////////////////////////////////////////////////////////////
//     TEXTO REMOVE QUEBRA DE LINHAS    - PARA O EDITOR RTE
////////////////////////////////////////////////////////////////////////////
function escapeVal(textarea,replaceWith)
{
   //textarea is reference to that object, replaceWith is string that will replace the encoded return
   textarea.value = escape(textarea.value)
   //encode textarea string's carriage returns

   for(i=0; i<textarea.value.length; i++)
   {
      //loop through string, replacing carriage return encoding with HTML break tag

      if(textarea.value.indexOf("%0D%0A") > -1)
      {
         //Windows encodes returns as \r\n hex
         textarea.value=textarea.value.replace("%0D%0A",replaceWith)
      }
      else
         if(textarea.value.indexOf("%0A") > -1)
         {
            //Unix encodes returns as \n hex
            textarea.value=textarea.value.replace("%0A",replaceWith)
         }
         else
            if(textarea.value.indexOf("%0D") > -1)
            {
               //Macintosh encodes returns as \r hex
               textarea.value=textarea.value.replace("%0D",replaceWith)
            }

   }

   textarea.value=unescape(textarea.value)
   //unescape all other encoded characters
}

////////////////////////////////////////////////////////////////////////////
//     RPC
////////////////////////////////////////////////////////////////////////////

function callToServer(theFormName,sub) {
	if (!document.createElement) {return true};
	var IFrameDoc;

	// We'll build our URL by checking which state
	// has been selected in the drop down menu
	var stateEl = document.forms[theFormName].categoria
	var id_estado = stateEl.options[stateEl.selectedIndex].value
	if (id_estado=='')
   {
      var nomeBairro = document.forms.forms[theFormName].subcategoria
      for(i=nomeBairro.length-1; i>=0; i--)
      {
         nomeBairro.options[i] = null;
      }
      newOption = new Option("...","")
	   nomeBairro.options[nomeBairro.length] = newOption
      return false
   } // no state has been selected
   else {
   var URL = "?sistema=produtos&oper=subcategorias&categoria_id="+id_estado+sub+"&formulario="+theFormName}
	//provide a "loading" message
	///var responseMessage = document.getElementById('responseMessage');
	//responseMessage.style.display = 'inline';
	//responseMessage.innerHTML = 'Carregando...';

	if (!IFrameObj && document.createElement) {
		// create the IFrame and assign a reference to the
		// object to our global variable IFrameObj.
		// this will only happen the first time
		// callToServer() is called
		try {
			var tempIFrame=document.createElement('iframe');
			tempIFrame.setAttribute('id','RSIFrame');
			tempIFrame.style.border='0px';
			tempIFrame.style.width='0px';
			tempIFrame.style.height='0px';
			IFrameObj = document.body.appendChild(tempIFrame);
         //IFrameObj = document.frames['RSIFrame']
			if (document.frames) {
				// this is for IE5 Mac, because it will only
				// allow access to the document object
				// of the IFrame if we access it through
				// the document.frames array
				IFrameObj = document.frames['RSIFrame'];
			}
		} catch(exception) {
			// This is for IE5 PC, which does not allow dynamic creation
			// and manipulation of an iframe object. Instead, we'll fake
			// it up by creating our own objects.
			iframeHTML='<iframe id="RSIFrame" style="';
			iframeHTML+='border:0px;';
			iframeHTML+='width:0px;';
			iframeHTML+='height:0px;';
			iframeHTML+='"><\/iframe>';
			document.body.innerHTML+=iframeHTML;
			IFrameObj = new Object();
			IFrameObj.document = new Object();
			IFrameObj.document.location = new Object();
			IFrameObj.document.location.iframe = document.getElementById('RSIFrame');
			IFrameObj.document.location.replace = function(location) {
				this.iframe.src = location;
			}
		}
	}
	if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
		// we have to give NS6 a fraction of a second
		// to recognize the new IFrame
		setTimeout('callToServer("'+theFormName+'")',10);
		return false;
	}
	var ie=navigator.userAgent.indexOf  ("Opera")==-1

   if(ie==false)
   {
     IFrameDoc = document.getElementById("RSIFrame");
   }
   else
   {
      if (IFrameObj.contentDocument) {
		 // For NS6
		 IFrameDoc = IFrameObj.contentDocument;
	   } else if (IFrameObj.contentWindow) {
		// For IE5.5 and IE6
		IFrameDoc = IFrameObj.contentWindow.document;
	   } else if (IFrameObj.document) {
		// For IE5
		IFrameDoc = IFrameObj.document;
	   } else {
		return true;
	  }
	}

	IFrameDoc.location = URL;

	return false;
}
// handleResponse is passed two parameters when called from the onload
// event of the pages loaded in the hidden IFRAME:
//	st: a string indicating which state is being loaded
//	doc: the document object of the page loaded in the IFRAME
function handleResponse(f,st, sb,doc) {
	// get a reference to the multiple select list, which we will populate
	// with the data from the document loaded in the IFRAME
	var namesEl = document.forms[f].subcategoria
   //alert("subcategoria"+sb);
	// clear earlier records from the multiple select list
	namesEl.length = 0

	// get a reference to the DIV containing the data for this state
	var dataEl = doc.getElementById(st)

	// get a reference to the collection of the children elements of
	// our DIV containing the data (this collection is the DIVs containing
	// the actual zip names)
	var namesColl = dataEl.childNodes

	// for easy scripting, assign the number of ZIP names for this state
	// to a variable
	var numNames = namesColl.length

	// iterate through the collection of zip Names and
	// create an option element for each one
	for (var q=0; q<numNames; q++)
   {
		if (namesColl[q].nodeType!=1)
         continue; // it's not an element node, let's skedaddle
		//var str = '' // used to store the text we'll use in the new option
		//str+= namesColl[q].id + ' ( '

      //########################
      var nome = namesColl[q].id
		// get a reference to the collection of the children elements of
		// this DIV (this collection contains the zip codes that fall under this zip name)

		var zipsColl = doc.getElementById(namesColl[q].id).childNodes
		var numZips = zipsColl.length

		// iterate through this collection of zips and each one to the string
		for (var r=0; r<numZips; r++) {
			if (zipsColl[r].nodeType!=1) continue; // it's not an element node, let's skedaddle
			//str += zipsColl[r].id + ' '
			var identificador = zipsColl[r].id
			}
		//str+= ')'
		// (1) addOptionNS(theForm)
      //function addOptionNS(theForm)
      //{
      //	var newOpt  = new Option("Three", "3");
	   //  var selLength = theForm.sel1.length;
	   //  theForm.sel1.options[selLength] = newOpt;
	   //  if (NS4) history.go(0);
      //}

      // (2) addOptionIE(theForm)
      //function addOptionIE(theForm)
      //{
	   //  var newOpt = document.createElement("OPTION");
	   //  newOpt.text= nome;
	   //  newOpt.value="3";
	    // theForm.sel1.add(newOpt);
      //}
		// create a new option element and add it to the zipNames form element
		if(identificador == sb)
			newOption = new Option(nome,identificador,true,true);
		else
			newOption = new Option(nome,identificador,false,false);
		//var newOption = new Option(nome,identificador)
		namesEl.options[namesEl.length] = newOption
	}

	//provide a "success" message
	//var responseMessage = document.getElementById('responseMessage');
	//responseMessage.innerHTML = 'loaded records from <a href="'+doc.location+'">this external file<\/a>.';
}

function espcallToServer(theFormName,sub) {
	if (!document.createElement) {return true};
	var IFrameDoc;

	// We'll build our URL by checking which state
	// has been selected in the drop down menu
	var stateEl = document.forms[theFormName].categoria
	var id_estado = stateEl.options[stateEl.selectedIndex].value
	if (id_estado=='')
   {
      var nomeBairro = document.forms.forms[theFormName].subcategoria
      for(i=nomeBairro.length-1; i>=0; i--)
      {
         nomeBairro.options[i] = null;
      }
      newOption = new Option("...","")
	   nomeBairro.options[nomeBairro.length] = newOption
      return false
   } // no state has been selected
   else {
   var URL = "?sistema=produtos&oper=subcategoriasesp&categoria_id="+id_estado+sub+"&formulario="+theFormName}
	//provide a "loading" message
	///var responseMessage = document.getElementById('responseMessage');
	//responseMessage.style.display = 'inline';
	//responseMessage.innerHTML = 'Carregando...';

	if (!IFrameObj && document.createElement) {
		// create the IFrame and assign a reference to the
		// object to our global variable IFrameObj.
		// this will only happen the first time
		// callToServer() is called
		try {
			var tempIFrame=document.createElement('iframe');
			tempIFrame.setAttribute('id','RSIFrame');
			tempIFrame.style.border='0px';
			tempIFrame.style.width='0px';
			tempIFrame.style.height='0px';
			IFrameObj = document.body.appendChild(tempIFrame);
         //IFrameObj = document.frames['RSIFrame']
			if (document.frames) {
				// this is for IE5 Mac, because it will only
				// allow access to the document object
				// of the IFrame if we access it through
				// the document.frames array
				IFrameObj = document.frames['RSIFrame'];
			}
		} catch(exception) {
			// This is for IE5 PC, which does not allow dynamic creation
			// and manipulation of an iframe object. Instead, we'll fake
			// it up by creating our own objects.
			iframeHTML='<iframe id="RSIFrame" style="';
			iframeHTML+='border:0px;';
			iframeHTML+='width:0px;';
			iframeHTML+='height:0px;';
			iframeHTML+='"><\/iframe>';
			document.body.innerHTML+=iframeHTML;
			IFrameObj = new Object();
			IFrameObj.document = new Object();
			IFrameObj.document.location = new Object();
			IFrameObj.document.location.iframe = document.getElementById('RSIFrame');
			IFrameObj.document.location.replace = function(location) {
				this.iframe.src = location;
			}
		}
	}
	if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
		// we have to give NS6 a fraction of a second
		// to recognize the new IFrame
		setTimeout('callToServer("'+theFormName+'")',10);
		return false;
	}
	var ie=navigator.userAgent.indexOf  ("Opera")==-1

   if(ie==false)
   {
     IFrameDoc = document.getElementById("RSIFrame");
   }
   else
   {
      if (IFrameObj.contentDocument) {
		 // For NS6
		 IFrameDoc = IFrameObj.contentDocument;
	   } else if (IFrameObj.contentWindow) {
		// For IE5.5 and IE6
		IFrameDoc = IFrameObj.contentWindow.document;
	   } else if (IFrameObj.document) {
		// For IE5
		IFrameDoc = IFrameObj.document;
	   } else {
		return true;
	  }
	}

	IFrameDoc.location = URL;

	return false;
}
// handleResponse is passed two parameters when called from the onload
// event of the pages loaded in the hidden IFRAME:
//	st: a string indicating which state is being loaded
//	doc: the document object of the page loaded in the IFRAME
function esphandleResponse(f,st, sb,doc) {
	// get a reference to the multiple select list, which we will populate
	// with the data from the document loaded in the IFRAME
	var namesEl = document.forms[f].subcategoria
   //alert("subcategoria"+sb);
	// clear earlier records from the multiple select list
	namesEl.length = 0

	// get a reference to the DIV containing the data for this state
	var dataEl = doc.getElementById(st)

	// get a reference to the collection of the children elements of
	// our DIV containing the data (this collection is the DIVs containing
	// the actual zip names)
	var namesColl = dataEl.childNodes

	// for easy scripting, assign the number of ZIP names for this state
	// to a variable
	var numNames = namesColl.length

	// iterate through the collection of zip Names and
	// create an option element for each one
	for (var q=0; q<numNames; q++)
   {
		if (namesColl[q].nodeType!=1)
         continue; // it's not an element node, let's skedaddle
		//var str = '' // used to store the text we'll use in the new option
		//str+= namesColl[q].id + ' ( '

      //########################
      var nome = namesColl[q].id
		// get a reference to the collection of the children elements of
		// this DIV (this collection contains the zip codes that fall under this zip name)

		var zipsColl = doc.getElementById(namesColl[q].id).childNodes
		var numZips = zipsColl.length

		// iterate through this collection of zips and each one to the string
		for (var r=0; r<numZips; r++) {
			if (zipsColl[r].nodeType!=1) continue; // it's not an element node, let's skedaddle
			//str += zipsColl[r].id + ' '
			var identificador = zipsColl[r].id
			}
		//str+= ')'
		// (1) addOptionNS(theForm)
      //function addOptionNS(theForm)
      //{
      //	var newOpt  = new Option("Three", "3");
	   //  var selLength = theForm.sel1.length;
	   //  theForm.sel1.options[selLength] = newOpt;
	   //  if (NS4) history.go(0);
      //}

      // (2) addOptionIE(theForm)
      //function addOptionIE(theForm)
      //{
	   //  var newOpt = document.createElement("OPTION");
	   //  newOpt.text= nome;
	   //  newOpt.value="3";
	    // theForm.sel1.add(newOpt);
      //}
		// create a new option element and add it to the zipNames form element
		if(identificador == sb)
			newOption = new Option(nome,identificador,true,true);
		else
			newOption = new Option(nome,identificador,false,false);
		//var newOption = new Option(nome,identificador)
		namesEl.options[namesEl.length] = newOption
	}

	//provide a "success" message
	//var responseMessage = document.getElementById('responseMessage');
	//responseMessage.innerHTML = 'loaded records from <a href="'+doc.location+'">this external file<\/a>.';
}

///////////////////////////////////////////
//    ACESSORIO CADASTRO     - VALIDA CAMPOS
///////////////////////////////////////////
function submitFormCadastrarAcessorio()
{
   var nome_mensagem = "";
   var descricao_mensagem = "";
   var imagem_mensagem = "";
   var validado = true;

   if(document.forms['cadastrar_acessorio'].nome.value == "")
   {
      validado = "false";
      nome_mensagem = '- O campo "Nome do Acessório" deve estar preenchido!\n';
   }

   if(document.forms['cadastrar_acessorio'].descricao.value == "")
   {
      validado = "false";
      descricao_mensagem = '- O campo "Descrição" deve estar preenchido!\n';
   }

   if(document.forms['cadastrar_acessorio'].descricao_imagem.value != "" && document.forms['cadastrar_acessorio'].imagem.value == "")
   {
      validado = "false";
      imagem_mensagem = '- O campo "Imagem" deve estar preenchido! \n';
   }

   if(validado=="false")
   {
      alert("Atenção:\n"+nome_mensagem+descricao_mensagem+imagem_mensagem);
      return false
   }
   else
   {
      return true;
   }
}

///////////////////////////////////////////
//    ACESSORIO CADASTRO     - VALIDA CAMPOS
///////////////////////////////////////////
function submitFormAlterarAcessorio()
{
   var nome_mensagem = "";
   var descricao_mensagem = "";
   var validado = true;

   if(document.forms['cadastrar_acessorio'].nome.value == "")
   {
      validado = "false";
      nome_mensagem = '- O campo "Nome do Acessório" deve estar preenchido!\n';
   }

   if(document.forms['cadastrar_acessorio'].descricao.value == "")
   {
      validado = "false";
      descricao_mensagem = '- O campo "Descrição" deve estar preenchido!\n';
   }

   if(validado=="false")
   {
      alert("Atenção:\n"+nome_mensagem+descricao_mensagem);
      return false
   }
   else
   {
      return true;
   }
}


///////////////////////////////////////////
//    IMAGEM CADASTRO     - VALIDA CAMPOS
///////////////////////////////////////////
function submitFormCadastrarImagem()
{
   var imagem_mensagem = "";
   var imagem1_mensagem = "";
   var validado = true;

   if(document.forms['cadastrar_imagem'].descricao.value != "" && document.forms['cadastrar_imagem'].imagem.value == "")
   {
      validado = "false";
      imagem_mensagem = '- O campo "Imagem" e "Descrição" devem estar preenchido! \n';
   }

   if(document.forms['cadastrar_imagem'].imagem.value == "")
   {
      validado = "false";
      imagem1_mensagem = '- O campo "Imagem" deve estar preenchido! \n';
   }
   if(validado=="false")
   {
      alert("Atenção:\n"+imagem_mensagem+imagem1_mensagem);
      return false
   }
   else
   {
      return true;
   }
}

