var valores=new Array();
var buffer;
var encontrado;
var caracter;
var campo;
var cosa=false;
var pulsaciones=0;
var evento=false;
var ocu;
var co;
var confirmar;
var lanzarBuscar=0;
var post='';



/**
 *
 */
function eliminar_uno(nombre, id, pagina, ruta, nom, modulo){
	if(confirm('El registro ' + nom + ' va a ser eliminado de la tabla ' + nombre + '. ¿Desea continuar?.'))
	submitar(pagina, pagina + '.php?pa=' + modulo + '&ac=eliminar&id=' + id + ruta);
}

/**
 *
 */
function eliminarImagen(id, ruta, pag, post2, nom){	
	if(confirm('Atención: la imagen ' + nom + ' va a ser borrada. ¿Desea continuar?.'))
	Cargar(id, ruta, pag, post2);
	//submitar(pagina, pagina + '.php?pa=' + nombre + '&ac=eliminar&id=' + id + ruta);
}

/**
 * Elimina registros de una tabla, llama a submitar con la ruta especificada, para que lo haga.
 * Se pide confirmación y se submitan los id's de los registos con la acción: eliminar.
 * Recibe la seccion del menu en la que se va a borrar, el nombre del formulario, la ruta y el número de pestaña
 */
function eliminar(pag, modulo, ruta){
	var enlace='';
	var i=0;
	var ext=valores.length;
	while(i<ext){
		if(-1!=valores[i])	enlace+=valores[i] + ',';
		++i;
	}
	if(enlace){
		if(ext>1)	mensaje='Los registros seleccionados van a ser eliminados, ¿Desea continuar?';
		else	mensaje='El registro seleccionado va a ser eliminado, ¿Desea continuar?';
		if(confirm(mensaje)){
			enlace=enlace.slice(0, -1);
			enlace=pag + '.php?pa=' + modulo + '&ac=eliminar&ids=' + enlace + ruta;
			//Se vacia el array de id's cargados para eliminar.
			valores=new Array();
			submitar(pag, enlace); 
		}
	}
	else{
		valores=new Array(); 
		alert('Seleccione algún registro');
	}
}

/**
 *
 */
function cargar_eliminar_todos(nom, id, num){
	i=0;
	valores=new Array(); 
	if(document.getElementById(id).checked){
		while(i<num){
			document.getElementById(nom + i).checked=true;
			valores[i]=document.getElementById(nom + i).value;
			++i;
		}
	}
	else{
		while(i<num){
			document.getElementById(nom + i).checked=false;
			++i;
		}
	}
}

/**
 *
 */
function cargar_eliminar(id, valor){
	i=0;
	ext=valores.length;
	if(document.getElementById(id).checked){
		while(i<ext && valores[i]!=-1)	++i;
		if(valores[i]==-1)	valores[i]=valor;
		else	valores[valores.length]=valor;
	}
	else{
		while(i<ext && valores[i]!=valor)	++i;
		if(valores[i]==valor)	valores[i]=-1;
	}

}

/**
 *
 */
function submitar(formulario, ruta){
	if('admin'==formulario){
		//alert(post);
		//sumar_post(ruta);
		//alert(post);
		//aniadir_post('l_logado_activo');
		//aniadir_post('admin_buscar');
		//post+='&l_logado_activo=' + document.getElementById('l_logado_activo').value;
		//post+='&admin_buscar=' + document.getElementById('admin_buscar').value;
		if(document.getElementById('buscar_id') 
		&& -1==ruta.indexOf('ticket=')
		&& -1==ruta.indexOf('ac=eliminarOperacion')
		&& -1==ruta.indexOf('ac=aniadir')
		)	sumar();
		
		document.getElementById(formulario).action=ruta;
		
		if(-1==ruta.indexOf('ac=actualizar')
		&& -1==ruta.indexOf('ac=ingresar') 
		&& -1==ruta.indexOf('va=enviado')
		&& -1==ruta.indexOf('ac=cerrar')  
		/*&& -1==ruta.indexOf('ac=buscar') */
		){
			//alert(ruta + '\n\n' + post);
			Cargar('contenido', ruta, formulario, post);
		}
		else	document.getElementById(formulario).submit();
	}
	else{
		if(ruta)	document.getElementById(formulario).action=ruta;
		document.getElementById(formulario).submit();
	}
}

/**
 *
 */
function sumar(){

	//Carga los datos del punto de venta para enviar por ajax
	if(document.getElementById('buscar_id').value){
		post+='&buscar_id=' + urlencode(document.getElementById('buscar_id').value);
		//alert(urlencode(document.getElementById('buscar_id').value));
		//aniadir_post('buscar_id');
	}
	aniadir_post('buscar_id_2');

	//Forma de pago
	if(document.getElementById('admin').pago)	post+='&pago=' + radio_value(document.getElementById('admin').pago);
	//Forma de envio
	if(document.getElementById('admin').envio)	post+='&envio=' + radio_value(document.getElementById('admin').envio);
	//Direcciones
	if(document.getElementById('admin').libretas1_tipo)	post+='&libretas1_tipo=' + radio_value(document.getElementById('admin').libretas1_tipo);
	if(document.getElementById('admin').libretas2_tipo)	post+='&libretas2_tipo=' + radio_value(document.getElementById('admin').libretas2_tipo);


	//Descuento
	aniadir_post('descuento_porcentaje'); 
	aniadir_post('descuento_cantidad');
	aniadir_post('atendido');
	//aniadir_post('comentario');
	if(document.getElementById('comentario') && document.getElementById('comentario').value){
		post+='&comentario=' + urlencode(document.getElementById('comentario').value);
	}
	//aniadir_post('cliente');

	if(1==document.getElementById('nuevo_cliente').value){
		//Datos de un cliente nuevo
		aniadir_post('nuevo_cliente');
		//aniadir_post('cliente_dni');
		aniadir_post('nombre');
		aniadir_post('usuario');
		aniadir_post('apellidos');
		aniadir_post('dir_nombre');
		aniadir_post('telefono');
		aniadir_post('postal');
		aniadir_post('poblacion');
		aniadir_post('provincia');
		aniadir_post('dni');
		aniadir_post('movil');
		//aniadir_post('xryref');
	
		//Direccion de facturacion.
		aniadir_post('usuario_2');
		aniadir_post('apellidos_2');
		aniadir_post('dir_nombre_2');
		aniadir_post('telefono_2');
		aniadir_post('postal_2');
		aniadir_post('poblacion_2');
		aniadir_post('provincia_2');
		aniadir_post('movil_2');
		aniadir_post('dni_2');
	}
}

/**
 *
 */
function aniadir_post(name){
	if(document.getElementById(name))	post+='&' + name + '=' + document.getElementById(name).value;
}

/**
 *
 */
function radio_value(campo){
    var i=0;
	var encon=false;
	var ext=campo.length;
	while(i<ext && !encon){
		if(campo[i].checked)	encon=true;
		else	++i;
	}
	if(encon)	return campo[i].value;
	else	return '';
}

/**
 *
 */
 /*
function comprobar_url(){
	var barras_1=0;
	var barras_2=0;
	ext=document.referrer.length;
	for(i=0, j=0, actual='', anterior='';i<ext && ('?'!=document.location.href.charAt(i) || '?'!=document.referrer.charAt(j)); ++i, ++j){
		
		if('/'==document.location.href.charAt(i))	++barras_1;
		if('/'==document.referrer.charAt(j))	++barras_2;
		if(3==barras_1 || 3==barras_2)	break;
		actual=actual + document.location.href.charAt(i);
		anterior=anterior + document.referrer.charAt(j);
	}
	//alert(actual + ' ' + anterior);
	if(actual!=anterior || !actual || !anterior)	location='index.php';
}
*/


