/*
 * @Pedro de la Lastra
 *  DHTML: function include(), function HideTab(), ChangeTab(), ChangeClass()
 *  AJAX: function loadSection(), function loadNews(), function loadOffers(), loadMap(), loadDetails()
 */
var oRotator = '';

function include(file) {
  var script  = document.createElement('script');
  script.src  = file;
  script.type = 'text/javascript';

  document.getElementsByTagName('head')[0].appendChild(script);
}

function URLDecode( val )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = val;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   
   return plaintext;
}

/* Ajax function */
function swapMenu(sItem, sClassOn, sClassOff){
	$(hMenu.get("id")).className = hMenu.get("class");
	$(sItem).className = sClassOn;
	hMenu.set("id", sItem);
	hMenu.set("class", sClassOff);
}

function loadSection ( nSectionId, sClassOn, sClassOff, nMenuId )
{
	bFirstTime = false;
	var aArgs = loadSection.arguments;
	var hPar = $H({ section_id: aArgs[0], i: 0 });
	switch(true)
	{
		case (aArgs.length > 4):
			hPar.merge(aArgs[4]);
			break;
		case (aArgs.length > 2):
			swapMenu('menu_'+aArgs[3], aArgs[1], aArgs[2]);
			break;
	}

	//Oculta los menus especiales si es la home
	if(nSectionId == 1){
		$$('.special').invoke('hide');
	}
	else{
		$$('.special').invoke('show');
	}
	
	new Ajax.Updater('divContent', './inc/load_section.asp', {
	  method: 'post',
	  encoding: 'ISO-8859-1',
	  parameters: hPar.toObject()
	});	
//	xobj2.sendAndLoad("./includes/loadSeccion.inc.asp",vars,"POST");		
}

function loadMap ( nSectionId, i )
{
	new Ajax.Updater('divContent', './inc/load_map.asp', {
	  method: 'post',
	  encoding: 'ISO-8859-1',
	  parameters: { section_id: nSectionId, i: i }
	});	
}


function loadNews (tabu )
{
		var xobj2 = new LoadVars();
		var vars = new Object();
        vars.i = tabu;

        document.getElementById("contenido").innerHTML = "<div class='left-menu'>&nbsp;</div><div class='contenido-imagen' style='margin: 0 auto;' ><img src='./img/cargador.gif' width=32 height=32></div>";
		xobj2.onLoad=function(bool) 
		{
			//EN LA CARGA
			if (this.errorcr == 1) 
			  {
				alert(this.msg_error); 
			  }
			else
			  {
				document.getElementById("contenido").innerHTML = URLDecode(this.noticia);
			  }
		}
		
        

        var thetab=document.getElementById("maintab").getElementsByTagName("li")[tabu]
		ChangeTab (thetab);
     	xobj2.sendAndLoad("./includes/loadNoticia.inc.asp",vars,"POST");		
		
}

function loadOffers ( nSectionId, i )
{
	    
	new Ajax.Updater('divContent', './inc/load_offer.asp', {
	  method: 'post',
	  encoding: 'windows-1252',
	  parameters: { section_id: nSectionId, i: i }
	});	
	
}

function loadDetails ( nSectionId, nOfferId, tabu )
{
	    
/*		var xobj2 = new LoadVars();
		var vars = new Object();
        vars.idSeccio = idSeccio;
		vars.idOferta = idOferta;
*/	
        $("divContent").innerHTML = "<div class='left-menu'>&nbsp;</div><div class='contenido-imagen' style='margin: 0 auto;' ><img src='./img/cargador.gif' width=32 height=32></div>";
		new Ajax.Updater('divContent', './inc/load_details.asp', {
		  method: 'post',
		  parameters: { section_id: nSectionId, offer_id: nOfferId },
		  onComplete: function(){
			if (window.nueva_consulta !== 1)
			{
				if (tabu==-1)
				{
					HideTabs();
				}
				else
				{
					var thetab=document.getElementById("maintab").getElementsByTagName("li")[tabu];
					ChangeTab (thetab);			
				}
			}//if nueva_consulta
			}
		});	
/*		xobj2.onLoad=function(bool) 
		{
			//EN LA CARGA
			if (this.errorcr == 1) 
			  {
				alert(this.msg_error); 
			  }
			else
			  {
				document.getElementById("contenido").innerHTML = URLDecode(this.ofertas);
			  }
		}
*/		
        

//         xobj2.sendAndLoad("./includes/loadDetalle.inc.asp",vars,"POST");		
		
}


