/*-------------------------------------------------------------------------
ATRIBUI EVENTOS PARA FORMULARIO
@author Moisés Mosele 07/07/2011
---------------------------------------------------------------------------*/
$(function(){
	var strings = {
	    'BR' : {
	            'realizando_busca' : 'Realizando a busca, por favor aguarde'
		},
	    'EN' : {
	            'realizando_busca' : 'Searching, please wait'
			},
		'ES' : {
		        'realizando_busca' : 'Buscando, por favor espere'
			}
	};

	$( 'a.TextoPreto' )
		.live( 'click', function(){
			$( 'a.TextoPreto' )
				.removeClass( 'selected' )
			;

			$( this )
				.addClass( 'selected' )
			;
		})
	;

	$( 'form#consulta' )
		.prepend(
			'<div id="carregando">' +
				'<div id="container">' +
					'<div id="txt">' + strings[language]['realizando_busca'] + '</div>' +
				'</div>' +
			'</div>' )
			.end()

		.find( ':button' )
			.bind( 'click', function( event ){
				$( '#carregando' )
					.fadeIn()
				;
			})
			.end()

		.find( ':input[type="text"]' )
			.bind( 'keydown', function( event ){
				if( event.which == 13 ){  // enter pressed
					$( '#carregando' )
						.fadeIn()
					;
				}
			})
			.unbind( 'focus' )
			/*.bind( 'focus keyup', function(){
				if( $(this).val() == '' ){
					var iframe = $( 'iframe#about' );
					iframe
						.attr( 'src', 'cat_default.php?idVer=' + iframe.attr( 'class' ) )
					;
				}
			})*/
	;

	$( '#about' )
		.bind( 'load', function(){
			$( '#carregando' )
				.fadeOut()
			;
		})
	;

	$( 'iframe#detalhe' )
		.bind( 'load', function(){
			var title = $( this ).contents().find( 'td.TextoAmarelo' );
			title = $( '<div class="TextoAmarelo" style="margin-top:2px; float:left; color:#CC6600;">' + ( title.length ? title.html() : '' ) + '</div>' );

			$( 'img[src="/img/cat_03.gif"]' )
				.css({
					'float'	:	'left'
				})
				.next( 'div' )
					.remove()
					.end()
				.after( title )
			;

		})
	;
});

/**
 * seta o valor do campo 'busca completa' da busca rápida e efetua a busca
 */
function busca_rapida( busca ){
	$( 'form#consulta' )
		.find( ':input[name="vfDes_palavra_chave"]' )
			.val( busca )
			.end()
		.find( ':button.ClassBoxSearch' )
			.trigger( 'click' )
			.end()
		// sim, repete isso aqui:
		.find( ':input[name="vfDes_palavra_chave"]' )
			.val( busca )
			.end()
	;
}


/*-------------------------------------------------------------------------
DISPARA PÁGINA DE INICIO -> HOME
---------------------------------------------------------------------------*/

function AbreIntro() {
	janela= window.open("home.php","home","width=770,height=485,left="+((screen.Width - 770)/2)+",top="+((screen.availHeight - 485)/2)+"")
}

/*-------------------------------------------------------------------------
IFRAME CATALOGO
---------------------------------------------------------------------------*/
function goTo(where,who) {
	var oObj;
	oObj = document.getElementById(who);
	oObj.src = where;
}

function goToParent(where,who) {
	var oObj;
	oObj = this.parent.document.getElementById(who);
	oObj.src = where;
}