/**
 *
 */
function orden_sentido(formulario, ruta, orden, ascendente, id){
	if(!ascendente && orden==id)	ruta+='&se=de';
	submitar(formulario, ruta);
}

/**
 *
 */
function cambiar_color(id, color){
	if(color && '#eff2fa'!=color)	{document.getElementById(id).style.backgroundColor=color;}
	else if(!color) {document.getElementById(id).style.backgroundColor='#ffffff';}
	document.getElementById(id).style.cursor='pointer';
}

/**
 *
 */
function cambiar_color_letras(id, color, id2){
	if(color){
		if(id2)	{document.getElementById(id2).style.color=color;}
		document.getElementById(id).style.color=color;
		document.getElementById(id).style.cursor='pointer';
		document.getElementById(id).style.textDecoration='underline';
	}
	else if(!color){
	
		if(id2)	{document.getElementById(id2).style.color='#333333';}
		document.getElementById(id).style.color='#333333';
		document.getElementById(id).style.textDecoration='none';
	}
}

function entrar(formulario){
	if(13==event.keyCode)	document.getElementById(formulario).submitar(formulario, null);
}

function abrir(URL, nombre_enlace, ruta){	
	buffer=new Image();
	buffer.src=ruta;
	setTimeout('hacer_2("' + URL + '", "' + nombre_enlace + '")', 300);
}

function hacer_2(URL, nombre_enlace){
	
	//alert(buffer.width + ' ' + buffer.height);
	anc=30 + buffer.width;
	alt=30 + buffer.height;
	parametros='width=' + anc + ', height=' + alt + ',directories=NO, status=YES, scrollbars=NO, resizable=YES, Titlebar=NO, fullscreen=NO, location=NO, left=40px, top=170px';
	//if(ventana)	{ventana.close(); ventana=null;}
	//ventana=
	window.open(URL, nombre_enlace, parametros);
}

function sumar_cantidad(pag, url, formulario, nombre, ref){	
	formulario.elements[nombre+ref].value++;
	submitar(pag, url);
}

function restar_cantidad(pag, url, formulario, nombre, ref){
	if(formulario.elements[nombre+ref].value>1)	formulario.elements[nombre+ref].value --;
	submitar(pag, url);
}

function sumar_cantidad2(pag, url, nombre){
	++document.getElementById(nombre).value;
	submitar(pag, url);
}

function restar_cantidad2(pag, url, nombre){
	if(document.getElementById(nombre).value>1)		--document.getElementById(nombre).value;
	submitar(pag, url);
}


/*
function mostrar(capa, ind, PATH_APLICACION){
	
	imagen_abajo='ico_flechaDown2.gif';
	imagen_arriba='ico_flechaUp2.gif';

	capa2='';

	if('categorias'==capa || 'fabricantes'==capa){
		if(''==document.getElementById(ind).style.display)	{document.getElementById(ind).style.display='none'; document.getElementById(capa).src=PATH_APLICACION + 'img/gif/' + imagen_abajo;}
			else if('none'==document.getElementById(ind).style.display)	{document.getElementById(ind).style.display=''; document.getElementById(capa).src=PATH_APLICACION + 'img/gif/' + imagen_arriba;}

		capa2=capa+1;
	}
	else
		{
			capa2='foto_' + capa;
			if('none'!=document.getElementById(capa).style.display)
				{
						document.getElementById(capa).style.display='none';
						document.getElementById(capa2).src=PATH_APLICACION + 'img/gif/' + imagen_abajo;
						cajas[ind]= 0;
				}
				else if('none'==document.getElementById(capa).style.display)
					{
						document.getElementById(capa).style.display='';
						document.getElementById(capa2).src=PATH_APLICACION + 'img/gif/' + imagen_arriba;
						cajas[ind]=1;
					}
		}
}
*/

/**
 *
 */
function mostrar_select(pag, ruta, formulario, modulo, num, num2, num3, campo){	
	//alert('pag: ' + pag + '\nruta: ' + ruta + '\nformulario: ' + formulario + '\nmodulo: ' + modulo + '\nnum: ' + num +  '\nnum2: ' + num2 + '\nnum3: ' + num3);
	var i=0;
	var texto='';
	var ext=formulario.elements.length;
	while(i<ext){
		if(campo==formulario.elements[i].name){
			var indice = formulario.elements[i].selectedIndex ;
			var valor = formulario.elements[i].options[indice].value;
			texto = formulario.elements[i].options[indice].value ;
			if('categorias'==formulario.elements[i].name && !num)	texto='';
			break;
		}
		++i;
	}
	if(texto)	ruta+=texto;

	//div=modulo;
	//alert(ruta);
	//alert(div + ' - ' + ruta + ' - ' + formulario + ' - ' + post);
	if(modulo)	Cargar(modulo, ruta, formulario, post);
	/*if(num3){
		if(num2>0)	{ruta+='&fi=' + num2;}
		sumar_post(ruta);
		Cargar('ficha' + num3, ruta, formulario, post);
	}
	*/
	
	/*if(texto && document.getElementById(texto).style.display=="none"){
		document.getElementById(texto).style.display="";
		for(i=0;i<formulario.elements.length;i++){
			if(formulario.elements[i].name=="menus"){
				for(j=0;j<formulario.elements[i].options.length;j++){
					texto2 = formulario.elements[i].options[j].text;
					if(texto2!=texto && texto2)	{document.getElementById(texto2).style.display="none"; }
				}
			}
		}
	}*/
}

/**
 *
 */
function seleccionar_boton(formulario, id, classColor, id2, array_id, classColor2){
	//alert(classColor);
	formulario=document.getElementById(formulario);
	formulario.elements[id].checked=true;
	i=0;
	while(i<array_id.length){
	
		//document.getElementById(array_id[i]).style.backgroundColor=classColor2;
		//document.getElementById(array_id[i]).class=classColor2;
		$('#' + array_id[i]).removeClass(classColor);
		$('#' + array_id[i]).addClass(classColor2);
		++i;
	}

	//if(classColor)	document.getElementById(id2).style.backgroundColor=classColor;
	if(classColor){
		//document.getElementById(id2).class=classColor;
		$('#' + id2).removeClass(classColor2);
		$('#' + id2).addClass(classColor);
	}
}

/*
function mostrar_capa(capa, total){
	if(total)	{for(i=0;i<total;++i)	{document.getElementById('capa_' + i).style.display='none';}}
	if(''==document.getElementById(capa).style.display)	document.getElementById(capa).style.display='none';
	else if('none'==document.getElementById(capa).style.display)	document.getElementById(capa).style.display='';
}*/

/*
function mostrar_subcapa(capa, tam, maximo){
	
	if('none'==document.getElementById(capa).style.display){
		//for(i=1;i<maximo;++i){
		i=0;
		//alert(maximo);
		//maximo=35;
		while(i<maximo){
			if(document.getElementById('capa_' + i))	document.getElementById('capa_' + i).style.display='none';
			++i;
		}
		document.getElementById(capa).style.display='';
	}
	if(document.getElementById('admin').admin_buscar)	document.getElementById('admin').admin_buscar.value='';

}
*/
/*
function lista_establecimientos(id){
	document.getElementById(id).style.cursor='pointer';
	document.getElementById(id).style.backgroundColor='#FFCC00';
	document.getElementById(id).style.color='#000000';
}
*/
/*
function ocultar_ficha(capa){
	document.getElementById(capa).style.backgroundColor='#4e6f90';
	document.getElementById(capa).style.color='#ffffff';
}
*/
/*
function mostrar_ficha(capa){
	document.getElementById(capa).style.border='1px solid #bfbfbf';
	document.getElementById(capa).style.borderRightColor='#908d8d';
	document.getElementById(capa).style.borderBottomColor='#908d8d';
	document.getElementById(capa).style.backgroundColor='#f8f8f8';
	document.getElementById(capa).style.color='#4e6f90';
}
*/