function HideTabs ()
{
   var e = document.getElementsByTagName('li');
   for(var i=0;i<e.length;i++)
   {
        e[i].className = "";	 
   }
}

function ChangeTab ( el )
{
  if ( el )
   {
   var e = document.getElementsByTagName('li');
   for(var i=0;i<e.length;i++)
   {
      if ( e[i].className == "selected" )
        e[i].className = "";	 
   }
   el.className = "selected";
	
   }
}


function changeClass ( el, class1, class2 )
{
  if ( el )
   {
   var e = document.getElementsByTagName('A');
   var html = "";   
   for(var i=0;i<e.length;i++)
   {
      if ( e[i] != el && e[i].className == class1 )
        e[i].className = class2;	 
      html = html + e[i].className + " -";	  
   }
   el.className = ( el.className == class1 ? class2 : class1 );
	
   }
}



// ---- envío de solicitud de catálogo
function confirmSubmission(sContent){
	$('Content').innerHTML = sContent.responseText;
}

function sendForm()
{
	frm = document.frma
	checkV = 1
	if (!validarNIF(frm.nif.value)) {frm.nif.focus(); checkV=0; alert(ArrayErr[9]); return;}		 	
	if (frm.nombre.value=="") {frm.nombre.focus(); checkV=0; alert(ArrayErr[0]); return;}	
	if (frm.apellidos.value=="") {frm.apellidos.focus(); checkV=0; alert(ArrayErr[1]); return;}	
	if (frm.empresa.value=="") {frm.empresa.focus(); checkV=0; alert(ArrayErr[2]); return;}
	if (frm.direccion.value=="") {frm.direccion.focus(); checkV=0; alert(ArrayErr[8]); return;}		
	if (!validarCP(frm.codigopostal.value)) {frm.codigopostal.focus(); checkV=0; alert(ArrayErr[6]); return;}
	if (frm.poblacion.value=="") {frm.poblacion.focus(); checkV=0; alert(ArrayErr[5]); return;}
	if (!validarEmail(frm.email.value)) {frm.email.focus(); checkV=0; alert(ArrayErr[3]); return;}		
	if (!validarTelefon(frm.telefono.value)) {frm.telefono.focus(); checkV=0; alert(ArrayErr[4]); return;}		
	if (!validarTelefon(frm.fax.value)) {frm.fax.focus(); checkV=0; alert(ArrayErr[7]); return;}		
	if (!frm.aceptaprot.checked) {frm.aceptaprot.focus(); checkV=0; alert(ArrayErr[10]); return; }
	if (checkV==1) {
		$('frma').request({
			encoding: 'ISO-8859-15',
			onComplete: function(transport){ 
		  		confirmSubmission(transport) ;
			}
		})
	}
	//if (checkV==1) {alert("OK")}
}

