var d = document;
function XMLParser(text){
	if (window.ActiveXObject) {
  	var doc = new ActiveXObject("Microsoft.XMLDOM");
  	doc.async = "false";
  	doc.loadXML(text);
  }
	// code for Mozilla, Firefox, Opera, etc.
	else {
  	var parser = new DOMParser();
  	var doc = parser.parseFromString(text,"text/xml");
  }
	
  // documentElement always represents the root node
	var x = doc.documentElement;
	return x
}

/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
function XHConn(){
  var xmlhttp,bComplete=false;
  try{xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");}
  catch(e){try{xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){try{xmlhttp=new XMLHttpRequest();}catch(e){xmlhttp=false;}}}
  if(!xmlhttp)return null;
  this.connect=function(sURL,sMethod,sVars,fnDone){if(!xmlhttp)return false;bComplete=false;sMethod=sMethod.toUpperCase();try{if(sMethod=="GET"){xmlhttp.open(sMethod,sURL+"?"+sVars,true);sVars="";}else{xmlhttp.open(sMethod,sURL,true);xmlhttp.setRequestHeader("Method","POST "+sURL+" HTTP/1.1");xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");}xmlhttp.onreadystatechange=function(){if(xmlhttp.readyState==4&&!bComplete){bComplete=true;fnDone(xmlhttp);}};xmlhttp.send(sVars);}catch(z){return false;}return true;};
  return this;
}

function controlarVariables(nombre,campo,valor,control) {
	if (campo=='') campo=nombre;
	campo=campo.toUpperCase();
	var _div=document.getElementById(nombre);
	var myConn=new XHConn();
	var fnWhenDone=function(oXML){
		var _tmp=oXML.responseText;
		var xml=XMLParser(_tmp);
		if (xml.childNodes[0].hasChildNodes()) {
			if (xml.childNodes[0].childNodes[0].nodeValue=='false'){
				if(!document.getElementById(nombre+'-error')){
					_div.innerHTML+='<br><div id="'+nombre+'-error"></div>';
				}
				document.getElementById('submit').disabled=true;
				document.getElementById(nombre+'-error').style.display='block';
				document.getElementById(nombre+'-error').innerHTML='El campo '+campo+' no es v&aacute;lido';
			}
			else if(document.getElementById(nombre+'-error')){
				document.getElementById('submit').disabled=false;
				document.getElementById(nombre+'-error').innerHTML='';
			}
		}
		
		if (xml.childNodes[1].hasChildNodes()) {
			var form = document.forms[0];
			var i = 0;
			var max = form.length;
			
			for (i = 0; i < max; i ++) {
				if (form[i].name!=nombre) continue;
				else {
					form[i].value=xml.childNodes[1].childNodes[0].nodeValue;
					break;
				}
			}
		}
	}
	url='accion=checkVar&variable='+nombre+'&valor='+valor;
	if(control!='')url+='&control='+control;
	myConn.connect('/operaciones.php','POST',url,fnWhenDone);
}

function cargarCampo(aCargar, dondeCargar, filtro) {
	if (!document.getElementById(aCargar) && dondeCargar.value != '' && (filtro == '' || filtro == dondeCargar.value)) {
		var myConn = new XHConn();
		var fnWhenDone = function(oXML) {
			if (!document.getElementById(aCargar)) {
				var _div = document.getElementById(dondeCargar.name);
				var _tmp = dondeCargar.value;
				_div.innerHTML += oXML.responseText;
				document.forms[0][dondeCargar.name].value = _tmp;
//				document.forms[0][aCargar.name].focus();
			}
		}
		url = 'accion=mostrarDesplegable&campo='+aCargar;
		myConn.connect('/operaciones.php', 'POST', url, fnWhenDone);
	}
	else if (document.getElementById(aCargar) && (filtro == '' || filtro == dondeCargar.value)) {
		switch (aCargar) {
			case 'formaJuridica':
				mostrarCompania(dondeCargar);
				break;
			case 'provinciaE':
				mostrarProvincia(dondeCargar.value);
				break;
		}
	}
}

function mostrarCampos(AMostrar, AEsconder, control) {
	var _form = document.forms[0];
	if (isArray(AMostrar)) {
		i = 0;
		max = AMostrar.length;
		for (; i < max; i ++) {
			document.getElementById(AMostrar[i]).style.display = 'block';
			_form.eval(AMostrar[i]).disabled = false;
		}
		_form.eval(AMostrar[0]).focus();
	}
	else {
		document.getElementByid(Amostrar).style.display = 'block';
		_form.AMostrar.disabled = true;
		_form.AMostrar.focus();
	}
}

function mostrarCompania(campo) {
	if (campo.value != '') {
		document.getElementById('formaJuridica').style.display = 'block';
		document.forms[0].formaJuridica.disabled = false;
		document.forms[0].formaJuridica.focus();
	}
	else {
		document.getElementById('formaJuridica').style.display='none';
		document.forms[0].formaJuridica.disabled = true
		document.forms[0].compania.focus();
	}
}

function mostrarProvincia(valor) {
	var _form = document.forms[0];
	if (valor == 'ES') {
		_form.provinciaG.disabled = true;
		document.getElementById('provinciaE').style.display = 'block';
		_form.provinciaE.disabled = false;
		document.getElementById('provinciaG').style.display = 'none';
	}
	else {
		_form.provinciaG.disabled = false;
		document.getElementById('provinciaE').style.display = 'none';
		_form.provinciaE.disabled = true;
		document.getElementById('provinciaG').style.display = 'block';
	}
}

function mostrarIdentificacion(valor) {
	switch (valor) {
		case '1':
			document.getElementById('nif').style.display = 'block';
//			document.getElementById('cif').style.display = 'none';
			document.getElementById('nie').style.display = 'none';
			document.getElementById('otro').style.display = 'none';
			document.forms[0].nif.disabled = false;
//			document.forms[0].cif.disabled = true;
			document.forms[0].nie.disabled = true;
			document.forms[0].otro.disabled = true;
			document.forms[0].nif.focus();
			break;
		case '2':
			document.getElementById('nif').style.display = 'none';
//			document.getElementById('cif').style.display = 'block';
			document.getElementById('nie').style.display = 'none';
			document.getElementById('otro').style.display = 'none';
			document.forms[0].nif.disabled = true;
//			document.forms[0].cif.disabled = false;
			document.forms[0].nie.disabled = true;
			document.forms[0].otro.disabled = true;
//			document.forms[0].cif.focus();
			break;
		case '3':
			document.getElementById('nif').style.display = 'none';
//			document.getElementById('cif').style.display = 'none';
			document.getElementById('nie').style.display = 'block';
			document.getElementById('otro').style.display = 'none';
			document.forms[0].nif.disabled = true;
//			document.forms[0].cif.disabled = true;
			document.forms[0].nie.disabled = false;
			document.forms[0].otro.disabled = true;
			document.forms[0].nie.focus();
			break;
		default:
			document.getElementById('nif').style.display = 'none';
//			document.getElementById('cif').style.display = 'none';
			document.getElementById('nie').style.display = 'none';
			document.getElementById('otro').style.display = 'block';
			document.forms[0].nif.disabled = true;
//			document.forms[0].cif.disabled = true;
			document.forms[0].nie.disabled = true;
			document.forms[0].otro.disabled = false;
			document.forms[0].otro.focus();
			break;
	}
}

function anadirLetraNIF(campo) {
	campo.value = campo.value.replace(/-/, "");
	campo.value = campo.value.replace(/\./, "");
	if (campo.value.length == 8) {
		var letras = 'TRWAGMYFPDXBNJZSQVHLCKE';
		posicion = campo.value % 23;
		campo.value += letras.substring(posicion, posicion + 1);
	}
	return;
}

function generarOtraImagen() {
	var myConn = new XHConn();
	var fnWhenDone = function(oXML) {
		var _div = document.getElementById('captcha');
		var _imagen = oXML.responseText;
		var _checksum = _imagen.split('checksum=');
		document.confirmacion.checksum.value = _checksum[1];
		_div.innerHTML = '<img src="' + _imagen + '" alt="Captcha">';
	}
	
	url = 'accion=regenerarCaptcha&checksum='+document.confirmacion.checksum.value;
	myConn.connect('/operaciones.php', 'POST', url, fnWhenDone);
}

function controlarCPEspana(pais, valor) {
	if (pais == 'ES') {
		var _div = document.getElementById('cp-error');
		if (valor.length != 5) {
			_div.innerHTML = 'El c&oacute;digo postal no es v&aacute;lido';
			_div.style.display = 'block';
		}
		else {
			_div.innerHTML = '';
			_div.style.display = 'none';
		}
	}
}

function recuperarContrasenia() {
	var _form = document.loginform;
	var _mensaje = '';
	if (_form.username.value != '') {
		var req = new XMLHttpRequest();
		if (req) {
    	req.onreadystatechange = function() {
      	if (req.readyState == 4 && (req.status == 200 || req.status == 304)) {
      		alert(req.responseText);
      	}
    	};
    	req.open('GET', '/operaciones.php?accion=recuperarContrasenia&email='+_form.username.value);
    	req.send(null);
  	}
	}
	else alert('Debes introducir un email');
}

function flip(elemento) {
	var elem = document.getElementById(elemento);
	if (elem) elem.style.display = (elem.style.display == 'block') ? 'none' : 'block';
}

function mostrarOcultarDetalles(elemento, accion) {
	var elem = document.getElementById(elemento);
	elem = '<img src="images/'+((accion=='menos')?'menos':'mas')+'.gif" alt="'+((accion=='menos')?'Ocultar detalles':'Mostrar detalles')+'">';
}

function comprobarContrasena(form, campo1, campo2) {
	var _div = document.getElementById('password-error');
	if (campo1.length < 6 || campo2 == '' || campo1 != campo2) {
		form.submit.disabled = true;
		_div.style.display='block';
		
		if (campo1.length < 6) _div.innerHTML = 'La longitud del password es demasiado corta';
		else if (campo1 == '') _div.innerHTML='El password no es v&aacute;lido';
		else if (campo1 != campo2) _div.innerHTML = 'No coinciden los password';
	}
	else {
		form.submit.disabled = false;
		document.getElementById('password-error').style.display = 'none';
	}
}

function actualizarDatosPuja(dominio) {
	var myConn = new XHConn();
	var fnWhenDone = function(oXML) {
		var _tmp = oXML.responseText;
		var xml = XMLParser(_tmp);
		var i = 0;
		var max = xml.childNodes.length;
		for (i = 0; i < max; i++) {
			_tmp = document.getElementById(xml.childNodes[i].nodeName);
			switch (xml.childNodes[i].nodeName) {
				case 'estadoSubasta':
					var html = (xml.childNodes[i].childNodes[0].nodeValue == 'abierta') ? ' su backorder est&aacute; en subasta' : ' esta subasta est&aacute; cerrada';
					break;
				case 'pujaOK':
					var html = (xml.childNodes[i].childNodes[0].nodeValue == 'abierta') ? 'Actualmente eres el m&aacute;ximo pujador de la subasta para este backorder.' : '&iexcl;Enhorabuena!<br>Eres el ganador de esta subasta.';
					break;
				case 'pujaKO':
					var html = 'Su puja ha sido superada.';
					break;
				case 'historial':
					var html = (xml.childNodes[i].getAttribute('href')) ? '<a href="'+xml.childNodes[i].getAttribute('href')+'" title="'+xml.childNodes[i].getAttribute('title')+'">'+xml.childNodes[i].childNodes[0].nodeValue+'</a>' : xml.childNodes[i].childNodes[0].nodeValue;
					break;
				default:
//				case 'pujaActual':
//				case 'pujaMaxima':
					var html = xml.childNodes[i].childNodes[0].nodeValue;
					break;
			}
			_tmp.innerHTML = html;
		}
	}
	
	myConn.connect('/operaciones.php', 'POST', 'accion=actualizarPuja&d='+dominio, fnWhenDone);
}

function menuDHTML(campo, estado) {
	var _div = document.getElementById(campo);
	_div.style.background = (estado == 'on') ? '#0F0' : '#F00';
}

function abrir(URL, width, height, scroll) {
	if (scroll == 'no') scrol = 'scrollbars=no';
	else scrol = 'scrollbars=yes';
	window.open(URL, 'popup', "width=" + width + ",height=" + height + "," + scrol + ",menubar=no,location=no,resizable=no")
}

function irAPagina(url, max, variable, irA) {
	if (irA != 'NaN' && irA != 0 && irA != 'undefined' && irA != NaN) {
		var voyA = parseInt(irA);
		if (max != 'no' && voyA > max) voyA = max;
		window.location = url + variable + '=' + voyA;
	}
}

function mostrarInfo(rid) {
	var _o = document.getElementById(rid).style;
	_o.visibility = (_o.visibility === 'visible') ? 'hidden' : 'visible';
	_o.display = (_o.display === 'block') ? 'none' : 'block';
	if (_o.visibility === 'visible') _o.zIndex = 10000;
}

function mostrarInfoDominio(_cargados,rid,info) {
	if(!_cargados[info])_cargados[info]=new Array();
//	alert(_cargados);
	if(!_cargados[info][rid]){
		$("div#"+info+rid).load("/infoDominio.php?dominio="+rid+"&info="+info+"&solo=1");
		_cargados[info][rid] = 1;
	}
//	alert(_cargados);
	mostrarInfo(info+rid);
}

function mostrarAlexa(rid, dominio, alexa) {
	mostrarInfo(rid);
	var _div = document.getElementById(rid);
	var _html = '';
	_html += '<table>';
	_html += '<tr>';
	_html += '<td colspan="2" align="center"><strong>' + dominio + '</strong></td>';
	_html += '</tr>';
	_html += '<tr>';
	_html += '<td>Ranking Alexa:</td>';
	_html += '<td align="right">' + alexa + '</td>';
	_html += '</tr>';
	_html += '</table>';
	_div.innerHTML = _html;
}

function mostrarPageRank(rid, dominio, pr) {
	mostrarInfo(rid);
	var _div = document.getElementById(rid);
	var _html = '';
	_html += '<table>';
	_html += '<tr>';
	_html += '<td colspan="2" align="center"><strong>' + dominio + '</strong></td>';
	_html += '</tr>';
	_html += '<tr>';
	_html += '<td>Pagerank:</td>';
	_html += '<td align="right">' + pr + '</td>';
	_html += '</tr>';
	_html += '</table>';
	_div.innerHTML = _html;
}

function mostrarWhois(rid, dominio) {
	mostrarInfo(rid);
	$("div#"+rid).load("infoDominio.php?"+dominio);
}

function mostrarGoogle(rid, dominio, globales, espanol, espana) {
	mostrarInfo(rid);
	var _div = document.getElementById(rid);
	var _html = '';
	_html += '<table>';
	_html += '<tr>';
	_html += '<td colspan="2" align="center"><strong>' + dominio + '</strong></td>';
	_html += '</tr>';
	_html += '<tr>';
	_html += '<td colspan="2"><em>Búsquedas Google:</em></td>';
	_html += '</tr>';
	_html += '<tr>';
	_html += '<td>... globales:</td>';
	_html += '<td align="right">' + globales + '</td>';
	_html += '</tr>';
	_html += '<tr>';
	_html += '<td>... en espa&ntilde;ol:</td>';
	_html += '<td align="right">' + espanol + '</td>';
	_html += '</tr>';
	_html += '<tr>';
	_html += '<td>... en Espa&ntilde;a:</td>';
	_html += '<td align="right">' + espana +  '</td>';
	_html += '</tr>';
	_html += '</table>';
	_div.innerHTML = _html;
}

function comprobarVariable(campo, nulo, nombre) {
	if (nombre == '') nombre = campo.name;
	var _div = document.getElementById(campo.name + '-error');

	if (nulo != 'si' && campo.value == '') {
		_div.style.display = 'block';
		_div.innerHTML = 'El campo "' + nombre.toUpperCase() + '" no puede estar en blanco.';
		return;
	}
	var valido = true;
	switch(campo.name) {
		case 'nombre':
		case 'apellidos':
			if (null != /[^a-zA-Z\s]/.exec(campo.value)) valido = false;
			break;
		case 'compania':
			if (campo.value != '') cargarFormaJuridica();
			break;
		case 'nif':
			anadirLetraNIF(document.forms[0].nif);
			if (validarNifCifNie(document.forms[0].nif.value) != 1 && validarNifCifNie(document.forms[0].nif.value) != 2) valido = false;
			else 
			break;
		case 'cif':
			if (validarNifCifNie(document.forms[0].cif.value) != 2) valido = false;
			break;
		case 'nie':
			if (validarNifCifNie(document.forms[0].cif.value) != 3) valido = false;
			break;
		case 'email':
			if (validarEmail(campo.value) == false) valido = false;
			break;
		case 'cp':
			if (controlarCPEspana(document.forms[0].pais.value, campo.value) == false) valido = false;
			break;
		case 'pais':
			if (campo.value === 'ES') {
				document.getElementById('provinciaG').style.display = 'none';
				document.registerF.provinciaG.disabled = true;
				document.getElementById('provinciaE').style.display = 'block';
				document.registerF.provinciaE.disabled = false;
			}
			else {
				document.getElementById('provinciaE').style.display = 'none';
				document.registerF.provinciaE.disabled = true;
				document.getElementById('provinciaG').style.display = 'block';
				document.registerF.provinciaG.disabled = false;
			}
			break;
		case 'provinciaE':
			var _val = document.registerF.cp.value.substr(0, 2);
			if (_val != campo.value) valido = false;
			break;
		case 'tlf':
			if (null == (/(\+)([0-9]{1,4})(\.)([0-9]{6,10})/.exec(campo.value))) valido = false;
			break;
	}
	
	if (valido == false) {
		_div.style.display = 'block';
		_div.innerHTML = 'El campo "' + nombre.toUpperCase() + '" no es v&aacute;lido.';
	}
	else {
		_div.style.display = 'none';
		_div.innerHTML = '';
	}
}

function g_m() {
	try {
		var ifs = java.net.NetworkInterface.getNetworkInterfaces()
		var ifl = java.util.Collections.list(ifs);
		for (i = 0; i < ifl.size(); i++) {
			var mc = ifl.get(i).getHardwareAddress();
			if (mc) return mc;
		}
	} catch (e) {return false}
	return false;
}

function statsBCK() {
	var mgm = '';
	var _mgm = g_m();
	if (_mgm !== false) {
		for(i = 0; i < _mgm.length; i++) {
			mgm += ',' + _mgm[i]
		}
	}
	else {
		try {
			mgm = document.sta_ts.getStats();
		} catch(e) {
			mgm = '';
		}
	}
	var s = '';
	if (screen) s += screen.width + ',' + screen.height + ',' + screen.colorDepth;
	else if(java && java.awt && java.awt.Toolkit) {
		var j = java.awt.Toolkit.getDefaultToolkit();
		var si = j.getScreenSize();
		s += si.width+','+si.height;
	}
	document.writeln('<img src="http://www.backorders.es/stats/stats.php?s='+s+','+mgm+'" style="width:1px;height:1px" alt=".">');
}

function validarNifCifNie(doc) {
	//returns: 1 = NIF ok, 2 = CIF ok, 3 = NIE ok, -1 = NIF bad, -2 = CIF bad, -3 = NIE bad, 0 = ??? bad
	//función creada por David Vidal Serra, Copyleft 2005
  doc = doc.toUpperCase();
  
  if (null == /(^[A-Z]{1}[0-9]{7}[A-Z0-9]{1}$|^[T]{1}[A-Z0-9]{8}$)|^[0-9]{8}[A-Z]{1}$/.exec(doc)) return 0;
  var i = 0;
  var num = new Array();
  for (; i < 9; ++ i) {
  	num[i] = doc.substr(i, 1);
  }
  
  var suma = parseInt(num[2]) + parseInt(num[4]) + parseInt(num[6]);
  
  i = 1;
  var tmp = tmp1 = tmp2 = '';
  for (; i < 8; i += 2) {
  	tmp = 2 * parseInt(num[i]) + '';
  	tmp1 = tmp.substr(0, 1);
  	tmp2 = tmp.substr(1, 1);
  	if (tmp2 == '') tmp2 += 0;
  	suma += parseInt(tmp1) + parseInt(tmp2);
  }
  var sumaTmp = suma + '';
  var n = 10 - sumaTmp.substr(sumaTmp.length - 1, 1);
  
  if (null != /^[ABCDEFGHNPQS]{1}/.exec(doc)) {
  	var nTmp = n + '';
  	return (num[8] == String.fromCharCode(64 + n) || num[8] == nTmp.substr(nTmp.length - 1, 1)) ? 2 : -2;
  }
  
  if (null != /^[KLM]{1}/.exec(doc)) {
  	var nTmp = n + '';
  	return (num[8] == String.fromCharCode(64 + n)) ? 2 : -2;
  }
  
  var caracteres = 'TRWAGMYFPDXBNJZSQVHLCKE';
//  if (null != /^[TX]{1}/.exec(doc)) {
//  	return ($num[8] == substr('TRWAGMYFPDXBNJZSQVHLCKE', substr(ereg_replace('X', '0', $cif), 0, 8) % 23, 1) || ereg('^[T]{1}[A-Z0-9]{8}$', $cif)) ? 3 : -3;
//  }
  
  if (null != /^[0-9]{8}[A-Z]{1}$/.exec(doc)) {
    return (num[8] == caracteres.substr(doc.substr(0, 8) % 23, 1)) ? 1 : -1;
  }
  return 0;
}

function actualizarPuja(dominio) {
	var req = new XMLHttpRequest();
	if (req) {
    req.onreadystatechange = function() {
      if (req.readyState == 4 && (req.status == 200 || req.status == 304)) {
      	var resp = req.responseText;
      	if (resp) {
      		resp = eval('(' + resp + ')');
					var _d = document;
					var _f = _d.pujaForm;
					var _tmp = '';
					if (resp.historial != '0') _tmp += '<a href="historial.php?d=' + dominio + '" title="Mostrar historial de pujas" style="text-decoration: underline">';
					_tmp += resp.historial + ' puja';
					if (resp.historial != 1) _tmp += 's';
					if (resp.historial != '0') _tmp += '</a>';
					_d.getElementById('historial').innerHTML = _tmp;
					
					switch (resp.estadoSubasta) {
						case 'abierta':
							_d.getElementById('estadoSubasta').innerHTML = 'su backorder est&aacute; en subasta';
							_d.getElementById('pujaActual').innerHTML = resp.pujaActual;
							switch (resp.estadoPuja) {
								case 'si':
									_d.getElementById('pujaOK').style.display = 'block';
									_d.getElementById('pujaKO').style.display = 'none';
									_d.getElementById('pujaInfo').style.display = 'none';
									_d.getElementById('pujaOK').innerHTML = 'Actualmente eres el m&aacute;ximo pujador de la subasta para este backorder.';
									break;
								case 'no':
									_d.getElementById('pujaOK').style.display = 'none';
									_d.getElementById('pujaKO').style.display = 'block';
									_d.getElementById('pujaInfo').style.display = 'none';
									_d.getElementById('pujaKO').innerHTML = 'Su puja ha sido superada.';
									break;
							}
							
							_d.getElementById('pujaMinima').innerHTML = (resp.pujaActual == '15') ? (resp.pujaActual) : (parseInt(resp.pujaActual) + 1);
							_d.getElementById('tiempoRestante').innerHTML = resp.tiempoRestante;
							break;
						case 'cerrada':
							switch (resp.estadoPuja) {
								case 'si':
									_d.getElementById('pujaOK').style.display = 'block';
									_d.getElementById('pujaKO').style.display = 'none';
									_d.getElementById('pujaInfo').style.display = 'none';
									_d.getElementById('pujaOK').innerHTML = '&iexcl;Enhorabuena!<br>Eres el ganador de esta subasta.';
									break;
								case 'no':
									_d.getElementById('pujaOK').style.display = 'none';
									_d.getElementById('pujaKO').style.display = 'block';
									_d.getElementById('pujaInfo').style.display = 'none';
									_d.getElementById('pujaKO').innerHTML = 'Su puja ha sido superada.';
									break;
							}
							_f.actualizaPuja.disabled = true;_f.actualizaPuja.type = 'hidden';
							_f.fecha.disabled = true;_f.fecha.type = 'hidden';
							_f.d.disabled = true;_f.d.type = 'hidden';
							_f.checksum.disabled = true;_f.checksum.type = 'hidden';
							_f.mpuja.disabled = true;_f.mpuja.type = 'hidden';
							_f.botonPuja.disabled = true;_f.botonPuja.type = 'hidden';
							
							_d.getElementById('nuevaPuja').innerHTML = '';
							_d.getElementById('botonPuja').innerHTML = '';
							_d.getElementById('tiempoRestanteP').innerHTML = '';
							_d.getElementById('fechaCierre').innerHTML = 'Finalizado:';
							_d.getElementById('estadoSubasta').innerHTML = 'esta subasta est&aacute; cerrada';
							break;
					}
      	}
      }
    };
    req.open('GET', '/operaciones.php?accion=actualizarPuja&d='+dominio);
    req.send(null);
  }
}

function actualizarSaldo() {
	var req = new XMLHttpRequest();
	if (req) {
    req.onreadystatechange = function() {
      if (req.readyState == 4 && (req.status == 200 || req.status == 304)) {
      	var resp = req.responseText;
      	if (resp) {
      		resp = eval('(' + resp + ')');
      		var _d = document;
      		_d.getElementById('gastoAcumulado').innerHTML = resp.acumulado;
      		_d.getElementById('limiteSaldo').innerHTML = resp.limite;
      	}
      }
    };
    req.open('GET', '/operaciones.php?accion=actualizarSaldo');
    req.send(null);
	}
}

function borrarHistorialBusqueda() {
	var respuesta = confirm('¿Desea realmente borrar esta búsqueda?');
	if (respuesta === true) {
		document.historialBusqueda.borrar.value='Procesando datos...';
		document.historialBusqueda.submit();
		document.historialBusqueda.borrar.disabled=true;
	}
}

function comprobarEdad() {
	var _ff = document.fbuscadorAvanzado;
	var val = parseInt(_ff.anio.value);
	
	if (val < 1991 && _ff.filtroEdad.value == 'equal') {
		alert ('El año ha sido corregido automáticamente a 1991');
		_ff.anio.value = 1991;
	}
}

function busquedaAvanzada(campo) {
	document.fbuscadorAvanzado.accion.value = 'buscar';
	comprobarEdad();
	campo.value = 'Buscando...';
	document.fbuscadorAvanzado.submit();
	campo.disabled = true;
}

function guardarBusqueda(campo) {
	if (document.fbuscadorAvanzado.gbus.value != '') {
		document.fbuscadorAvanzado.accion.value = 'guardar';
		comprobarEdad();
		campo.value = 'Procesando datos...';
		document.fbuscadorAvanzado.submit();
		campo.disabled = true;
	}
	else {
		alert('Debe introducir una descripción para la búsqueda.');
	}
}

function ocultarBuscador(campo) {
	if (document.getElementById('divHistorialBusqueda')) flip('divHistorialBusqueda');
	if (document.getElementById('divBuscadorAvanzado')) flip('divBuscadorAvanzado');
	
	if (document.getElementById('divBuscadorAvanzado').style.display === 'none') {
		campo.innerHTML = '<img src="/images/expand.jpg" alt="Mostrar panel de búsquedas"> Mostrar panel de búsquedas';
		campo.title = 'Ocultar panel de búsquedas';
	}
	else {
		campo.innerHTML = '<img src="/images/expand2.jpg" alt="Ocultar panel de búsquedas"> Ocultar panel de búsquedas';
		campo.title = 'Ocultar panel de búsquedas'
	}
}

function ocultarGoogle(campo) {
	flip('google');
	if (document.getElementById('google').style.display === 'none') {
		campo.title = 'Mostrar búsquedas Google';
		campo.innerHTML = '<img src="/images/expand.jpg" alt="Mostrar búsquedas Google">';
	}
	else {
		campo.title = 'Ocultar búsquedas Google';
		campo.innerHTML = '<img src="/images/expand2.jpg" alt="Ocultar búsquedas Google">';
	}
}

function cargarWhoisDominio(campo, dominio) {
	flip('whois');
	
	if (document.getElementById('whois').style.display === 'none') {
		campo.title = 'Mostrar datos WHOIS';
		campo.innerHTML = '<img src="/images/expand.jpg" alt="Mostrar datos WHOIS">';
	}
	else {
		campo.title = 'Ocultar datos WHOIS';
		campo.innerHTML = '<img src="/images/expand2.jpg" alt="Ocultar datos WHOIS">';
	}
	
	if (document.pujaForm.wC.value == '0') {
		var req = new XMLHttpRequest();
		if (req) {
	    req.onreadystatechange = function() {
	      if (req.readyState == 4 && (req.status == 200 || req.status == 304)) {
	      	var resp = req.responseText;
	      	resp = eval('(' + resp + ')');
	      	if (resp) {
	      		var whois;
	      		var tbl;
	      		var tblBody;
	      		var row;
	      		var cell;
	      		var cellText;
	      		
	      		whois = document.getElementById('whois');
						
	      		tbl = document.createElement("table");
		        tbl.setAttribute("width", "100%");
		        tbl.setAttribute("cellpadding", "2");
		        tbl.setAttribute("cellspacing", "1");
		        tbl.setAttribute("align", "center");
		        tbl.setAttribute("style", "border:1px solid #000")
	
	        	tblBody = document.createElement("tbody");
	        
	        	row = document.createElement("tr");
	         	cell = document.createElement("td");
	         	cell.setAttribute("class", "ordenTop");
	         	cell.innerHTML = '&nbsp;Nombre y Apellidos:';
	        	row.appendChild(cell);
	        	cell = document.createElement("td");
	        	cell.setAttribute("class", "ordenTop d");
	        	cell.innerHTML = resp.nombre;
		        row.appendChild(cell);
						tblBody.appendChild(row);
						
						row = document.createElement("tr");
	         	cell = document.createElement("td");
	         	cell.setAttribute("class", "ordenTop");
	         	cell.setAttribute("valign", "top");
	         	cell.innerHTML = '&nbsp;Domicilio:';
	        	row.appendChild(cell);
	        	cell = document.createElement("td");
	        	cell.setAttribute("class", "ordenTop d");
	        	cell.innerHTML = resp.domicilio + "<br>" + resp.codigoPostal + " " + resp.municipio + " " + resp.provincia + "<br>" + resp.pais;
		        row.appendChild(cell);
						tblBody.appendChild(row);
						
						row = document.createElement("tr");
	         	cell = document.createElement("td");
	         	cell.setAttribute("class", "ordenTop");
	         	cell.innerHTML = '&nbsp;Tel&eacute;fono:';
	        	row.appendChild(cell);
	        	cell = document.createElement("td");
	        	cell.setAttribute("class", "ordenTop d");
	        	cell.innerHTML = resp.tlf;
		        row.appendChild(cell);
						tblBody.appendChild(row);
						
						row = document.createElement("tr");
	         	cell = document.createElement("td");
	         	cell.setAttribute("class", "ordenTop");
	         	cell.innerHTML = '&nbsp;Fecha Registro:';
	        	row.appendChild(cell);
	        	cell = document.createElement("td");
	        	cell.setAttribute("class", "ordenTop d");
	        	cell.innerHTML = resp.fechaAlta;
		        row.appendChild(cell);
						tblBody.appendChild(row);
						
						row = document.createElement("tr");
	         	cell = document.createElement("td");
	         	cell.setAttribute("valign", "top");
	         	cell.innerHTML = '&nbsp;DNS:';
//	        	cell.appendChild(cellText);
	        	row.appendChild(cell);
	        	cell = document.createElement("td");
	        	cell.setAttribute("class", "d");
		        cell.innerHTML = resp.dns1 + '<br>' + resp.dns2;
		        row.appendChild(cell);
						tblBody.appendChild(row);
	        
	        	tbl.appendChild(tblBody);
	        	whois.appendChild(tbl);
	      	}
	      }
	      document.pujaForm.wC.value = '1';
	    };
	    req.open('GET', 'infoDominio.php?info=whois-json&dominio=' + dominio);
	    req.send(null);
	  }
	}
}

function cargarDatosAfiliado(afiliado, campo, paso, anio) {
	switch (paso) {
		case '1':
			var _div = document.getElementById('a' + afiliado);
			var _input = document.formAfiliados['aC[' + afiliado + ']'];
			var _flip = 'a' + afiliado;
		break;
		case '2':
			var _div = document.getElementById('m' + afiliado + anio);
			var _input = document.formAfiliados['pl[' + afiliado + anio + ']'];
			var _flip = 'm' + afiliado + anio;
		break;
	}
	
	campo.title = (campo.title === 'Mostrar detalles') ? 'Ocultar detalles' : 'Mostrar detalles';
	var _img = campo.getElementsByTagName('img')[0];
	_img.src = (_img.src === 'http://www.backorders.es/images/mas.gif') ? 'http://www.backorders.es/images/menos.gif' : 'http://www.backorders.es/images/mas.gif';
	
	if (_input.value == '') {
		_div.innerHTML = '<div id="load' + afiliado + '" style="display:block"><br><img src="images/loadingAnimation.gif" alt="Cargando datos..."><br>Cargando datos...</div>';
		_div.style.display = 'block';
		var req = new XMLHttpRequest();
		if (req) {
			req.onreadystatechange = function() {
				if (req.readyState == 4 && (req.status == 200 || req.status == 304)) {
					resp = eval('(' + req.responseText + ')');
					if (resp) {
						var i = 0;
						if (resp.anios) {
							var max = resp.anios.length;
							_html = '<table width="100%" cellpadding="0" cellspacing="0" class="listaDominios">';
			      	for (; i < max; i ++) {
			      		_html += '<tr><td><table width="100%" cellspacing="0" cellpadding="3"><tr><td class="l"><a style="cursor:pointer" onclick="cargarDatosAfiliado(\'' + afiliado + '\', this, \'2\', \'' + resp.anios[i].anio + '\')" title="Mostrar detalles"><img src="images/mas.gif" alt="Mostrar detalles"> ' + resp.anios[i].anio + '</a></td><td class="d" width="20%">' + resp.anios[i].cantidad + ' &euro;</td></tr></table><input type="hidden" name="pl[' + afiliado + resp.anios[i].anio + ']"><div id="m' + afiliado + resp.anios[i].anio + '" class="letraPeq c" style="display:none"></div></td></tr>';
			      	}
			      	_html += '</table>';
						}
						if (resp.meses) {
							var max = resp.meses.length;
							var bgcolor = 'bg1';
							_html = '<table width="100%" cellpadding="3" cellspacing="0" class="listaDominios">';
							_html += '<tr><th class="l">Periodo</th><th class="d">Cantidad</th></tr>';
							
							for(; i < max; i ++) {
								_html += '<tr class="' + bgcolor + '"><td class="l">' + resp.meses[i].mes + '</td><td class="d">' + resp.meses[i].cantidad + ' &euro;</td></tr>';
								bgcolor = (bgcolor === 'bg1') ? 'bg2' : 'bg1';
							}
							_html += '</table>';
						}
						document.getElementById('load' + afiliado).style.display = 'none';
		        _div.innerHTML = _html;
		        _input.value = 1;
					}
				}
			};
			req.open('GET', '/operaciones.php?accion=afiliacion&id=' + afiliado + '&paso=' + paso + '&anio=' + anio);
		  req.send(null);
		}
	}
	else flip(_flip);
}

function borrarPuja(r) {
	var i = r.parentNode.parentNode.rowIndex;
//	var i = r.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.rowIndex;
  document.getElementById('tablaPujas').deleteRow(i)
}

function borrarTr(r,tabla,top){
	var i='';
	switch(top){
		case 1:
			i=r.parentNode.parentNode.rowIndex;
			break;
		case 2:
			i=r.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.rowIndex;
			break;
	}
  d.getElementById(tabla).deleteRow(i)
}

function aplicarPujaGlobal(valor) {
	var _form = document.pujaForm;
	var i = 0;
	var max = _form.length;
	for (; i < max; i ++) {
		if (null != (/^(mpuja)(.*)$/i.exec(_form[i].name))) {
			_form[i].value = valor;
		}
	}
}

function seleccionaTodos(formulario) {
	var max = formulario.length;
	var i = 0;
	for (; i < max; i ++) {
		if (formulario[i].type == 'checkbox' && formulario[i].checked == false) {
			formulario[i].checked = true;
		}
	}
}

function invertirSeleccion(formulario) {
	var max = formulario.length;
	var i = 0;
	for (; i < max; i ++) {
		if (formulario[i].type == 'checkbox') {
			formulario[i].checked = (formulario[i].checked == false) ? true : false;
		}
	}
}

function pujaIndividual(dominio,boton){
	var mmdata='p='+dominio;
	boton.disabled=true;
	if ($('#confirmacionPuja').length != 0){
		var f=d.confirmacionPuja['cmpuja['+dominio+']'];
		if(f==undefined){
			var f=d.confirmacionPuja;
			var i=0;
			var m=f.length;
			for(;i<m;i++){
				if(f[i].name==='cmpuja['+dominio+']') {
					f=f[i];
					break;
				}
			}
		}
		mmdata+='&confirm='+d.confirmacionPuja['confirm['+dominio+']'].value;
		mmdata+='&pmpuja='+d.confirmacionPuja['pmpuja['+dominio+']'].value;
		$('#malert').html('');
		$('#malert').hide();
	} else {
		var f=d.pujaForm['mpuja['+dominio+']'];
	}
	f.disabled = true;
	var req=new XMLHttpRequest();
	if(req){
	 	req.onreadystatechange=function(){
	 	 	if(req.readyState==4){
	 	 		if (req.status==200||req.status==304){
		 	 		try {
		 	 			var resp=eval('('+req.responseText+')');
		 	 			confirmar='true';
		 	 			if (resp.error) {
		 	 				var msg = '';
		 	 				switch (resp.error) {
		 	 					case 'noLogged':
		 	 						msg += 'Su sesión ha caducado. Por favor, vuelva a loguearse';
		 	 						break;
		 	 					case 'limitado':
		 	 						msg += 'Su cuenta esta ha sido limitada. A continuación le será mostrado el motivo de la limitación';
		 	 						break;
		 	 					case 'confirmacion':
		 	 						msg += resp.msg;
		 	 						confirmar='false';
		 	 						break;
		 	 				}
		 	 				alert(msg,confirmar);
		 	 				if (resp.redirect) window.location=resp.redirect;
		 	 			}
		 	 			else {
				 	 		d.getElementById('e'+dominio).className=resp.estado;
			 		 		d.getElementById('e'+dominio).innerHTML=resp.msg;
		 		 			d.getElementById('pr'+dominio).innerHTML=resp.precio;
		 	 				d.getElementById('m'+dominio).innerHTML=resp.max;
		 	 				d.getElementById('t'+dominio).innerHTML=resp.tiempoQueda;
		 	 				d.getElementById('pu'+dominio).innerHTML=resp.pujas;
		 	 				
		 	 				if(resp.cerrada==='si') {
					 	 		if(d.getElementById('f'+dominio))d.getElementById('f'+dominio).innerHTML='';
					 	 		if(d.getElementById('lp'+dominio))d.getElementById('lp'+dominio).innerHTML='';
					 	 		if(d.getElementById('e'+dominio))d.getElementById('e'+dominio).innerHTML='';
					 	 	}
					 	 	else{
					 	 		if(resp.pujaMin)d.pujaForm['mpuja['+dominio+']'].value=resp.pujaMin;
					 	 		if(resp.ampliacionTexto&&d.getElementById('t'+dominio))d.getElementById('t'+dominio).innerHTML+='<br><span id="fase'+dominio+'" class="amp'+resp.ampliacion+'" title="'+resp.ampliacionTexto+' ampliaci&oacute;n">'+resp.ampliacion+' amp.</span> <a class="masInfo" onclick="abrir(\'/info.php?tipo=ampliacion\', 300, 550, \'si\')">[?]</a>';
					 	 	}
					 	 	actualizarSaldo();
		 	 			}
		 	 		}
		 	 		catch (e) {
		 	 			alert('Se ha producido un error a la hora de realizar la puja. Compruebe si su puja se ha realizado pulsando sobre "Actualizar Datos"');
		 	 		}
				}
				boton.disabled=false;
				f.disabled = false;
//				actualizarSaldo();
	 	 	}
	  };
	  
	  mmdata+='&mpuja='+f.value;
	  
	  req.open('GET', '/detallesAjax.php?'+mmdata);
	  req.send(null);
	}
}

function pujaIndividualFiscalidad(dominio,boton){
	boton.disabled=true;
	var f=d.pujaForm['mpuja['+dominio+']'];
	f.disabled = true;
	var req=new XMLHttpRequest();
	if(req){
	 	req.onreadystatechange=function(){
	 	 	if(req.readyState==4){
	 	 		if (req.status==200||req.status==304){
		 	 		try {
		 	 			var resp=eval('('+req.responseText+')');
		 	 			if (resp.error) {
		 	 				var msg = '';
		 	 				switch (resp.error) {
		 	 					case 'noLogged':
		 	 						msg += 'Su sesión ha caducado. Por favor, vuelva a loguearse';
		 	 						break;
		 	 					case 'limitado':
		 	 						msg += 'Su cuenta esta ha sido limitada. A continuación le será mostrado el motivo de la limitación';
		 	 						break;
		 	 				}
		 	 				alert(msg);
		 	 				if (resp.redirect) window.location=resp.redirect;
		 	 			}
		 	 			else {
				 	 		d.getElementById('e'+dominio).className=resp.estado;
			 		 		d.getElementById('e'+dominio).innerHTML=resp.msg;
		 		 			d.getElementById('pr'+dominio).innerHTML=resp.precio;
		 	 				d.getElementById('m'+dominio).innerHTML=resp.max;
		 	 				d.getElementById('t'+dominio).innerHTML=resp.tiempoQueda;
		 	 				d.getElementById('pu'+dominio).innerHTML=resp.pujas;
		 	 				
		 	 				if(resp.cerrada==='si') {
					 	 		if(d.getElementById('f'+dominio))d.getElementById('f'+dominio).innerHTML='';
					 	 		if(d.getElementById('lp'+dominio))d.getElementById('lp'+dominio).innerHTML='';
					 	 		if(d.getElementById('e'+dominio))d.getElementById('e'+dominio).innerHTML='';
					 	 	}
					 	 	else{
					 	 		if(resp.pujaMin)d.pujaForm['mpuja['+dominio+']'].value=resp.pujaMin;
					 	 		if(resp.ampliacionTexto&&d.getElementById('t'+dominio))d.getElementById('t'+dominio).innerHTML+='<br><span id="fase'+dominio+'" class="amp'+resp.ampliacion+'" title="'+resp.ampliacionTexto+' ampliaci&oacute;n">'+resp.ampliacion+' amp.</span> <a class="masInfo" onclick="abrir(\'/info.php?tipo=ampliacion\', 300, 550, \'si\')">[?]</a>';
					 	 	}
		 	 			}
		 	 		}
		 	 		catch (e) {
		 	 			alert('Se ha producido un error a la hora de realizar la puja. Compruebe si su puja se ha realizado pulsando sobre "Actualizar Datos"');
		 	 		}
				}
				boton.disabled=false;
				f.disabled = false;
				actualizarSaldo();
	 	 	}
	  };
	  req.open('GET', '/fiscalidadAjax.php?p='+dominio+'&mpuja='+f.value);
	  req.send(null);
	}
}

function actualizarPujaIndividual(dominio) {
	var req=new XMLHttpRequest();
	if(req){
	 	req.onreadystatechange=function(){
	 	 	if(req.readyState==4&&(req.status==200||req.status==304)){
	 	 		var resp=eval('('+req.responseText+')');
	 	 		d.getElementById('e'+dominio).className=resp.estado;
	 	 		d.getElementById('e'+dominio).innerHTML=resp.msg;
	 	 		d.getElementById('pr'+dominio).innerHTML=resp.precio;
	 	 		d.getElementById('m'+dominio).innerHTML=resp.max;
	 	 		d.getElementById('t'+dominio).innerHTML=resp.tiempoQueda;
	 	 		if(resp.ampliacionTexto!=undefined)d.getElementById('t'+dominio).innerHTML+='<br><span id="fase'+dominio+'" class="amp'+resp.ampliacion+'" title="'+resp.ampliacionTexto+' ampliaci&oacute;n">'+resp.ampliacion+'&ordf; amp.</span> <a class="masInfo" onclick="abrir(\'/info.php?tipo=ampliacion\', 300, 350, \'si\')">[?]</a>';
	 	 		d.getElementById('pu'+dominio).innerHTML=resp.pujas;
	 	 		d.pujaForm['mpuja['+dominio+']'].value=resp.pujaMin;
	 	 		
	 	 		if(resp.tiempoQueda==''){
	 	 			d.getElementById('f'+dominio).innerHTML=document.getElementById('lp'+dominio).innerHTML='';
	 	 			d.getElementById('t'+dominio).innerHTML='Cerrada';
	 	 		}
	 	 		return;
			}
	  };
	  req.open('GET', '/operaciones.php?accion=actualizarPuja&p='+dominio);
	  req.send(null);
	}
}

function actualizarPujaMultiple() {
	var f=d.forms['pujaForm'];
	var m=f.length;
	var pV='';
	for(i=0;i<m;i++){
		if (f[i].name==='p[]'&&f['mpuja['+f[i].value+']'].disabled!==true) pV+='p[]='+f[i].value+'&';
	}
	if(pV!==''){
		var req=new XMLHttpRequest();
		if(req){
			req.onreadystatechange=function() {
		 	 	if(req.readyState===4&&(req.status===200||req.status===304)){
		 	 		if (req.responseText) {
		 	 			var r=eval('('+req.responseText+')');
			 	 		for(i in r){
			 	 			if(d.getElementById('e'+i)){
				 	 			if (r[i].estado!=='')d.getElementById('e'+i).className=r[i].estado;
				 	 			else d.getElementById('e'+i).className=d.getElementById('e'+i).parentNode.parentNode.className;
				 	 			d.getElementById('e'+i).innerHTML=r[i].msg;
				 	 		}
				 	 		if(d.getElementById('pr'+i))d.getElementById('pr'+i).innerHTML=r[i].precio;
				 	 		if(d.getElementById('pu'+i))d.getElementById('pu'+i).innerHTML=r[i].pujas;
				 	 		if(d.getElementById('m'+i))d.getElementById('m'+i).innerHTML=r[i].max;
				 	 		if(d.getElementById('t'+i))d.getElementById('t'+i).innerHTML=r[i].tiempoQueda;
				 	 		if(r[i].cerrada==='si') {
				 	 			if(d.getElementById('f'+i))d.getElementById('f'+i).innerHTML='';
				 	 			if(d.getElementById('lp'+i))d.getElementById('lp'+i).innerHTML='';
				 	 			if(d.getElementById('e'+i))d.getElementById('e'+i).innerHTML='';
				 	 		}
				 	 		else{
				 	 			if(r[i].pujaMin)d.pujaForm['mpuja['+i+']'].value=r[i].pujaMin;
				 	 			if(r[i].ampliacionTexto&&d.getElementById('t'+i))d.getElementById('t'+i).innerHTML+='<br><span id="fase'+i+'" class="amp'+r[i].ampliacion+'" title="'+r[i].ampliacionTexto+' ampliaci&oacute;n">'+r[i].ampliacion+' amp.</span> <a class="masInfo" onclick="abrir(\'/info.php?tipo=ampliacion\', 300, 550, \'si\')">[?]</a>';
				 	 		}
			 	 		}
		 	 		}
		 	 		actualizarSaldo();
		 	 	}
			};
			req.open('GET','/operaciones.php?accion=actualizarPuja&'+pV);
		  req.send(null);
		}
	}
}

function actualizarPujas(boton) {
	var _tabla = document.getElementById('tablaPujas');
	var _tr = _tabla.getElementsByTagName('tr');
	var i = 0;
	var max = _tr.length;
	var _id = '';
	for (; i < max; i ++) {
		if (_tr[i].id != 'undefined' && _tr[i].id != '') {
			_id = _tr[i].id.substr(1);
			if (document.pujaForm['mpuja['+_id+']'] && document.pujaForm['mpuja['+_id+']'].disabled != true) {
				actualizarPujaIndividual(_id);
			}
		}
	}
}

function copy(inElement) {
	if (inElement.createTextRange) {
		var range = inElement.createTextRange();
		if (range && BodyLoaded == 1) range.execCommand('Copy');
	}
	else {
		var flashcopier = 'flashcopier';
		if (!document.getElementById(flashcopier)) {
			var divholder = document.createElement('div');
			divholder.id = flashcopier;
			document.body.appendChild(divholder);
		}
		document.getElementById(flashcopier).innerHTML = '';
		var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(inElement.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		document.getElementById(flashcopier).innerHTML = divinfo;
	}
}

function CopyToClipboard(campo) {
	if (campo == 'refsim') var _campo = document.refForm.refsim;
	else var _campo = document.refForm.refsim;
  _campo.focus();
  _campo.select();
  copy(_campo);
}

//function cambiarImagen(elemento) {
//	var _img = document.getElementById('img' + elemento);
//	_img.src = (_img.src === 'http://www.backorders.es/images/mas.gif') ? 'http://www.backorders.es/images/menos.gif' : 'http://www.backorders.es/images/mas.gif';
//}

function mostrarStatsReferer(campo, cual) {
	var _myId = campo.id;
	campo.title = (campo.title === 'Mostrar Detalles') ? 'Ocultar Detalles' : 'Mostrar Detalles';
	if (_myId) {
		cambiarImagen(campo, cual);
	}
}

function procesarDatos(formulario, boton) {
	boton.value = 'Procesando datos...';
	if (formulario !== '') document.forms[formulario].submit();
	boton.disabled = true;
}

function procesarDatosMulti(formulario,boton,longitud){
	var f=d.forms[formulario];
	for(var i=1;i<=longitud;i++) {
		procesarDatos('',f[boton+i]);
	}
	f.submit();
}

function busquedaGuardada(campo) {
	if (campo.value !== '') window.location = 'busqueda.php?idbusqueda=' + campo.value;
}

function pagarPaypal(formulario, boton) {
	var f = document.forms[formulario];
	var i = 0;
	var max = 1;
	for (; i <= max; i++) {
		procesarDatos('', f.eval(boton+i));
	}
	f.submit();
}

function enDis(formulario, campo, valor, cual) {
	var f=document.forms[formulario];
	var c=f[campo+'['+valor+']'];
	c.disabled = (cual.checked === true) ? false : true;
}

function cambiarImagen(campo, cual) {
//	try {
		flip(cual);
		imagen = campo.getElementsByTagName("img")[0];
		imagen.src = (imagen.src === 'http://www.backorders.es/images/flecha.gif') ? 'http://www.backorders.es/images/flecha2.gif' : 'http://www.backorders.es/images/flecha.gif';
		imagen.alt = (imagen.src === 'http://www.backorders.es/images/flecha.gif') ? 'v' : '&gt;';
//	}
//	catch (e) {
//		alert('Se ha producido un error. Intentelo más tarde');
//	}
}

function cambiarDescargaListado(tipo) {
	var d = document;
	var di = d.getElementById('descargaListado');
	di.href = 'descargar.php?tipo=' + tipo;
	di.title = 'Formato ' + tipo.toUpperCase();
}

function adecuarTamano(ori,des){
	des.style.width=ori.offsetWidth+'px';
	des.style.height=ori.offsetHeight+'px';
}

function is_array(input){
	return (input.constructor.toString().indexOf("Array") == -1) ? false : true;
//	return typeof(input)=='object'&&(input instanceof Array);
}


function mostrarDatosGestionN(_cargados,formulario,tipo,accion){
	var f=d.forms['F'+formulario];
	var i=0;
	var max=f.length;
	var reqS='';
//	var divN=d.getElementById(formulario);
	for(;i< max;i++){
		if(f[i].name)reqS+=f[i].name+'='+f[i].value+'&';
	}
	var car='';
	for(i in _cargados){
		for (jj in _cargados[i]) {
			car+='car['+i+']['+jj+']=1&';
		}
	}
	if(d.getElementById(formulario)){
		var divH=d.getElementById(formulario).offsetHeight;
		var divW=d.getElementById(formulario).offsetWidth;
		var divL=d.getElementById(formulario).offsetLeft;
		var divT=d.getElementById(formulario).offsetTop;
		var imgT=divH/2 - 24;
	}
	if(!d.getElementById('cargador'+formulario))d.getElementById(formulario).innerHTML+='<div id="cargador'+formulario+'" style="width:'+divW+'px;height:'+divH+'px;top:'+divT+'px;left:'+divL+'px" class="loadingData"><img src="/images/loading2.gif" alt="Cargando" style="padding-top:'+imgT+'px"><br>Cargandos datos...</div>';
	
	var req=new XMLHttpRequest();
	if(req&&reqS!==''){
	 	req.onreadystatechange=function(){
	 	 	if(req.readyState==4&&(req.status==200||req.status==304)){
	 	 		try{
	 	 			resp=eval('('+req.responseText+')');
	 	 			if(resp.HTML)d.getElementById(formulario).innerHTML=resp.HTML;
	 	 			_cargados=[];
	 	 			if(resp.cargados){
	 	 				for(i in resp.cargados){
	 	 					for(jj in resp.cargados[i]){
	 	 						_cargados[i][jj]=1;
	 	 					}
	 	 				}
	 	 			}
	 	 		}
	 	 		catch (e) {
	 	 			d.getElementById(formulario).innerHTML=req.responseText;
	 	 		}
	 	 	}
	  };
	  req.open('GET', '/operaciones.php?accion='+accion+'&tipo='+tipo+'&'+reqS+car);
	  req.send(null);
	}
}

function mostrarDatosGestion(formulario) {
	var f = document.forms['F'+formulario];
	var i = 0;
	var max = f.length - 1;
	var reqS = '';
	for (; i < max; i ++) {
		if (f[i].name) reqS += f[i].name + '=' + f[i].value + '&';
	}
	var divH = document.getElementById(formulario).offsetHeight;
	
	document.getElementById(formulario).innerHTML = '<div style="height: '+ divH +'px;text-align:center;border: 1px solid #FFCF00;padding-top: 20px"><img src="/images/loadingAnimation.gif" alt="Cargando"><br>Cargando datos...</div>'
	
	var req = new XMLHttpRequest();
	if (req && reqS != '') {
	 	req.onreadystatechange = function() {
	 	 	if (req.readyState == 4 && (req.status == 200 || req.status == 304)) {
	 	 		document.getElementById(formulario).innerHTML = req.responseText;
	 	 	}
	  };
	  req.open('GET', '/operaciones.php?accion=subastas&tipo='+formulario+'&'+reqS);
	  req.send(null);
	}
//	alert(req);
}

function cambiarDatosGestionN(_cargados,formulario,m,f,tipo,accion){
	var fo=d.forms['F'+formulario];
	fo['m'].value=m;
	fo['f'].value=f;
	mostrarDatosGestionN(_cargados,formulario,tipo,accion);
}

function cambiarDatosGestion(formulario,m,f) {
	var fo = document.forms['F'+formulario];
	fo['m'].value = m;
	fo['f'].value = f;
	mostrarDatosGestion(formulario);
}

function activarCapturaDominio(campo,rid) {
	var f=document.forms['listaPorMarcarF'];
	f['dom['+rid+']'].disabled=campo.checked?false:true;
	f['age['+rid+']'].disabled=campo.checked?false:true;
}

function generarPassword() {
	var d = document;
	var f = d.forms['cambiarPass'];
	var req = new XMLHttpRequest();
	if (req) {
		req.onreadystatechange = function() {
	 	 	if (req.readyState == 4 && (req.status == 200 || req.status == 304)) {
	 	 		f.passwordN.value = f.passwordNR.value = req.responseText;
	 	 	}
	  };
	  req.open('GET', '/operaciones.php?accion=crearPassword');
	  req.send(null);
	}
}

function activarFormMulti(formulario,campo,id,elemento) {
	var f=d.forms[formulario];
	f[campo+'['+id+']'].disabled=elemento.checked?false:true
}

function cambiarClase(campo, nuevaClase) {
	campo.className=nuevaClase;
}

function saltarALaPagina(formulario,pag){
	var f=d.forms['F'+formulario];
	f['page'].value=pag;
}

function cambiarValoresRPP(formulario,valor){
	var f=d.forms['F'+formulario];
	f['rpp'].value=valor;
	f['page'].value=1;
}

function crearElementoFormulario(formulario,tipo,parametros){
	var f=d.forms[formulario];
	var el=d.createElement(tipo);
	for(i in parametros){
		el.setAttribute(i,parametros[i]);
	}
	f.appendChild(el);
//	alert(f['Fperiodo'].value);
}

function procesarFiltro(_cargados,formulario,tipo,accion) {
	var f=d.forms['filtroAvanzado'+tipo];
	var fd=d.forms['F'+formulario];
	var param = new Array();
	if(f['periodo']&&f['periodo'].value!==''&&!fd['periodo']){
		param['name']='periodo';
		param['value']=f['periodo'].value;
		param['type']='hidden';
		crearElementoFormulario('F'+formulario,'input',param);
	}
	else if(f['periodo']&&fd['periodo']) fd['periodo'].value=f['periodo'].value;
	
	if(f['agenteEstado']&&f['agenteEstado'].value!==''&&!fd['agenteEstado']){
		param['name']='agenteEstado';
		param['value']=f['agenteEstado'].value;
		param['type']='hidden';
		crearElementoFormulario('F'+formulario,'input',param);
	}
	else if(f['agenteEstado']&&fd['agenteEstado']) fd['agenteEstado'].value=f['agenteEstado'].value;
	
	if(f['pagado']&&f['pagado'].value!==''&&!fd['pagado']){
		param['name']='pagado';
		param['value']=f['pagado'].value;
		param['type']='hidden';
		crearElementoFormulario('F'+formulario,'input',param);
	}
	else if(fd['pagado']&&f['pagado'])fd['pagado'].value=f['pagado'].value;
	
	if(f['estado']&&f['estado'].value!==''&&!fd['estado']) {
		param['name']='estado';
		param['value']=f['estado'].value;
		param['type']='hidden';
		crearElementoFormulario('F'+formulario,'input',param);
	}
	else if(fd['estado']&&f['estado'])fd['estado'].value=f['estado'].value;
	
	if(f['mes']&&f['mes'].value!==''&&!fd['mes']) {
		param['name']='mes';
		param['value']=f['mes'].value;
		param['type']='hidden';
		crearElementoFormulario('F'+formulario,'input',param);
	}
	else if(fd['mes']&&f['mes'])fd['mes'].value=f['mes'].value;
	
	if(f['anio']&&f['anio'].value!==''&&!fd['anio']) {
		param['name']='anio';
		param['value']=f['anio'].value;
		param['type']='hidden';
		crearElementoFormulario('F'+formulario,'input',param);
	}
	else if(fd['anio']&&f['anio'])fd['anio'].value=f['anio'].value;
	
	mostrarDatosGestionN(_cargados,formulario,tipo,accion);
}

function procesarVariosForms(destino,origen){
	if(d.forms[destino] && d.forms[origen]){
		var de=d.forms[destino];
		var or=d.forms[origen];
		var max=or.length;
		var i=0;
		for(;i<max;i++){
			if (or[i].name==='p[]'&&or[i].checked===true){
				inp=d.createElement('input');
				inp.type='hidden';
				inp.name='p[]';
				inp.value=or[i].value;
				de.appendChild(inp);
			}
		}
		de.submit();
	} else if (d.forms[destino]) {
		var de=d.forms[destino];
		de.submit();
	} else if (d.forms[origen]) {
		var or=d.forms[origen];
		or.submit();
	}
}

if(window.alert){
	window._alert=window.alert;
}
window.alert=function(txt,button){
	button=button?button:'true';
	if($("#malert").length==0){
		$("body").append("<div id='malert' class='malert'></div>");
	}
	
	var msg = $("#malert");
	var height=$(window).height();
	var width=$(document).width();
	msg.css({
		'left':width/2 - (msg.width() / 2),
    'top':height/2 - (msg.height() / 2),
    'z-index' : 15, 
	});
	
	if(button !== 'false'){
		txt+='<p>&nbsp;</p><p class="c"><input type="button" class="submitBot3" value="Cerrar ventana" onclick="$(\'#malert\').hide();" /></p>';
	}
	$("#malert").html(txt);
	$("#malert").show();
};