function mostrar_caja(id){
	document.getElementById(id).style.display='';
}

function ocultar_caja(id){
	document.getElementById(id).style.display='none';
}

/*
function mostrar_sucursales(capa){
	//alert(document.getElementById(capa).value);
	//alert('mas_sucursales_' + num + '_' + document.getElementById(capa).value);
	//mostrar_caja('mas_sucursales_' + num + '_' + document.getElementById(capa).value);
	//alert('mas_sucursales_' + num + '_' + document.getElementById(capa).value);
	//alert(capa);
	mostrar_caja(capa);
}
*/

/**
 *
 */
function pulsares(e) {
  tecla = (document.all) ? e.keyCode :e.which;
  return (tecla!=13);
}

/**
 *
 */
function buscar(pag, campo, ruta, ruta_segun, e){
	if(13==pulsar(e)){
		if(document.getElementById(campo).value){
			//aniadir_post(campo);
			post+='&' + campo + '=' + document.getElementById(campo).value;
			submitar(pag, ruta);
		}
		else{
			cosa=true;
			submitar(pag, ruta_segun);
		}
		return false;
	}
	/*else if(document.getElementById(campo).value && 'admin'==pag)	{submitar(pag, ruta);}*/
	return true;
}

function buscarDni(pag, ruta, e, campo){
	if(13==pulsar(e) || pressIntro){
		aniadir_post(campo);
		submitar(pag, ruta);
	}
}

function buscarReferencia(e){
	evento=false;
	if(13==pulsar(e)){
		evento=true; 
	}
	++pulsaciones; 
	cosa=true; 	
}

function buscarVale(campo, pag, ruta, e){
	if(13==pulsar(e) || pressIntro){
		aniadir_post(campo); 
		submitar(pag, ruta);
	}
}

/*
function comprobar_cantidad(formulario, ruta, cantidad){
	if(!cantidad)	alert('Introduzca la cantidad de producto a solicitar');
	else if(isNaN(cantidad))	alert('Introduzca un numero entero válido para la cantidad de producto a solicitar');
	else  submitar(formulario, ruta);
}
*/


/**
 *
 */
function cargarZonaGeografica(idEnvios, idProvincia, pais, pag, enlaceEnvios, enlaceProvincia, enlaceTotales, provincia, enlaceAcordeon){
	aup='&paisZona=' + pais;
	//alert(aup);
	//alert(provincia);
	if(provincia)	aup+='&provinciaZona=' + provincia;
	
	//Carga el selector de provincias.
	if(enlaceProvincia)	Cargar(idProvincia, enlaceProvincia, pag, '&paisZona=' + pais);
	
	//Carga el listado de transportistas.
	if(document.getElementById(pag).envio){
		aup+='&envio=' + radio_value(document.getElementById(pag).envio);
		Cargar(idEnvios, enlaceEnvios, pag,  aup);
	}
	//Carga el resumen de totalizaciones.
	//seleccionarEnvio(pag, enlaceTotales);
	//alert(enlaceTotales);
	
	//Cargar('resumenTotalizaciones', enlaceTotales, pag, '');
}

/**
 *
 */
function cargarEnvio(pag4){
	//var idEnvio=document.getElementById(pag4).envio;
	var idEnvio=document.getElementsByName('envio');
	var aux4='&envio=' + radio_value(idEnvio);
	aux4+='&zprovincia=' + document.getElementById(pag4).provincia.value;
	aux4+='&zpais=' + document.getElementById(pag4).pais.value;	
	return aux4;
}

/**
 *
 */
function seleccionarEnvio(pag4, enlace4){
	var aux4='';
	aux4=cargarEnvio(pag4);
	//else 
	//alert(enlace4 + ' ' + aux4);
	Cargar('resumenTotalizaciones', enlace4, pag4, aux4);
	//$('#envios' + id).slideToggle('fast'); 
}

/**
 *
 */
function seleccionarPago(pag3, enlace3){
	var aux3='&pago=' + radio_value(document.getElementById(pag3).pago);
	if(document.getElementById(pag3).provincia)	aux3+=cargarEnvio(pag3);
	Cargar('resumenTotalizaciones', enlace3, pag3, aux3);
	//$('#pagos' + id).slideToggle('fast'); 
}

/**
 *
 */
function menuAcordeon(titulo, descripcion){
	$(document).ready(function(){																	
		//$(".hp:first").addClass("active");
		$(descripcion + ':not(:first)').hide();
	
		$(titulo).click(function(){
		
			$(this).next(descripcion).slideToggle('slow')
			.siblings(descripcion + ':visible').slideToggle('slow');
			
			//$(this).toggleClass("active");
			//$(this).siblings(".hp").removeClass("active");
		});
		
	});	
}

/*
function cambiar_imagen(ruta, imagen){
	document.mapa_espana.src=ruta + imagen;
}*/

/*
function hallar_cp(cp){

	var cp2;
	var provincia=null;
	cp2 = cp.substr(0, 2);

	if(cp.length != 5)	{alert('El código postal debe estar formado por 5 cifras.');}
		else {
				switch(cp2){
					case '01': provincia = 'Álava'; break; case '02': provincia = 'Albacete'; break; case '03': provincia = 'Alicante'; break;
					case '04': provincia = 'Almería'; break; case '05': provincia = 'Ávila'; break; case '06': provincia = 'Badajoz'; break;
					case '07': provincia = 'Islas Baleares'; break; case '08': provincia = 'Barcelona'; break; case '09': provincia = 'Burgos'; break;
					case '10': provincia = 'Cáceres'; break; case '11': provincia = 'Cádiz'; break; case '12': provincia = 'Castellón'; break;
					case '13': provincia = 'Ciudad Real'; break; case '14': provincia = 'Córdoba'; break; case '15': provincia = 'La Coruña'; break;
					case '16': provincia = 'Cuenca'; break; case '17': provincia = 'Gerona'; break; case '18': provincia = 'Granada'; break;
					case '19': provincia = 'Guadalajara'; break; case '20': provincia = 'Guipúzcoa'; break; case '21': provincia = 'Huelva'; break;
					case '22': provincia = 'Huesca'; break; case '23': provincia = 'Jaén'; break; case '24': provincia = 'León'; break;
					case '25': provincia = 'Lérida'; break; case '26': provincia = 'La Rioja'; break; case '27': provincia = 'Lugo'; break;
					case '28': provincia = 'Madrid'; break; case '29': provincia = 'Málaga'; break; case '30': provincia = 'Murcia'; break;
					case '31': provincia = 'Navarra'; break; case '32': provincia = 'Orense'; break; case '33': provincia = 'Asturias'; break;
					case '34': provincia = 'Palencia'; break; case '35': provincia = 'Las Palmas de Gran Canaria'; break; case '36': provincia = 'Pontevedra'; break;
					case '37': provincia = 'Salamanca'; break; case '38': provincia = 'Santa Cruz de Tenerife'; break; case '39': provincia = 'Cantabria'; break;
					case '40': provincia = 'Segovia'; break; case '41': provincia = 'Sevilla'; break; case '42': provincia = 'Soria'; break;
					case '43': provincia = 'Tarragona'; break; case '44': provincia = 'Teruel'; break; case '45': provincia = 'Toledo'; break;
					case '46': provincia = 'Valencia'; break; case '47': provincia = 'Valladolid'; break; case '48': provincia = 'Vizcaya'; break;
					case '49': provincia = 'Zamora'; break; case '50': provincia = 'Zaragoza'; break; case '51': provincia = 'Ceuta'; break;
					case '52': provincia = 'Melilla'; break;
					default: provincia = '';
				}
			}
	return provincia;
}
*/