function sendAMForm()
{
	frm = document.frma
	checkV = 1
	if (frm.nombre.value=="") {frm.nombre.focus(); checkV=0; alert(ArrayErr[0]); return;}	
	if (frm.apellidos.value=="") {frm.apellidos.focus(); checkV=0; alert(ArrayErr[1]); return;}	
	if (frm.empresa.value=="") {frm.empresa.focus(); checkV=0; alert(ArrayErr[2]); return;}
	if (!validarEmail(frm.email.value)) {frm.email.focus(); checkV=0; alert(ArrayErr[3])}		
	if (frm.localidad.value=="") {frm.localidad.focus(); checkV=0; alert(ArrayErr[5]); return;}
	if (!validarCP(frm.codigopostal.value)) {frm.codigopostal.focus(); checkV=0; alert(ArrayErr[6]); return;}
	if (frm.pais.value=="") {frm.pais.focus(); frm.pais.focus(); checkV=0; alert(ArrayErr[8]); return;}
	if (!validarTelefon(frm.telefono.value)) {frm.telefono.focus(); checkV=0; alert(ArrayErr[4]); return;}		
	if (!frm.aceptaprot.checked) {frm.aceptaprot.focus(); checkV=0; alert(ArrayErr[10]); return; }
	if (checkV==1) {
		$('frma').request({
			encoding: 'ISO-8859-15',
			onComplete: function(transport){ 
		  		confirmSubmission(transport) ;
			}
		})
	}
}



function sendFormCV()
{
	frm = document.frma
	checkV = 1
	if (frm.nombre.value=="") {frm.nombre.focus(); checkV=0; alert(ArrayErrCV[0]); return;}	
	if (frm.apellidos.value=="") {frm.apellidos.focus(); checkV=0; alert(ArrayErrCV[1]); return;}	
   if(!isDate(frm.FechaNacimiento.value)) {frm.FechaNacimiento.focus(); alert(ArrayErrCV[2]); return; }	
	if (frm.poblacion.value=="") {frm.poblacion.focus(); checkV=0; alert(ArrayErrCV[3]); return;}
	if (frm.direccion.value=="") {frm.direccion.focus(); checkV=0; alert(ArrayErrCV[4]); return;}		
	if (!validarCP(frm.codigopostal.value)) {frm.codigopostal.focus(); checkV=0; alert(ArrayErrCV[5]); return;}
	if (!validarTelefon(frm.telefono.value)) {frm.telefono.focus(); checkV=0; alert(ArrayErrCV[6]); return;}		
	if (!validarTelefon(frm.movil.value)) {frm.movil.focus(); checkV=0; alert(ArrayErrCV[7]); return;}		
	if (!validarEmail(frm.email.value)) {frm.email.focus(); checkV=0; alert(ArrayErrCV[8]); return;}		
	if (frm.experiencia.value=="") {frm.experiencia.focus(); checkV=0; alert(ArrayErrCV[9]); return;}
	if (!frm.aceptaprot.checked) {frm.aceptaprot.focus(); checkV=0; alert(ArrayErrCV[10]); return; }
	if (checkV==1) {
		$('frma').request({
			encoding: 'ISO-8859-15',
			onComplete: function(transport){ 
		  		confirmSubmission(transport) ;
			}
		})
	}
}

function sendSearch()
{
	frm = document.buscador
	checkV = 1
	if (frm.brand.value=="0") {frm.brand.focus(); checkV=0; alert(ArrayErrSer[0]); return;}	
	if (frm.model.value=="") {frm.model.focus(); checkV=0; alert(ArrayErrSer[1]); return;}	
	if (checkV==1) {frm.submit()}
}

//include('./js/language.js.asp');


function validarTelefon(valor) {
  var numTelf = valor;
  var longNum = numTelf.length;
  if (longNum==9)
   {
     var i;
	 for (i=0; i<9; i++) {
	  var c=numTelf.substring(i,i+1);
	  if (((c<"0")||(c>"9")))	   {	   return false;	   }
	 }
	 zzz=1;
	 return true;
   }
  else   {	return false;   }
}

function validarEmail(nom) {
	valor= nom.split("@")
	if(valor.length==2)
	{
			valor2= valor[1].split(".")
			if(valor2.length>1)
			{
				  return true;
			}
			else
			{
				  return false;
			}
	}
	else
	{
	  return false;
	}

}