/*-------------------------------------------------------------------------
SWAP IMAGE -> TROCA DE IMAGENS / MOUSE OVER / VALIDA FORM
---------------------------------------------------------------------------*/

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_validateForm(args) { //v4.0
  var i,p,q,nm,test,num,min,max,errors='';//,args=MM_validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
    if (val) { nm=val.name; if ((val=val.value)!="") {
		if (test.indexOf('isEmail')!=-1) {
	      	p=val.indexOf('@');
	      	if (p<1 || p==(val.length-1)) {
	      		if (test == 'RisEmail')
	        		errors+='- '+nm+' precisa ser um endereço de e-mail válido.\n';
	        	if (test == 'EisEmail')
	        		errors+='- '+nm+' the e-mail address must be valid.\n';
	        	if (test == 'SisEmail')
	        		errors+='- '+nm+' la dirección del e-mail debe ser válida.\n';
	      	}
	    } else {
	      	if ((test!='R') & (test!='E') & (test!='S')) {
	      		num = parseFloat(val);
	        	if (isNaN(val)) {
		      		if (test == 'RisNumber')
		        		errors+='- '+nm+' precisa ser um número.\n';
		        	if (test == 'EisNumber')
		        		errors+='- '+nm+' must be a number.\n';
		        	if (test == 'SisNumber')
		        		errors+='- '+nm+' debe ser un número.\n';

		        	if (test == 'RisSetor' && val == "Selecione um setor")
		        		errors+='- '+nm+' é de preenchimento obrigatório.\n';
		        	if (test == 'EisSetor' && val == "Select a department")
		        		errors+='- '+nm+' is a mandatory field.\n';
		        	if (test == 'SisSetor' && val == "Seleccione un sector")
		        		errors+='- '+nm+' és un campo obligatorio.\n';
	        	}
	        	if (test.indexOf('inRange') != -1) {
	        		p=test.indexOf(':');
	          		min=test.substring(8,p); max=test.substring(p+1);
	          		if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
	    		}
	      	}
	    }
     } else {
    	if (test.charAt(0) == 'R') errors += '- '+nm+' é de preenchimento obrigatório.\n';
    	if (test.charAt(0) == 'E') errors += '- '+nm+' is a mandatory field.\n';
    	if (test.charAt(0) == 'S') errors += '- '+nm+' és un campo obligatorio.\n';
     }
    }
  }
  if (errors) alert('Os seguintes erros ocorreram:\n'+errors);
  document.MM_returnValue = (errors == '');
}

/*-------------------------------------------------------------------------
MOSTRA SEARCH
---------------------------------------------------------------------------*/


function MM_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
//    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
//    obj.visibility=v; }
    if (obj.style) {
		obj=obj.style;
		v=(obj.visibility=='visible')?'hidden':'visible';
	}
    obj.visibility=v; }
}

/*-------------------------------------------------------------------------
TROCA BACKGROUND DAS CELULAS
---------------------------------------------------------------------------*/

function mOvr (alvo, cor) {
  alvo.bgColor = cor;
}

function mOut (alvo, cor) {
  alvo.bgColor = cor;
}

/*-------------------------------------------------------------------------
FUNÇÕES GENÉRICAS
---------------------------------------------------------------------------*/

function abreJanela(url,att) {
	window.open(url,'janela',att);
}

function enviaForm() {
	oArgs = enviaForm.arguments;
	aArgs = new Array();
	for(i=0; i<oArgs.length;i++) {
		aArgs[i] = oArgs[i];
	}
	formName = aArgs.shift();
	oForm = document.getElementById(formName);

	MM_validateForm(aArgs);

	if(document.MM_returnValue) {
		oForm.submit();
	}
}

function limpaForm(form) {
	oForm = document.getElementById(form);
	oForm.reset();
}
/*--------------------------------------------------------------------------------------
  FIGURAS ALEATÓRIA -> Front Page
---------------------------------------------------------------------------------------*/
/*
var howMany = 4;
var image = new Array(howMany)

image[0]='01'
image[1]='02'
image[2]='03'
image[3]='04'


function rndnumber(){
var randscript = -1
while (randscript < 0 || randscript > howMany || isNaN(randscript)){
randscript = parseInt(Math.random()*(howMany))
}
return randscript
}

quo = rndnumber()
quox = image[quo]
*/

/*--------------------------------------------------------------------------------------
FUNÇÕES DA PARTE DO CATÁLOGO - ZM - EQUIPE DE DESENVOLVIMENTO
--------------------------------------------------------------------------------------*/