/*
function comunicaciones(capa, ruta, pag){
	ruta_2=ruta + co;
	//alert('capa: ' + capa + ' ruta: ' + ruta);
	//alert(post);

	Cargar(capa, ruta_2, pag, post);
	setTimeout('comunicaciones("' + capa + '", "' + ruta + '", "' + pag + '", "' + post + '")', 6000);
}*/
/*
function comunicaciones_acciones(formulario, accion, name, capa, ruta, pag){
	document.getElementById(formulario).comunicacion_accion.value=accion;
	aniadir_post(name);

	//ruta_2=ruta + co;
	Cargar(capa, ruta_2, pag, post);
	//comunicaciones(capa, ruta, pag)
}*/


function Cargar(Objeto,Quien,Formulario,Valores_Propios){
	//alert('Objeto: ' + Objeto + '\nQuien: '+ Quien + '\nFormulario: ' + Formulario + '\nValores Propios: ' + Valores_Propios);
//si se envia el formulario vacio, no se que hace pero va mas rapido.
//Formulario='';
var Valores='?';
/*Valores='?'
	$('#'+Formulario+' :text').each(function(){
		Valores+='&'+(this.id+'='+this.value)
	}
	)
	
	$('#'+Formulario+' :password').each(function(){
		Valores+='&'+(this.id+'='+this.value)
	}
	)
	$('#'+Formulario+' :hidden').each(function(){
		Valores+='&'+(this.id+'='+this.value)
	}
	)
	*/
	
	
	Valores+='&'+Valores_Propios;


    $.ajax({
	url: Quien,
    type: 'POST',
	dataType: 'html',
    data:Valores,
	timeout: 100000,
    error: function(xhr, ajaxOptions, thrownError){
		//alert(xhr.status);
		//alert(xhr.responseText);
        //alert(thrownError);
		//alert(Objeto + ' \n\n ' + Quien + ' \n\n ' + Formulario + ' \n\n ' + Valores);
	    $('#'+Objeto).html('Error');
	},
    success: function(data){
	    $('#'+Objeto).html(data);
	}/*,
        beforeSend: function (){
	   $("#"+Objeto).html("<div id='Loading'><img  src='../private/clases/img/downmio.gif' style='vertical-align:middle;'></div>");
	}*/
    });
}

/*
function imagen_fondo(id, ruta, id2, color){
	document.getElementById(id).style.backgroundImage=ruta;
	document.getElementById(id2).style.color=color;
}*/
/*
function redimensionar_imagen(id, tam){
	if(document.getElementById(id).width>tam)	{document.getElementById(id).width=tam;}
}*/







/**
 *
 */
function posicionar(id, fila, descripcion){  
	if("Microsoft Internet Explorer"!=navigator.appName)	focalizarLinea(id, fila, descripcion);		
	else	setTimeout('posicionar2("' + id + '", "' + fila + '", "' + descripcion + '")', 1);
}

/**
 *
 */
function posicionar2(id, fila, descripcion){
	if(document.getElementById(id) && document.getElementById(id).value && document.getElementById(fila) && document.getElementById(descripcion))	focalizarLinea(id, fila, descripcion)
	else setTimeout('posicionar2("' + id + '", "' + fila + '", "' + descripcion + '")', 1);	
}

/**
 *
 */
function focalizarLinea(id, fila, descripcion){
	document.getElementById(id).focus();
	document.getElementById(fila).style.backgroundColor='#edeff4';
	document.getElementById(descripcion).style.backgroundColor='#edeff4';	
}














/**
 * 
 */
function validar(formulario, nombre, name, requerido, tamano, tipo, campo, type, rnn, r1n, valores, reg){
	
	error=validador(nombre, name, requerido, tamano, tipo, campo, type, rnn, r1n, valores, reg);
	if(!error)	return true;	
	else{
		alert(error);
		ext=document.getElementById(formulario).elements.length;
		i=0;
		
		while(i<ext){
			if(document.getElementById(formulario).elements[i].name==encontrado){
				//alert(document.getElementById(formulario).elements[i].name);
				encontrado='';
				document.getElementById(formulario).elements[i].focus();
				break;
			}
			++i;
		}
		return false;
	}
}

/**
 * Validador de campos de formulario.
 */