function validarCP(valor) {
  var CP = valor;
  var longNum = CP.length;
  if (longNum==5)
   {
     var i;
	 for (i=0; i<5; i++) {
	  var c=CP.substring(i,i+1);
	  if (((c<"0")||(c>"9")))
	   {
	   return false;
	   }
	 }
	 zzz=1;
	 return true;
   }
  else
   {
	return false;
   }
}


function validarNIF(valor) {
	return true;
  var NIF = valor;
  var longNum = NIF.length;
  //miramos el primer caracter!
  if (((NIF.substring(0,1).toUpperCase()>="A")&&(NIF.substring(0,1).toUpperCase()<="Z")))//es un CIF o NIE
	   {
		  if (((NIF.substring(8,9).toUpperCase()=="K")||(NIF.substring(8,9).toUpperCase()=="L")||(NIF.charAt(8).toUpperCase()=="X")))  // es posible NIE
		   {
		     if ( !isNaN( parseInt(NIF.substring(1,7))) ) //si toe el resto son numeros!
			 {

				 tst=true
				 for (i=1; i<7; i++) {
				  var c=NIF.substring(i,i+1);
				  if (((c<"0")||(c>"9")))
				   {
				   tst=false;
				   }
				  }				  
				  return tst;

			 }
		     else{	 return false; }			//NO NIE CORRECTO!!		   
		   }
		   else //es UN CIF!!
		   {	 
		     if ( !isNaN( parseInt(NIF.substring(1,8))) ) //si toe el resto son numeros!
			 {
				 tst=true
				 for (i=1; i<8; i++) {
				  var c=NIF.substring(i,i+1);
				  if (((c<"0")||(c>"9")))
				   {
				   tst=false;
				   }
				  }				  
				  return tst;

			 }
		     else{	 return false; }			//NO NIF CORRECTO!!		   
		   } //FIN DEVALIDACION DE CIF!
	   }	
	   else //si el primero no es una letra!
	   {
		  if (((NIF.substring(8,9).toUpperCase()>="A")&&(NIF.substring(8,9).toUpperCase()<="Z")))  // es posible NIE
		   {
		     if ( !isNaN( parseInt(NIF.substring(0,7))) ) //si toe el resto son numeros!
			 {
				 tst=true
				 for (i=0; i<7; i++) {
				  var c=NIF.substring(i,i+1);
				  if (((c<"0")||(c>"9")))
				   {
				   tst=false;
				   }
				  }				  
				  return tst;
			 }
		     else{	 return false; }			//NO NIF CORRECTO!!		   
		   }
		     else{	 return false; }			//NO NIF CORRECTO!!		   	   
	   }
}




//***************************************************
//    FUNCION DE VALIDACION DE FECHAS
//***************************************************
function isDate(str) {
	if (str.length != 10) { return false }
	for (j=0; j<str.length; j++) {
		if ((j == 2) || (j == 5)) {
			if (str.charAt(j) != "/") { return false }
		} else {
			if ((str.charAt(j) < "0") || (str.charAt(j) > "9")) { return false }
		}
	}

var day = str.charAt(0) == "0" ? parseInt(str.substring(1,2)) : parseInt(str.substring(0,2));
var month = str.charAt(3) == "0" ? parseInt(str.substring(4,5)) : parseInt(str.substring(3,5));
var begin = str.charAt(6) == "0" ? (str.charAt(7) == "0" ? (str.charAt(8) == "0" ? 9 : 8) : 7) : 6;
var year = parseInt(str.substring(begin, 10));

if (day == 0) { return false }
if (month == 0 || month > 12) { return false }
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
	if (day > 31) { return false }
} else {
	if (month == 4 || month == 6 || month == 9 || month == 11) {
		if (day > 30) { return false }
	} else {
		if (year%4 != 0) {
			if (day > 28) { return false }
		} else {
			if (day > 29) { return false }
		}
	}
}
return true;
}
//***************************************************

function openFullWindow(sUrl){
	
	var sFeatures = "toolbar=0,status=0,width=1000,height=650";
//	var sFeatures = "toolbar=0,status=0";
	window.open(sUrl, "FullWindow", sFeatures)
}

