//@author:  Antonio Gámez
//@empresa: Doble H Multimedia
//____________________________________________________________________________________
function ComboxDelOption(obj,item){
	if (item < 0) return;
	//while (true){
   	if (document.f[obj].length > item)
      	document.f[obj].remove(item);
   //   else return;
   //}
}
//____________________________________________________________________________________
function ComboxNewOption(obj,id,value){      	
	document.f[obj][document.f[obj].length] = new Option(value, id);
}
//____________________________________________________________________________________
function esEmail(mail){
	var email=/^[\w-_\.]+@[\w]{1}[\w-_\.]*[\.]{1}[\w]{2,3}$/;
	//var email = /^(.+\@.+\..+)$/;
	return email.test(mail);
}
//____________________________________________________________________________________
function maximaLongitud(texto,maxlong) {
   var tecla, in_value, out_value;
   if (texto.value.length > maxlong) {
      in_value = texto.value;
      out_value = in_value.substring(0,maxlong);
      texto.value = out_value;
      return false;
   }
   return true;
}
//____________________________________________________________________________________
function CopyPaste(o,d){
	if (o && d) {document.getElementById(d).value = document.getElementById(o).value;}	
	return false;
}
//____________________________________________________________________________________
function ShowItem(fld){
	document.getElementById(fld).style.display="block";
}
//____________________________________________________________________________________
function HideItem(fld){
	document.getElementById(fld).style.display="none";
}
//____________________________________________________________________________________
/*Muestra la forma de pago seleccionada*/
function FormasDePago(forma){
	
	var formas=Array('DIVTarjeta','DIVReembolso','DIVPrepago','DIVCuenta');
	for (i=0;i<formas.length;i++) {
		document.getElementById(formas[i]).style.display="none";
		if ( document.forms['fcliente'].elements['fpago'][i].checked )
			forma = i;
	}
	if (forma > -1)
		document.getElementById(formas[forma]).style.display="block";
}
//____________________________________________________________________________________
function SetStatus(msg){
   window.status = msg;
}
//____________________________________________________________________________________
function checkEnter(event){ 	
	var NS4 = (document.layers) ? true : false;
	var code = 0;
	if (NS4) code = event.which;
	else code = event.keyCode;
	if (code==13)
		return true;
	return false;
}
//____________________________________________________________________________________
function MM_swapImgRestore() { //v3.0 dreamweaver
  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_swapImage() { //v3.0 dreamweaver
  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_findObj(n, d) { //v4.01 dreamweaver
  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 TestData(){
   var formulario = "f";
   var contenido = "";
   var colorError = "#E0DFE3";
   var colorNormal= "#ffffff"
   var err = "";
   for (i=0;i<arguments.length;i++){
      eval("document.forms."+formulario+"."+arguments[i]+".style.background = '"+colorNormal+"'");
//excepciones. los campos con formato los hago aparte. a ver si puedo generalizar esto :(
      if (arguments[i]=='email') {
         if (!esEmail(eval("document.forms."+formulario+"."+arguments[i]+".value"))){
            eval("document.forms."+formulario+"."+arguments[i]+".focus()");
            eval("document.forms."+formulario+"."+arguments[i]+".style.background = '"+colorError+"'");
            err="cualquiercosa";
         }
      }
//fin excepciones
      eval("contenido = document.forms."+formulario+"."+arguments[i]+".value.replace(/ /g,'')");
      if (contenido=="") {
         eval("document.forms."+formulario+"."+arguments[i]+".style.background = '"+colorError+"'");
         if (err=="") {
            eval("document.forms."+formulario+"."+arguments[i]+".focus()");
            err = "cualquiercosa";
         }
      }
   }
//accion elimiar
   if (document.forms.f.action=='?op=delete'){
      if (!confirm('Seguro que desea eliminar este registro')) return false;
   }
   if (err){
      alert("¡¡Los campos marcados son necesarios o no son válidos!!");
      return false;
   }
   eval("document.forms."+formulario+".submit()");
}
//____________________________________________________________________________________
function Show(page,w,h) {
   var X = (screen.width/2)-(w/2);
   var Y = (screen.height/2)-(h/2);
   sList = window.open(page, "list", "status=0,alwaysRaised=1,scrollbars=0,width="+w+",height="+h+",top="+Y+",left="+X);
}
//____________________________________________________________________________________
function Show2(page,w,h) {
   var X = (screen.width/2)-(w/2);
   var Y = (screen.height/2)-(h/2);
   sList = window.open(page, "list", "status=0,alwaysRaised=1,scrollbars=1,width="+w+",height="+h+",top="+Y+",left="+X);
}
//____________________________________________________________________________________
//Prepara la busqueda de libros.
function SearchBooks(option){	
	var f1=document.forms.f.fecha1.value;
	if (f1 == '') f1 = GetDate('');
	var f2=document.forms.f.fecha2.value;
	if (f2 == '') f2 = GetDate('dd/mm/yyyy');
	var editor=document.forms.f.editor.value;
	//if (editor == '') editor = "null";
	var materia=document.forms.f.materia.value; //desplegable
	var catalogo=document.forms.f.catalogo.value; //desplegable
	var nref=document.forms.f.nref.value;
	//if (nref == '') nref = "null";	
	var titulo=document.forms.f.titulo.value;
	titulo=titulo.replace(/~/g,'');
	titulo=titulo.replace(/%/g,'');
	titulo=titulo.replace(/\+/g,'}');
	titulo=titulo.replace(/\-/g,'{');
	//titulo=replaceSubstring(titulo,"e","ñ");
	//if (titulo == '') titulo = "null";
	
	URLdestino = f1 + "~" + f2 + "~" + editor + "~" + materia + "~";
	URLdestino +=catalogo + "~" + nref + "~" + titulo;
	//alert ((URLdestino));
	if (option=='search')
		location = '?filter=' + URLdestino;
	else
		location = '?op=export&filter=' + URLdestino;
}
//____________________________________________________________________________________
//Prepara la busqueda de articulos.
function SearchArti(){	
	var cab = document.getElementById('cabecera').value; //desplegable
	var tit = document.getElementById('titulo').value;
	var aut = document.getElementById('autores').value;
	tit=tit.replace(/~/g,''); //limpieza de caracteres q nos pueden causar problemas
	tit=tit.replace(/%/g,'');
	tit=tit.replace(/\+/g,'}');
	tit=tit.replace(/\-/g,'{');
	aut=aut.replace(/~/g,'');
	aut=aut.replace(/%/g,'');
	aut=aut.replace(/\+/g,'}');
	aut=aut.replace(/\-/g,'{'); 
	
	URLdestino = cab + "~" + tit + "~" + aut;
	location = '?filter=' + URLdestino;
}
//____________________________________________________________________________________
//Prepara la busqueda de descargas.
function SearchDownloads(){	
	var f1=document.forms.f.fecha1.value;
	if (f1 == '') f1 = GetDate('');
	var f2=document.forms.f.fecha2.value;
	if (f2 == '') f2 = GetDate('dd/mm/yyyy');
	var tit = document.getElementById('titulo').value;
	var aut = document.getElementById('autor').value;
	tit=tit.replace(/~/g,''); //limpieza de caracteres q nos pueden causar problemas
	tit=tit.replace(/%/g,'');
	tit=tit.replace(/\+/g,'}');
	tit=tit.replace(/\-/g,'{');
	aut=aut.replace(/~/g,'');
	aut=aut.replace(/%/g,'');
	aut=aut.replace(/\+/g,'}');
	aut=aut.replace(/\-/g,'{'); 
	
	URLdestino = f1 + "~" + f2 + "~" + tit + "~" + aut;
	location = '?filter=' + URLdestino;
}
//____________________________________________________________________________________
//format: dd/mm/yyyy o yyyy/mm/dd
function GetDate(format){	
	var today = new Date();
	var dd = "",mm="",yyyy="";
	dd = today.getDate();
	if (today.getDate() < 10) dd = "0"+dd;
	mm = today.getMonth()+1;
	if (today.getMonth()+1 < 10) mm = "0"+mm;
	if (format == 'dd/mm/yyyy')
		today = dd+"/"+mm+"/"+today.getYear();
	if (format == 'yyyy/mm/dd')
		today = today.getYear()+"/"+mm+"/"+dd;
	if (format == '')
		today = '01/01/2000';
	return today;		
}
//____________________________________________________________________________________
function currencyFormat(fld, milSep, decSep, e) {
	 //Arreglo para que no el campo no exceda de la longitud marcada por maxlength//
	 var campo = window.event.srcElement.name;
	 var lenMaxima = document.getElementById(campo).getAttribute("maxlength");
	 var lenActual = document.getElementById(campo).value.length;
	 if (lenMaxima==lenActual) return false;
	 //fin arreglo
    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;
    if (whichCode == 13) return true; // Enter
    key = String.fromCharCode(whichCode); // Get key value from key code
    if (strCheck.indexOf(key) == -1) return false; // Not a valid key
    len = fld.value.length;
    for(i = 0; i < len; i++)
     if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
    aux = '';
    for(; i < len; i++)
     if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0) fld.value = '';
    if (len == 1) fld.value = '0'+ decSep + '0' + aux;
    if (len == 2) fld.value = '0'+ decSep + aux;
    if (len > 2) {
     aux2 = '';
     for (j = 0, i = len - 3; i >= 0; i--) {
      if (j == 3) {
       aux2 += milSep;
       j = 0;
      }
      aux2 += aux.charAt(i);
      j++;
     }
     fld.value = '';
     len2 = aux2.length;
     for (i = len2 - 1; i >= 0; i--)
      fld.value += aux2.charAt(i);
     fld.value += decSep + aux.substr(len - 2, len);
    }
    return false;
}
//____________________________________________________________________________________
function FormatNumber(total,decimals){
   if ( decimals==undefined )
      decimals = 2;

   decimals *= 1;

   var suffix = ""
   for ( var i=0; i<decimals; i++ )
      suffix += "0";

   var num = "" + parseFloat(total);
   if ( num == "NaN" )
      return num = "0" + ((decimals>0) ? "."+suffix : "");

   if ( num.indexOf(".") == -1 )
      return num += (decimals>0) ? "."+suffix : "";

   num += suffix;
   var tp = num.indexOf(".")+decimals;
   var rnd = Math.round(num.substring(tp,tp+1)+"."+num.substring(tp+1));

   return num.substring(0,tp)+rnd;
}
//____________________________________________________________________________________
function OnlyNumbers(e){
	var charCode = e.keyCode;
	// Chequeamos que sea un numero comparandolo con los valores ASCII
	if (charCode > 31 && (charCode < 48 || charCode > 57)){
		//alert (charCode);
		return false;
	}
	return true;
}
//____________________________________________________________________________________
function Actions(act){
	document.getElementById("op").value=act;
	document.getElementById('f').submit();
	return false;
}
//____________________________________________________________________________________
function NewAgencia(){
	Show2('agencias.php','500','350');
}
//____________________________________________________________________________________
function NumbersIP(e){
	var charCode = e.keyCode;
	// Chequeamos que sea un numero comparandolo con los valores ASCII
	if (charCode > 31 && (charCode < 48 || charCode > 57)){		
		return false;
	}
	numeroPulsado = charCode - 48;	
	valorActual = parseInt(e.srcElement.value,10);
	if (numeroPulsado==0 && !valorActual) return false;//teclear un cero a la izquierda
	total = numeroPulsado + valorActual*10;//lo que habia mas lo tecleado, por diez porque primero metes centenas o decenas
	if (total > 254) return false;		
	return true;
}
//____________________________________________________________________________________
function Replicar(){
	document.getElementById('ipA').value = document.getElementById('ip1').value;
	document.getElementById('ipB').value = document.getElementById('ip2').value;
}
//____________________________________________________________________________________
function ComboxNewOptionByObj(obj,val,texto,isAnotherWindow){
	var len = obj.options.length;
	if (isAnotherWindow)
		var oOption = opener.document.createElement('OPTION');
	else
		var oOption = document.createElement('OPTION');
	oOption.text=texto;
   oOption.value=val;
	obj.options[len] = oOption;
}
//____________________________________________________________________________________
function ComboxClearByObj(obj){
	while (obj.options.length > 0)
		obj.remove(0);
}
//____________________________________________________________________________________
/*Crea para un formulario los campos pasados por parametro*/
var formAlVuelo='principal';
function CamposAlVuelo(datos){
	var campos = datos.split("&");
	for (i=0;i < campos.length;i++){
		var fld = document.createElement('input');
		fld.setAttribute("type","hidden");
		var valores = campos[i].split("=");
		var nombre  = valores[0].replace("?","");
		var valor = "";
		valor = valores[1];
		fld.setAttribute("name",nombre);
		fld.setAttribute("value",valor);
		document.forms[formAlVuelo].appendChild(fld);
	}
	document.forms[formAlVuelo].submit();

}
//____________________________________________________________________________________
function Buscador(){
	var tit = document.getElementById('tit').value;
	CamposAlVuelo("?do=queryBooks&tit="+tit);
}
//____________________________________________________________________________________
function BuscadorA(){
	CamposAlVuelo("?do=queryBooksAdvanced");
}
//____________________________________________________________________________________
function BuscadorAd(){
	var tit = document.forms['buscador'].tit.value;	
	var aut = document.forms['buscador'].aut.value;	
	var mat = document.forms['buscador'].mat.value;
	var oper = '';
	if (document.forms['buscador'].oper[0].checked) oper=document.forms['buscador'].oper[0].value;
	else oper=document.forms['buscador'].oper[1].value;
	CamposAlVuelo("?do=queryBooks&tit="+tit+"&aut="+aut+"&mat="+mat+"&oper="+oper);
}
//____________________________________________________________________________________
/*Ventanas informativas*/
function VentanasInformativas(w,h,URL){
	var X = (screen.width/2)-(w/2);
	var Y = (screen.height/2)-(h/2);
	window.open(URL,'win','scrollbars=1,status=0,width='+w+',height='+h+',top='+Y+',left='+X);
}
//____________________________________________________________________________________
function PreparedFavorites(){
	var items = document.getElementById('favoritos').length;
	document.getElementById('favoritosgroup').value = "";
	for (i=0; i < items; i++)
   	document.getElementById('favoritosgroup').value += document.getElementById('favoritos').options[i].value+";";
}
//____________________________________________________________________________________
function DelFavoritos(){
	var item = document.getElementById('favoritos').selectedIndex;
	if (item > -1)
		document.getElementById('favoritos').options[item]=null;
}
//____________________________________________________________________________________
function AddFavoritos(){
	var item = document.getElementById('materia').selectedIndex;
	if (item > -1){
		var id   =  document.getElementById('materia').value;
		var text = document.getElementById('materia').options[document.getElementById('materia').selectedIndex].text;
		for (i=0;i<document.getElementById('favoritos').length;i++)
			if(document.getElementById('favoritos').options[i].value == id) return;//ya está   		
		document.getElementById('favoritos').options[document.getElementById('favoritos').options.length] = new Option(text, id);
	}
}
//____________________________________________________________________________________
function SincronizedCombos(){
	if ( !document.getElementById('favoritos') ){
		alert ("chungo");
		return;
	}
	var origen = document.getElementById('favoritos').length;
	var destin = document.getElementById('materia').length;	
	for (i=0; i < origen; i++)
		for (x=0; x < document.getElementById('materia').options.length; x++)
			if (document.getElementById('materia').options[x].value==document.getElementById('favoritos').options[i].value)
				document.getElementById('materia').options[x]=null;
}
//____________________________________________________________________________________
function TestDataCustom(){
	var fpago   = document.f.fpago[0].checked;
	var titular = document.getElementById("tartit").value.replace(/ /g,'');
	var num     = document.getElementById("tarnum").value.replace(/ /g,'');
	var mes  	= document.getElementById('tarmes').value;
	var anio 	= document.getElementById('taranio').value;
	var tipo 	= document.getElementById('taranio').value;
	var fexp    = ComprobarFechaTarjeta (mes, anio);
	var err     = "";
	if (fpago && !titular)
		err = "-No hay titular de tarjeta\n";
	if (fpago && !num)
		err += "-No hay número de tarjeta\n";
	if (fpago && !fexp)
		err += "-Fecha de caducidad de tarjeta.\n";
	if (err) {alert("Errores en la forma de pago:\n\n"+err);return false;}
	if (fpago && !compruebatarjetadecredito(num, tipo)){
		alert ("Error al introducir la tarjeta");
		return false;
	}
	return true;
}
//____________________________________________________________________________________
function InitCliente(){
	SincronizedCombos();
	MarcarErrores();
	if (document.getElementById('suscribir').checked) ShowItem('favoritosCC');
	if (document.forms['fcliente'].elements['fpago'][0].checked) FormasDePago(0);
	if (document.forms['fcliente'].elements['fpago'][1].checked) FormasDePago(1);
	if (document.forms['fcliente'].elements['fpago'][2].checked) FormasDePago(2);
	if (document.forms['fcliente'].elements['fpago'][3].checked) FormasDePago(3);
	document.getElementById('nom').focus();
}
//____________________________________________________________________________________
var camposError='';
function MarcarErrores(){
	if ( !camposError ) return;
	var errores = camposError.split(",");
	for (i=0;i<errores.length;i++)
		document.getElementById(errores[i]).style.background = '#cdcdcd';	
}
//____________________________________________________________________________________
function UpdateMyProfile(){
	PreparedFavorites();
	document.forms['fcliente'].submit();
	//TestData('user','pass','nom','ape','dni','mail','envdir','envloc','envpro','envcp','envpais','facdir','facloc','facpro','faccp','facpais')
}