function validador(nombre, name, requerido, tamano, tipo, campo, type, rnn, r1n, valores, reg){

	campo=new Array();
	var mensaje='Atención: hay errores en su formulario:\n';
	var salto='\n * ';
	//if(!nombre)	return 'Error de parámetros: No existe definición para el nombre del valor';
	//if(!name)		return 'Error de parámetros: No existe definición para el name del campo del formulario';
	//if(!requerido)	return 'Error de parámetros: No existe definición para los campos requeridos';
	//if(!tamano)	return 'Error de parámetros: No existe definicion para las dimensiones de los campos';
	i=0;
	var ext2;
	ext=name.length;
	while(i<ext){
		p=0;
		//Numero de registros para un campo con relación de 1 a n. 
		numR1n=1;
		//Número de registros para un campo con relación de n a n. 
		numRnn=1;
		//Carga el sufijo para un campo con relacion 1 a n.
		//if(r1n[i])	numR1n=valores['numFilas'][r1n[i]].length;
		//Consulta los registros de la tabla relacional n a n.
		registros=new Array();
		if(rnn[i] && reg[rnn[i]]){			
			var registros=new Array();
			registros=reg[rnn[i]];
			numRnn=registros.length;	
		}
		while(p<numR1n){
			j=0;
			if('radio'!=type[i])	existe=false;
			else	existe=true;
			while(j<numRnn){
				
				campo[j]=name[i];
				if(registros[j]>0)	campo[j]+=registros[j];
				//if(r1n[i])	campo[j]+=3;
				//alert(campo[j] + ' - ' + valores[campo[j]]);
				if(valores[campo[j]]){
					
					if(1==requerido[i] && !existe && valores[campo[j]]) 	existe=true;
					
					if('int'==tipo[i] || 'number'==tipo[i]){
						if('on'==valores[campo[j]])	valores[campo[j]]=1;
						//else	valores[campo[j]]=0;
						if (isNaN(valores[campo[j]])) mensaje+=salto + 'El campo ' + nombre[i] + ' debe ser un número entero';
					}
					else if('float'==tipo[i] || 'decimal'==tipo[i] || 'double'==tipo[i]){
						for(p=0, caracter='', ext2=valores[campo[j]].length; p<ext2 && ''==caracter; ++p){
							if('.'==valores[campo[j]].charAt(p) || ','==valores[campo[j]].charAt(p))	caracter=valores[campo[j]].charAt(p);
						}
						if(caracter)	parte=valores[campo[j]].split(caracter);
						else{
							parte=new Array(); 
							parte[0]=valores[campo[j]]; 
							parte[1]='';
						}
						if ((1==parte.length && isNaN (valores[campo[j]])) || (2==parte.length && (isNaN(parte[0]) || isNaN(parte[1])) || (parte.length > 2)))	mensaje+=salto + 'El campo ' + nombre[i] + ' debe ser un número decimal';
					}
					else if('bool'==tipo[i] || 'boolean'==tipo[i])	{if (!(('0'==valores[campo[j]]) || ('on'==valores[campo[j]]) || ('ON'==valores[campo[j]]) || ('false'==valores[campo[j]]) || ('FALSE'==valores[campo[j]]) || ('1'==valores[campo[j]]) || ('true'==valores[campo[j]]) || ('TRUE'==valores[campo[j]]))) mensaje+=salto + 'El campo ' + nombre[i] + ' debe ser un Si o un No';}
					else if('email'==tipo[i])	{if(!validar_email(valores[campo[j]]))	mensaje+=salto + 'El campo '+  nombre[i] + ' no es un ' + nombre[i] + ' válido';}
					else if('datetime'==tipo[i] || 'date'==tipo[i]){
						//if(sub(valores[campo[j]], ' ') && parte.length==2)	{parte=explode (' ', valores[campo[j]]);}
						//else	{parte[0]=valores[campo[j]];}
						//parte= explode('-', parte[0]);
						//if (parte.length!=3 || !isNaN (parte[0]) || ! isNaN(parte[1]) || !isNaN (parte[2]) || !checkdate(parte[1], parte[2], parte[0])) {return 'El campo ' + nombre[i] + ' debe ser una fecha válida';}
					}
					if (tamano[i][1] && valores[campo[j]].length < tamano[i][1]) mensaje+=salto + 'El campo ' + nombre[i] + ' debe tener una extensión mínima de ' + tamano[i][1] + ' carácteres';
					else if (tamano[i][0] && valores[campo[j]].length > tamano[i][0]) mensaje+=salto + 'El campo ' + nombre[i] + ' debe tener una extensión menor que ' + tamano[i][0] + ' carácteres';
				}
				else if('radio'==type[i]){
					existe=false;
					break;
				}
				++j;
			}
			//Comprueba si el campo es requerido y existe valor.
			if(1==requerido[i]  && false==existe )		mensaje+=salto + 'El campo ' + nombre[i] + ' falta y es requerido';
			if('Atención: hay errores en su formulario:\n'!=mensaje && !encontrado){
				encontrado=name[i];
				if(registros[0]>0)	encontrado+=registros[0];
			}
			++p;
		}
		++i;
	}
	if(confirmar)	mensaje+=salto + 'La confirmacion de la contraseña, no coincide';
	if(mensaje=='Atención: hay errores en su formulario:\n')	mensaje=null;
	
	return mensaje;
}	

/**
 *
 */
function validar_email(email){	
	var pru=0;
	var ext=email.length;
	for(n=0; n<ext && 2!=pru; ++n){	
		if('@'==email.charAt(n))	pru=1;
		if('.'==email.charAt(n) && 1==pru)	++pru;
	}
	if(2==pru)	return true;
	else return false;
}

/**
 *
 */
function focalizar(campo){
	if(document.getElementById(campo))	document.getElementById(campo).focus();
}

/**
 *
 */
function objetoFocus(campo){
	document.getElementById(campo).focus();
}

/**
 *
 */
function CheckIsIE(){
    if('MICROSOFT INTERNET EXPLORER'==navigator.appName.toUpperCase())   return true;
    else return false;
}

/**
 *
 */
function PrintThisPage(id, num){
	if(true==CheckIsIE()){
		if('ticket'==id){
			document.ticket.focus();
			document.ticket.print();
		}
		else if('factura'==id){
			document.factura.focus();
			document.factura.print();
		}
		else if('vale'==id){
			document.vale.focus();
			document.vale.print();
		}
	}
	else{	
		window.frames[num].focus();
		window.frames[num].print();
		//window.frames[num].imprimirFrame();
		/*window.frames[id].focus();
		window.frames[id].print();*/
	}
}


/*function imprimirFrame(){print();}*/

/**
 *
 */
/*
function recalcular(total, id, nombre_id, formas_pago, forma_pago_actual, tipoOperacion){

	//alert('total: ' + total + ' id: ' + id + ' nombre id:' + nombre_id  + ' forma de pago actual: ' + forma_pago_actual);
	if(document.getElementById(nombre_id + forma_pago_actual)){

		if(!document.getElementById(nombre_id + forma_pago_actual).value)	return 0;
	
		if(!tipoOperacion){
			if(document.getElementById(nombre_id + forma_pago_actual).value>0)	{}
			else{
				document.getElementById(nombre_id + forma_pago_actual).value=0;
				document.getElementById('pago' + forma_pago_actual).value='';
			}
		}
		else{
			if(document.getElementById(nombre_id + forma_pago_actual).value<0)	{}
			else{
				document.getElementById(nombre_id + forma_pago_actual).value=0;
				document.getElementById('pago' + forma_pago_actual).value='';
			}
		}
		
		valor = parseFloat(document.getElementById(nombre_id + forma_pago_actual).value);
		
		if(valor==''){
			document.getElementById(nombre_id + forma_pago_actual).value=total;
			document.getElementById('pago' + forma_pago_actual).value=forma_pago_actual;
		}
		else if((!tipoOperacion && valor>total) || (tipoOperacion && valor<total)){
			document.getElementById(nombre_id + forma_pago_actual).value=total;
			document.getElementById('pago' + forma_pago_actual).value=forma_pago_actual;
		}
		
		i=0;
		extension=0;
		total_parcial=0.00;
		num_formas_pago=formas_pago.length;
		
		while(i<num_formas_pago){
			if(forma_pago_actual!=formas_pago[i]){
				
				if((!tipoOperacion && document.getElementById(nombre_id + formas_pago[i]).value>0.00) || (tipoOperacion && document.getElementById(nombre_id + formas_pago[i]).value<0.00)){
					++extension;
					total_parcial=parseFloat(total_parcial) + parseFloat(document.getElementById(nombre_id + formas_pago[i]).value);
				}
			}
			++i;
		}
		
		num_cajas_pago=extension;
		//total_cajas=total_parcial;

		v_anterior=total-total_parcial;
		cantidad=parseFloat(v_anterior) - parseFloat(document.getElementById(nombre_id + forma_pago_actual).value);
		
		//Cantidad a repatir entre las distintas formas de pago.
		cantidad=cantidad/num_cajas_pago;
		i=0;
		while(i<num_formas_pago){
			if(forma_pago_actual!=formas_pago[i]){
				
				if(!tipoOperacion && document.getElementById(nombre_id + formas_pago[i]).value>0){
					document.getElementById(nombre_id + formas_pago[i]).value=redondear(parseFloat(document.getElementById(nombre_id + formas_pago[i]).value) + cantidad);
					if(document.getElementById(nombre_id + formas_pago[i]).value<0)	document.getElementById(nombre_id + formas_pago[i]).value=0;
				}
				else if(tipoOperacion && document.getElementById(nombre_id + formas_pago[i]).value<0){
					document.getElementById(nombre_id + formas_pago[i]).value=redondear(parseFloat(document.getElementById(nombre_id + formas_pago[i]).value) + cantidad);
					if(document.getElementById(nombre_id + formas_pago[i]).value>0)	document.getElementById(nombre_id + formas_pago[i]).value=0;
				}
			}
			if(0!=document.getElementById(nombre_id + formas_pago[i]).value)		document.getElementById('pago' + formas_pago[i]).value=formas_pago[i];
			else document.getElementById('pago' + formas_pago[i]).value='';
			++i;
		}
	}
}
*/