function setTipo()
{
	try{
		form = parent.document.getElementById('consulta');
		if (document.getElementById('vfTip_codigo')) {
			tipo = document.getElementById('vfTip_codigo').value;
		} else {
			tipo = "";
		}

		if (parent.document.getElementById('idVer')) {
			versao = parent.document.getElementById('idVer').value;
		} else {
			versao = "BR";
		}

		if (parent.document.getElementById('vfConformados')) {
			conformados = parent.document.getElementById('vfConformados').value;
		} else {
			conformados = "";
		}

		if(conformados == 0){
		parent.document.getElementById('vfDes_marca').value = '';
		parent.document.getElementById('vfCodigo_livre').value = '';
		parent.document.getElementById('vfDes_palavra_chave').value = '';
		}

		iframeMarca = parent.document.getElementById("ifMarca");
		iframeDetalhe = parent.document.getElementById("detalhe");
		iframeAbout = parent.document.getElementById("about");

		if (conformados == 0)
			form.vfCodigo_livre.value = '';
		if (tipo=="4") {
			iframeAbout.src = 'ifConformados.php?vfTip_codigo='+tipo+'&idVer='+versao;
			iframeDetalhe.src = 'cat_default.php?idVer='+versao;
			document.getElementById('vfDes_marca').value = 0;
			document.getElementById('vfDes_marca').disabled = true;
			var radio = document.forms['ifConsulta'].elements['vfQual'];
			radio[1].disabled = true;
			radio[2].disabled = true;
			radio[3].disabled = true;
			document.getElementById('vfCodigo_motor').disabled = true;
		} else if (tipo!="0") {
			iframeMarca.src = 'ifMarca.php?vfTip_codigo='+tipo+'&idVer='+versao;
			document.getElementById('vfDes_marca').disabled = false;
			var radio = document.forms['ifConsulta'].elements['vfQual'];
			radio[1].disabled = false;
			radio[2].disabled = false;
			radio[3].disabled = false;
			document.getElementById('vfCodigo_motor').disabled = false;
			parent.document.consulta.submit();
		}
	}catch(e){
		alert(e);
	}
}

/*
  Verifica se a tecla pressionada é enter se form submete o formulário
*/
/* JOB: 15312 / {244-0-07} - @des. Foi adicionado o parametro "e" (evento) .... e uma verificação de browser (whichCode) ... */
function getTecla(form,e){
  var whichCode = (window.Event) ? e.which : e.keyCode;
  if(whichCode == 13){
    document.getElementById(form).submit();
  }
}

function getTeclaCatalogo(form,e, clean){
	  var whichCode = e.keyCode;
	  if(whichCode == 13){
		document.getElementById(clean).value='';
		buscaProd();
	  }
}

function setMarca()
{
	try{
		form = document.ifConsulta;
		tipo = form.vfTip_codigo.value;
		marc = form.vfDes_marca.value;
                versao = form.idVer.value;

		parent.document.getElementById('vfCodigo_livre').value = '';
		parent.document.getElementById('vfDes_palavra_chave').value = '';
		parent.document.getElementById('vfCodigo_motor').value = '';

		if (marc!="0")
		{
			form.action = 'ifMarca.php?vfTip_codigo='+tipo+'&vfDes_marca='+marc+'&idVer='+versao+'&vfSubmit=1';
			form.submit();
		}
	}catch(e){
		alert(e);
	}
}

function setCodigo(){
	try{
		pai = parent.document.consulta;
		fil = document.ifConsulta;
		pai.vfDes_marca.value	 = fil.vfDes_marca.value;

		if (fil.vfQual[0].checked==true)
			pai.vfQual.value		 = fil.vfQual[0].value;
		else if (fil.vfQual[0].checked==true)
			pai.vfQual.value		 = fil.vfQual[1].value;
		else
			pai.vfQual.value		 = fil.vfQual[2].value;

		//pai.vfQual.value = fil.vfQual[0].value;
		pai.vfCodigo_motor.value = fil.vfCodigo_motor.value;
		parent.document.getElementById('vfCodigo_livre').value = '';
		parent.document.getElementById('vfDes_palavra_chave').value = '';
		pai.submit();
	}catch(e){
		alert(e);
	}
}

function buscaProd() {
	form = document.consulta;
	form.submit();
}

function listaProd(){
	form = parent.document.getElementById('consulta');
	parent.document.getElementById('vfTip_codigo').value = document.getElementById('vfTip_codigo').value;
	fil = document.getElementById('ifConsulta');
	form.vfDes_marca.value = fil.vfDes_marca.value;
	form.vfCodigo_motor.value = fil.vfCodigo_motor.value;
	/*if (fil.vfQual[0].checked == true) {
		form.vfQual.value = fil.vfQual[0].value;
		//alert("dentro 0: " + fil.vfQual[0].value);
	} else {
		if (fil.vfQual[1].checked == true) {
			form.vfQual.value = fil.vfQual[1].value;
			//alert("dentro 1: " +fil.vfQual[1].value);
		} else {
			//if (fil.vfQual[2].checked == true) {
				form.vfQual.value = fil.vfQual[2].value;
				//alert("dentro 2: " +fil.vfQual[2].value);
			//}
		}
	}*/

	form.vfQual.value = document.getElementById('vfQual').value;
	//setTimeout("form.submit();", 1000);
	form.submit();
}