function closeFlashCard(){
	$('flashContainer').hide();
}

function swapClass(oItem, sClass){
//	alert(hMenu.get("id") + " = " + $(oItem).id)
	if($(oItem).id != hMenu.get("id"))
		$(oItem).className = sClass
}

function printStock(){
	window.open('stock_print.asp','print_stock');
}

function sendFriend(sForm){
var oForm = $(sForm);

	if(isValid(oForm)){
		oForm.request({
			onComplete: function(result){
				if((result.responseText != "")){
					eval("var oResult = " + result.responseText + ";");
					if(oResult.error){
						alert(oResult.error);
						return false;
					}
				}
				$('content').hide();
				$('content_2').show();
			}
		})
	}
}

function isValid(oForm){
	
	switch(oForm.identify()){
			case "frmSendFriend":
				if(ifCondition((!isEmail($('from_email').getValue())), 'from_email', 'Su dirección de correo electrónico es incorrecta.')) return false;
				if(ifCondition((!isEmail($('to_email').getValue())), 'to_email', 'La dirección de correo electrónico de su amigo es incorrecta.')) return false;
				if(ifEmpty('subject', 'Debe especificar el asunto del correo.')) return false;
				if(ifEmpty('comments', 'Los comentarios no pueden quedar vacios.')) return false;
				break;
			case "frmDrawing":
				if(ifEmpty('client_code', 'El código del cliente no debe quedar vacio.')) return false;
				if(ifEmpty('client_name', 'La razón social no debe quedar vacia.')) return false;
				if(ifEmpty('city', 'La población no debe quedar vacia.')) return false;
				if(ifEmpty('postal_code', 'El código postal no debe quedar vacio.')) return false;
				if(ifEmpty('contact_person', 'Debe especificar la persona de contacto.')) return false;
				//if(ifCondition((!isEmail($('client_email').getValue())), 'client_email', 'La dirección de correo electrónico es incorrecta.')) return false;
				if(ifLength('promotion_code', 6, 6, 'La longitud del número del folleto debe ser de 6 caracteres.')) return false;
				if(ifCondition((isEmpty('letter_1') && isEmpty('letter_2') && isEmpty('letter_3') && isEmpty('letter_4') && isEmpty('letter_5') && isEmpty('letter_6')), 'letter_1', 'Debe especificar la(s) letra(s) de promoción que haya comprado.')) return false;
				if(ifEmpty('delivery_note', 'Debe especificar el número de albarán.')) return false;
			  if(ifCondition(!isDate($('purchased_on').getValue()), 'purchased_on', 'El valor de la fecha de compra es incorrecto')) return false;
				break;
	}
	return true;
}

function isEmail(src) {
     var emailReg = "^[\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w]$";
     var regex = new RegExp(emailReg);
     return regex.test(src);
}

function ifCondition(bCondition, sField, sMessage){
	if(bCondition){
		alert(sMessage);
		$(sField).focus();
		return true;
	}
}

function ifEmpty(sField, sMessage){
	if($(sField).getValue() == ""){
		alert(sMessage);
		$(sField).focus();
		return true;
	}
}

function isEmpty(sField){
	if($(sField).getValue() == ""){
		return true;
	}
}

function ifLength(sField, nMin, nMax, sMessage){
	if(($(sField).getValue().length < nMin) || ($(sField).getValue().length > nMax)){
		alert(sMessage);
		$(sField).focus();
		return true;
	}
}

function switchRotator( nIndex )
{
  	//alert(oRotator);
	oRotator.img_index = ((nIndex == 0)?oRotator.list.length:nIndex) - 1;
	if(oRotator.top_layer == oRotator.layer1)
	{
		oRotator.loadImage(oRotator.layer2);
	}
	else{
		oRotator.loadImage(oRotator.layer1);
	}

	oRotator.fade();
}