/**
 *
 */
function recalcular(total, id, nombre_id, formas_pago, forma_pago_actual, tipoOperacion, resetear){
	//alert(resetear);
	//alert('total: ' + total + ' id: ' + id + ' nombre id:' + nombre_id  + ' forma de pago actual: ' + forma_pago_actual);
	if(document.getElementById(nombre_id + forma_pago_actual)){

		//if(!document.getElementById(nombre_id + forma_pago_actual).value){
			//document.getElementById(nombre_id + forma_pago_actual).value=' ';
			//return 0;
		//}
		
		if(!tipoOperacion){
			//Operacion de venta.
			if(document.getElementById(nombre_id + forma_pago_actual).value>0.00)	{}
			else{
				document.getElementById(nombre_id + forma_pago_actual).value='';
				document.getElementById('pago' + forma_pago_actual).value='';
			}
		}
		else{
			//Operacion de devolucion.
			if(document.getElementById(nombre_id + forma_pago_actual).value<0.00)	{}
			else{
				document.getElementById(nombre_id + forma_pago_actual).value='';
				document.getElementById('pago' + forma_pago_actual).value='';
			}
		}
		
		valor=parseFloat(document.getElementById(nombre_id + forma_pago_actual).value);
		if(!valor)	valor=0;
		
		if(/*''==valor &&*/ resetear){
			document.getElementById(nombre_id + forma_pago_actual).value=total;
			document.getElementById('pago' + forma_pago_actual).value=forma_pago_actual;
		}
		else if((!tipoOperacion && valor>total) || (tipoOperacion && valor<total)){
			document.getElementById(nombre_id + forma_pago_actual).value=total;
			document.getElementById('pago' + forma_pago_actual).value=forma_pago_actual;
		}
		
		
		
		i=0;
		idUltimo=0;
		ultimo=0.00;
		restoTotal=0.00;
		parcialTotal=0.00;
		num_formas_pago=formas_pago.length;
		while(i<num_formas_pago){
			if(
			   		forma_pago_actual!=formas_pago[i] 
				 && (
					 	   (
							 	!tipoOperacion 
								&& 
								document.getElementById(nombre_id + formas_pago[i])
								&&
								document.getElementById(nombre_id + formas_pago[i]).value>0.00
						   ) 
						|| (tipoOperacion && document.getElementById(nombre_id + formas_pago[i]).value<0.00)
					)
				){				
				idUltimo=i;
				ultimo=parseFloat(document.getElementById(nombre_id + formas_pago[i]).value);
				parcialTotal+=ultimo;
			}
			++i;
		}
		
		//alert(total + ' - ' + parcialTotal);
		if(0.00==parcialTotal && !resetear)	document.getElementById(nombre_id + forma_pago_actual).value=total;	
		
		restoTotal=total-parcialTotal;
		restoTotal+=ultimo;
		//alert(restoTotal);
		ultimo=restoTotal;
		parcialTotal=total-parcialTotal;
		
		//alert(ultimo + ' - ' + valor);
		//Cantidad a repatir entre las distintas formas de pago.
		i=0;
		while(i<num_formas_pago){
			if(
			   	forma_pago_actual!=formas_pago[i]
				&& (
					   (!tipoOperacion 
							&& document.getElementById(nombre_id + formas_pago[i])
							&& document.getElementById(nombre_id + formas_pago[i]).value>0.00
							) 
					|| (tipoOperacion && document.getElementById(nombre_id + formas_pago[i]).value<0.00)
				   )
			  ){
				if(resetear)	document.getElementById(nombre_id + formas_pago[i]).value='';
				else{
					if(formas_pago[idUltimo]==formas_pago[i]){
						if((ultimo-valor>0.00 && !tipoOperacion) || (ultimo-valor<0.00 && tipoOperacion)){
							document.getElementById(nombre_id + formas_pago[i]).value=redondear(ultimo-valor);
						}
						else{
							if((!tipoOperacion && valor>parcialTotal) || (!tipoOperacion && valor<parcialTotal))	document.getElementById(nombre_id + forma_pago_actual).value=parcialTotal;
							else	document.getElementById(nombre_id + forma_pago_actual).value='';
						}
					}	
				}
				if((!tipoOperacion  && document.getElementById(nombre_id + formas_pago[i]).value<0.00) || (tipoOperacion  && document.getElementById(nombre_id + formas_pago[i]).value>0.00))	document.getElementById(nombre_id + formas_pago[i]).value='';				
			}
			if(document.getElementById(nombre_id + formas_pago[i])){
				if(0!=document.getElementById(nombre_id + formas_pago[i]).value){
					document.getElementById('pago' + formas_pago[i]).value=formas_pago[i];
				}
				else document.getElementById('pago' + formas_pago[i]).value='';
			}
			++i;
		}
	}
}

function redondear(numero){
	
	var original=parseFloat(numero);
	var result=Math.round(original*100)/100 ;
	return result;
}


/**
 * Introduce en el carrito de la compra todos los productos a devolver.
 */
function devoluciones(pag, ruta){
	if(document.getElementById('aniadir_todo').checked)		accion=true;
	else	accion=false;
	var i=0;
	var ext=ruta.length;
	while(i<ext){
		document.getElementById('devolver' + i).checked=accion;
		submitar(pag, ruta[i]);
		++i;
	}
}

/**
 *
 */
function borrar_descuento(id, id2, pag, ruta, e){
	if(document.getElementById(id2).value>0)	document.getElementById(id).value=0;
	if(13==pulsar(e) || pressIntro)	submitar(pag, ruta);
	//alert($(id).value);
}

/**
 *
 */
function pulsar(e){
	return (document.all) ? e.keyCode : e.which;
}


/**
 *
 */
function seleccionarLinea(id){
	if(document.getElementById(id).checked==false)	document.getElementById(id).checked=true;
	else document.getElementById(id).checked=false;
}

/**
 *
 */
function devolver(id_articulo, pag, ruta, ref, cantidad){
	if(document.getElementById(id_articulo).checked==false)	document.getElementById(id_articulo).checked=true;
	else document.getElementById(id_articulo).checked=false;

	hacer_devolucion(id_articulo, pag, ruta, ref, cantidad);
}

/**
 *
 */
function hacer_devolucion(id_articulo, pag, ruta, ref, cantidad){
	//Añado articulo a la cesta
	document.getElementById(id_articulo).value=document.getElementById(id_articulo).checked;
	aniadir_post(id_articulo);

	submitar(pag, ruta);
}

/**
 *
 */
function login_publico(formulario, url, e){
	cosa=true;
	modificar_contrasena();
	if(13==pulsar(e))	hacer(formulario, url);
}











/**
 *
 */
function cargarCampos(){
	i=0;
	if(!cargado){
		var formulario=document.forms[0];
		var ext=formulario.length;
		while(i<ext){
			if('hidden'!=formulario.elements[i].type && 'button'!=formulario.elements[i].type && formulario.elements[i].id && formulario.elements[i].name){	
				formulario.elements[i].onfocus = function(){campoEscribir=this.id; } 
			}
			++i;
		}
		cargado=true;
	}
}

/**
 *
 */
function escribir(letra, ac){
	//alert(campoEscribir);
	//if(!campoEscribir)	{

		//cargarCampos();
	//}
	
	campo=campoEscribir;
	if(campo){
		if('borrar'==ac)	document.getElementById(campo).value='';
		else if('atras'==ac){
			cad='';
			ext=document.getElementById(campo).value.length;
			for(i=0;i<ext-1;++i)	cad+=document.getElementById(campo).value.charAt(i);
			document.getElementById(campo).value=cad;
		}
		//else if('espaciar'==ac)		document.getElementById(campo).value+=' ';
		else{
			if('0'==document.getElementById(campo).value && '.'!=letra)	document.getElementById(campo).value='';
			if('buscar_id'==campo){
				//if(13==event.keyCode)	evento=true; 
				//else 
				evento=false;
				cosa=true;
				++pulsaciones; 
			}	
			document.getElementById(campo).value+=letra;
		}
	}
}

/**
 *
 */
function intro(e){
	//alert(document.getElementById(campo).onkeyup);
	if(campoEscribir){
		campo=document.getElementById(campoEscribir);
		if('buscar_id'==campoEscribir){
			evento=true;/*
			++pulsaciones; 
			cosa=true; 	*/
		}
		else{
			e.keyCode=13; 
			pressIntro=true;
			//e.which=13;
			if(campo.onkeyup)	campo.onkeyup();
			else if(campo.onkeydown)	campo.onkeydown(e);
			else if(campo.onkeypress)	campo.onkeypress(e);
			pressIntro=false;	
		}
	}
}









/****************** Bordes de botones en TPV **********************************************************/

function botonOver(id){
	//botonBordeBottom(id, '2', '-1');
	document.getElementById(id).style.borderBottomWidth='2px';
	document.getElementById(id).style.borderRightWidth='2px';
	document.getElementById(id).style.marginBottom='-1px';
	document.getElementById(id).style.marginRight='-1px';	
}

function botonOut(id){
	//botonBordeBottom(id, '1', '0');
	document.getElementById(id).style.borderBottomWidth='1px';
	document.getElementById(id).style.borderRightWidth='1px';
	document.getElementById(id).style.marginBottom='0px';
	document.getElementById(id).style.marginRight='0px';
	//if(document.getElementById(id).style.borderTopWidth=='2px')
	{
		//botonBordeTop(id, '1', '0');
		document.getElementById(id).style.borderTopWidth='1px'; 
		document.getElementById(id).style.borderLeftWidth='1px';
		//margenBottom(id, 0);
		document.getElementById(id).style.marginBottom='0px';
		document.getElementById(id).style.marginRight='0px';
	}
}

function botonOnclick(id){
	//botonBordeBottom(id, '1', '0');
	document.getElementById(id).style.borderBottomWidth='1px';
	document.getElementById(id).style.borderRightWidth='1px';
	//margenBottom(id, 0);
	/*
	document.getElementById(id).style.marginBottom='0px';
	document.getElementById(id).style.marginRight='0px';	
	*/
	//botonBordeTop(id, '2', '-1');
	document.getElementById(id).style.borderTopWidth='2px'; 
	document.getElementById(id).style.borderLeftWidth='2px';
	//margenBottom(id, -1);
	
	
	document.getElementById(id).style.marginBottom='-1px';
	document.getElementById(id).style.marginRight='-1px';	
	
}



function botonBordeBottom(id, borde, margen){	
	document.getElementById(id).style.borderBottomWidth=borde + 'px';
	document.getElementById(id).style.borderRightWidth=borde + 'px';
	margenBottom(id, margen);
}

function botonBordeTop(id, borde, margen){
	document.getElementById(id).style.borderTopWidth=borde + 'px'; 
	document.getElementById(id).style.borderLeftWidth=borde + 'px';
	margenBottom(id, margen);
}

function margenBottom(id, margen){
	document.getElementById(id).style.marginBottom=margen + 'px';
	document.getElementById(id).style.marginRight=margen + 'px';	
}

/****************** Bordes de botones en TPV **********************************************************/


/**
 *
 */
function enviarDocumentoEmail(campo, form, ruta, documento, email){	
	//Comprueba si hay email.
	if(document.getElementById(campo).value){
		if('Factura'!=documento && 'Devolucion'!=documento){
			if(confirm('El ' + documento + ' va a ser eviado a la dirección de e-mail: ' + document.getElementById(campo).value + '. ¿Desea continuar?'))		enviarFactura(campo, form, ruta);
		}
		else{
			if(confirm('La ' + documento + ' va a ser eviada a la dirección de e-mail: ' + document.getElementById(campo).value + '. ¿Desea continuar?'))	enviarFactura(campo, form, ruta);
		}
	}
}

/**
 *
 */
function enviarFactura(id, pag, enlaceEnviar){	
	//cosa=true;
	aniadir_post(id); 
	document.getElementById(id).value=''; 
	submitar(pag, enlaceEnviar); 
}

/**
 * Da formato de dos decimales a un tipo de dato float que recibe por parametro. 
 */
function precio(precio){
/*
  	precio=number_format(precio,2,',','.');

	if(strstr(precio, '.')){
		parte=explode('.', precio);
	  	ifparte[1]<10)	precio.='0';
	}

  	return precio;
*/
	var numero = new oNumero(precio)
	//document.write("El número: " + numero.valor+'<br>')
	//document.write("Formateado queda: ")
	return numero.formato(2, true);
}


//Objeto oNumero
function oNumero(numero){

//Propiedades
this.valor = numero || 0
this.dec = -1;
//Métodos
this.formato = numFormat;
this.ponValor = ponValor;

//Definición de los métodos
function ponValor(cad){
	if (cad =='-' || cad=='+') return
	if (cad.length ==0) return
	if (cad.indexOf('.') >=0)
		this.valor = parseFloat(cad);
	else
		this.valor = parseInt(cad);
}

function numFormat(dec, miles){
	var num = this.valor, signo=3, expr;
	var cad = ""+this.valor;
	var ceros = "", pos, pdec, i;
	for (i=0; i < dec; i++)
	ceros += '0';
	pos = cad.indexOf('.')
	if (pos < 0)
		cad = cad+"."+ceros;
	else
		{
		pdec = cad.length - pos -1;
		if (pdec <= dec)
			{
			for (i=0; i< (dec-pdec); i++)
				cad += '0';
			}
		else
			{
			num = num*Math.pow(10, dec);
			num = Math.round(num);
			num = num/Math.pow(10, dec);
			cad = new String(num);
			}
		}
	pos = cad.indexOf('.')
	if (pos < 0) pos = cad.lentgh
	if (cad.substr(0,1)=='-' || cad.substr(0,1) == '+')
		   signo = 4;
	if (miles && pos > signo)
		do{
			expr = /([+-]?\d)(\d{3}[\.\,]\d*)/
			cad.match(expr)
			cad=cad.replace(expr, RegExp.$1+','+RegExp.$2)
			}
	while (cad.indexOf(',') > signo)
		if (dec<0) cad = cad.replace(/\./,'')
			return cad;
}
}//Fin del objeto oNumero:
















/**
 *
 */
function cargarImagen(){
	$(document).ready(function() {
		//$("a[rel=productos]").fancybox({
		$("a.zoom").fancybox({
			'imageScale'  : true,
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic',
			'hideOnContentClick': true,
			'overlayOpacity': '0.36',
			'opacity': true,
			/*'titlePosition' 	: 'over',
			'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
				return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
			}
			*/
		});
	});
}

/**
 *
 */
function cargarPlantillas(){
	$(document).ready(function(){
		$(".enlao").fancybox({
		 	//'titlePosition'		: 'inside',
			//'autoScale' : true,
			'imageScale'  : false,
			'overlayShow'	: true,
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic',
			//'hideOnContentClick': true,
			//'autoDimensions': false,
			//'centerOnScroll': true

		});
		
		$("a.zoom").fancybox({
			'imageScale'  : false,
			'overlayShow'	: true,
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic',
			//'hideOnContentClick': true,
			'autoDimensions': true,
			'autoScale': true
			//'centerOnScroll': true
		});
	});
}

function cargTemplate(id, plantilla){
	document.getElementById(id).value=plantilla;	
}

/*function cargarImagen(){
	$(document).ready(function() {
		$("a.zoom").fancybox({
			'imageScale'  : true,
			'zoomSpeedIn'		:	300,
			'zoomSpeedOut'		:	300,
		});
	});
}*/

/**
 * Abre y cierra un div. 
 */
function cajaTienda(id){
	//$(id).parent().children('.modalbox').fadeToggle(200);
	//var id2=$(id).parent().children('.modalbox');
	//var id=$('.modalbox');
	if($(id).is(':visible')){	
		//$(id).fadeOut('slow');
		$(id).slideUp('fast');
	}
	else{
		//$(id).fadeIn(200);
		$(id).slideDown('fast');
	}
}


















/**
 *
 */
function buscarCliente(pag, id, div, ruta, ruta2){
	if(document.getElementById(id).value){
		aniadir_post(id);
		submitar(pag, ruta);
	}
	else	abrirVentana(div, ruta2, pag);
}

function abrirVentana2(div, ruta2, pag){
	///alert(div + ' - '+ ruta2 + ' - ' + pag);
	setTimeout('abrirVentana("' + div + '", "' + ruta2 + '", "' + pag + '")', 10);	
	//abrirVentana(div, ruta2, pag);	
}

function abrirVentana(div, ruta2, pag){
	if(!document.getElementById(div).innerHTML)	Cargar(div, ruta2, pag, post);
	mostrar_caja(div);	
}

/**
 *
 */
function consultarRef(pag, ext, id, ruta){
	var valoresEnviados=document.getElementById('caracteristicaFicha' + id).value;
	valoresEnviados=valoresEnviados.split(',');
	var extArray=valoresEnviados.length;
	//alert(valoresEnviados);
	var indiceFicha=-1;
	var resFicha=0;
	if(1==extArray){
		resFicha=buscarCoincidenciasRef(valoresEnviados[0], ext);
		indiceFicha=valoresEnviados[0];
	}
	else if(extArray>1){
		var i=0;
		var numFicha=0;
		while(i<extArray){
			resFicha=buscarCoincidenciasRef(valoresEnviados[i], ext);
			if(resFicha>numFicha){
				numFicha=resFicha;
				indiceFicha=valoresEnviados[i];
			}
			++i;
		}
	}
	//alert(indiceFicha);
	if(-1!=indiceFicha){
		//Envia el id de la referencia.	
		indiceFicha=indiceFicha.split('-');	
		//document.getElementById('valorEnviado').value=indiceFicha[1];
		//submitar(pag, ruta);
		//ruta+='&bo=fichaCar&pag=' + pag;
		//alert(ruta + ' ' + '&valorEnviado=' + indiceFicha[1]);
		Cargar('content', ruta, pag, '&valorEnviado=' + indiceFicha[1]);
		//Cargar(Objeto,Quien,Formulario,Valores_Propios){
		//alert(ruta);
	}
	else	alert('No se han encontrado resultados para esta configuración de características');	
}

function buscarCoincidenciasRef(valorEnviado, ext){
	var num=0;
	var i=0;
	while(i<ext){
		if(valorSelect=document.getElementById('caracteristicaFicha' + i).value){
			if(-1!=valorSelect.indexOf(valorEnviado))	++num;
		}
		++i;
	}
	return num;
}









function formatPrecio(precio){
	precio=precio.replace(/,/gi, '.');
	precio=parseFloat(precio);
	return precio;
}

function formatDecimales(precio){
	//precio=Math.floor(precio*100)/100;
	//precio=Math.round(precio*100)/100;
	precio=Math.round(precio*1000)/1000;
	return precio;
}

function calcularPvpCategoria(formulario){
	var i=0;
	formulario=document.getElementById(formulario);
	var ext=formulario.elements.length;
	campoPvp='';
	while(i<ext){

		if(formulario.elements[i].id && -1!=formulario.elements[i].name.indexOf('precio') && -1==formulario.elements[i].name.indexOf('precioCliente')){
			campoPvp=formulario.elements[i].name.replace(/precio/gi, 'pvp');
			calcularPvp(formulario.elements[i].name, campoPvp);
		}
		++i;
	}	
}















function cargarTemplateBoletin(opcion){
	Cargar('templateBoletin', 'ajax.php?op=' + opcion + '&su=te', 'admin', post);
}

function cargarSelect(idLab, idInput, copo){
	if(copo==document.getElementById(idInput).checked){
		//document.getElementById(obj).style.backgroundColor='#316ac5';
		$('#'+ idLab).addClass('labelSelect');
	} 
	else{
		//document.getElementById(obj).style.backgroundColor='#ffffff';
		 $('#'+ idLab).removeClass('labelSelect');
	}
}


function ponerOption(obj, id){
	//alert(obj.options[obj.selectedIndex].innerHTML);	
	document.getElementById(id).innerHTML=obj.options[obj.selectedIndex].innerHTML;
}


//Devuelve la fecha de hoy
function fecha_hoy(){
	fecha=new Date();
	if (fecha.getDate() < 10) dia = '0'+fecha.getDate();
	else dia = fecha.getDate();
	mes = fecha.getMonth() + 1;
	if (mes < 10) mes = '0'+mes;
	//hoy=dia+'-'+mes+'-'+fecha.getFullYear();
	hoy=fecha.getFullYear()+'-'+mes+'-'+dia;
	return hoy;
}

function cerrarDiv(id){
	$(id).click(function() {
		$(this).fadeOut(200, function() {
			$(this).hide();
		});
	});
}

/**
 * Cambia de tienda.
 */
function confirmarCambioTienda(id){
	if(confirm('Atención si cambia de tienda perderá todos los productos cargados en su carro de la compra. ¿Desea continuar?.'))	return true;
	else{ 
		cajaTienda(id);
		return false;
	}
}













/**
 *
 */
function urlencode( str ) {  
  
    var histogram = {}, histogram_r = {}, code = 0, tmp_arr = [];  
    var ret = str.toString();  
  
    var replacer = function(search, replace, str) {  
        var tmp_arr = [];  
        tmp_arr = str.split(search);  
        return tmp_arr.join(replace);  
    };  
  
    // The histogram is identical to the one in urldecode.  
    histogram['!']   = '%21';  
    histogram['%20'] = '+';  
  
    // Begin with encodeURIComponent, which most resembles PHP's encoding functions  
    ret = encodeURIComponent(ret);  
  
    for (search in histogram) {  
        replace = histogram[search];  
        ret = replacer(search, replace, ret) // Custom replace. No regexing  
    }  
  
    // Uppercase for full PHP compatibility  
    return ret.replace(/(\%([a-z0-9]{2}))/g, function(full, m1, m2) {  
        return "%"+m2.toUpperCase();  
    });  
  
    return ret;  
}  

/**
 *
 */
 /*
function sumar_post(ruta){
	//Envia el indicador de si ha pasado por el login.
	aniadir_post('l_logado_activo');
	aniadir_post('admin_buscar');
	if(document.getElementById('buscar_id') && -1==ruta.indexOf('ticket='))	sumar();
}
*/

