function inicializaPagina(){
	var file_whois;
	if(navigator.appName == "Microsoft Internet Explorer"){file_whois="whois.php";}else{file_whois="whois_firefox.php";}
	makeForms();
	if($("orig_sugerencias")){
		if($("orig_sugerencias").value!=""){
			$$(".do_whois").each(function(el){
				if($("dom_" + el.id, el).value != ""){
					var strDomain = $("dom_" + el.id, el).value;
					var ajx = new Ajax('ajax/'+file_whois, {
								method: "post",
								postBody: "sugerencias=" + strDomain,
								//onComplete: function() { autoCheck(el.id) },
								update: el.id
					}).request();
				}
			});
		}
	}else if($("orig_masivo")&&$("orig_dom")){
		if($("orig_masivo").value!=""){
			$$(".do_whois").each(function(el){
				if($("tld_" + el.id, el).value != ""){
					var strTld = $("tld_" + el.id, el).value;
					var strDomain = $("dom_" + el.id, el).value;
					var strDomainNoExt = $("domNoExt_" + el.id, el).value;
					var strPrice = $("precio_" + el.id, el).value;
					var ajx = new Ajax('ajax/'+file_whois, {
								method: "post",
								postBody: "masivo=" + strDomain + "&dom_domNoExt=" + strDomainNoExt +  "&dom_tld=" + strTld + "&dom_price=" + strPrice,
								onComplete: function() { autoCheck(el.id) },
								update: el.id
					}).request();
				}
			});
		}else{
			var elStrDom = $("orig_dom");
			if (elStrDom) {
				var strDom = elStrDom.value;
				var strSelTld = $("orig_tld").value;
				$$(".do_whois").each(function(el){
					if($E("#tld_" + el.id, el).value != ""){
						var strTld = $E("#tld_" + el.id, el).value;
						var strPrice = $E("#precio_" + el.id, el).value;
						var ajx = new Ajax('ajax/'+file_whois, {
									method: "post",
									postBody: "q_dom=" + strDom + "&dom_tld=" + strTld + "&orig_tld=" + strSelTld + "&dom_price=" + strPrice,
									//onComplete: function() { autoCheck(el.id) },
									update: el.id
						}).request();
					}
				});
			}
		}
	}
	var btcont = $E(".btcontrata");
	if (btcont) {
		btcont.addEvent("click", contratar);
	}
	estaChecked = false;
	ordenTld=["com", "es", "co", "me", "net", "org", "info", "biz", "mobi", "eu", "com_es", "org_es", "nom_es", "gob_es", "edu_es", "cat", "tel", "cc", "ws", "tv", "xxx"];
}
//-----------------------------------------------------------------------------
Window.onDomReady( inicializaPagina );
window.addEvent("domready", function() {						 
	//$('contenido').setStyles('background-color:#fad2d3;');
	//$$('.do_whois').set('id', 'whois_'+$('dom_tld').value);
	if($('q_dom')){
		$('q_dom').addEvent('click', function(e) {
			if($('q_dom').value=="dominio")$('q_dom').value="";
		});
		$('q_dom').addEvent('blur', function(e) {
			if($('q_dom').value=="")$('q_dom').value="dominio";
		});
	}
	if($('q_dom_ext')){
		$('q_dom_ext').addEvent('click', function(e) {
			if($('q_dom_ext').value=="dominio")$('q_dom_ext').value="";
		});
		$('q_dom_ext').addEvent('blur', function(e) {
			if($('q_dom_ext').value!=""){
				$('q_dom').value=$('q_dom_ext').value;
			}else{
				$('q_dom_ext').value="dominio";
			}
		});
		$$('.todas').addEvent('click', function(e) {
			if($$('.todas').getProperty('checked')=="true"){
				$$('.check').each(function(el){ el.setProperty('checked','') });
			}else{
				$$('.check')[0].setProperty('checked','checked');
			}
		});
		$$('.check').addEvent('click', function(e) {
			var pulsados = new Array();
			$$('.check').each(function(el){
				if(el.getProperty('checked')){// si alguna extension se activa, vaciamos checkbox "todas"
					$$('.todas').setProperty('checked','');
				}
			});	
			$$('.check').each(function(el){// comprobamos q no hay ninguna extension marcada y activamos checkbox "todas"
				if(el.getProperty('checked')) pulsados.push(1);
			});
			if(pulsados.length==0)$$('.todas').setProperty('checked','checked');
			var pulsados = new Array();
		});
	}
	if($('q_dom_cab')){
		$('q_dom_cab').addEvent('click', function(e) {
			if($('q_dom').value=="dominio")$('q_dom_cab').value="";
		});
		$('q_dom_cab').addEvent('blur', function(e) {
			if($('q_dom_cab').value!=""){
				$('q_dom').value=$('q_dom_cab').value;
			}else{
				$('q_dom_cab').value="dominio";
			}
		});
	}
});
//-----------------------------------------------------------------------------
function autoCheck(__id){
	// Valores de utilidad. Indican el número de dominios Totales, Pendientes
	// y que están Libres.
	var numTotal   = $ES("tr.do_whois").length;
	var numPend    = $ES("td.DispVerif").length;
	var numLibres  = $ES("td.Disponible").length;

	// libre == indica si el dominio que acabamos de recibir el resultado está
	// disponible para registrar. Luego habrá que comprobar si es el elegido.
	var libre = $E("td.Disponible", __id);
	var elem  = $E("input", __id);
	var dats  = elem.value.split("|");

	if (libre && dats[0] == $("orig_tld").value) {
		// Está libre nuestro dominio !!
		elem.checked = true;
		estaChecked = true;
		$$('div#'+__id).setStyles('background-color:#fad2d3;');
	}

//	console.log("Total: " + numTotal + " - Pendientes: " + numPend);

	var strDom     = $("orig_dom").value;
	var strOrigTld = $("orig_tld").value;


	// Puede que sea el último elemento y que no tengamos ninguno elegido, así
	// que tenemos que recorrer los dominios por orden para activar el input
	// del más "cercano".
	if ((numPend == 0) && !estaChecked) {
		//console.log("Recorremos los dominios...");

		ordenTld.each(function(tld){
			if (estaChecked) return;

			var el = $E("#whois_" + tld + " input");
			if (el && !el.disabled) {
				// Hemos encontrado uno en secuencia que está disponible!!
				el.checked = true;
				estaChecked = true;
			}
		});
	}
}
//-----------------------------------------------------------------------------
function getUpdate(typ,pr1,pr2){
	if (typ == "state") {
		// Estado:3, finaliza el video, tenemos que sacarlo del documento.
		if (pr1 == 3) {
			Lightbox.close();
		}
	}
}
//-----------------------------------------------------------------------------
function submitForm(e, formulario){
	var event = new Event(e);
	var extension
	if(formulario=="form_ext"){
		var k=0;
		$$('.check').each(function(el){
			if(el.getProperty('checked') && k==0){// si alguna extension se activa, cogemos la primera
				extension = el.getProperty('value');
				k++;
			}
		});
		if($$('.todas').getProperty('checked')=="true"){
			extension = "com";
		}
	}else{
		extension = $("dom_tld").value;	
	}
	var domain = $("q_dom");
	var l = domain.value.trim().length;
	domain.value = domain.value.trim().toLowerCase();
	var strDom = domain.value.trim();
	event.preventDefault();
	if (!l) {
		alert("Por favor, introduce un dominio en el campo de búsqueda.");
		domain.focus();
		return false;
	}
	switch(extension) {
		case "org":
		case "biz":
		case "info":
		case "mobi":
		case "tel":
		case "me":
		case "cat":
			if (!strDom.test(/^[a-z0-9][a-z0-9-]*[a-z0-9]$/)) {
				alert("El dominio es incorrecto, usa letras de la A a la Z, números y guiones.");
				domain.focus();
				return false;
			}
			break;
		case "com":
		case "net":
		case "eu":
		case "co":
		case "cc":
		case "ws":
		case "tv":
		case "es":
		case "xxx":
		case "com.es":
		case "org.es":
		case "nom.es":
		case "edu.es":
		case "gob.es":
			if (!strDom.test(/^[áéíóúüñça-z0-9][áéíóúüñça-z0-9-·]*[áéíóúüñça-z0-9]$/)) {
				alert("El dominio es incorrecto, usa letras de la A a la Z, números y guiones...");
				domain.focus();
				return false;
			}
			
			if (strDom.test(/·/)){
				var cadDom = strDom;
				while(cadDom.test(/·/)){
					var tam = cadDom.length;
					var pos = cadDom.indexOf("·");
					var antes_punto = cadDom.substr(pos-1, 1);
					var despues_punto = cadDom.substr(pos+1, 1);
					if (antes_punto != "l" || despues_punto != "l"){
						alert("El dominio es incorrecto.");
						domain.focus();
						return false;
					}
					cadDom = cadDom.substr(pos+1, tam-pos-1);
				}
			}
			break;
		default:
			return false;
	}
	
	if (strDom.test(/^xn--/)) {
		alert("El dominio es incorrecto, no puede comenzar por la cadena 'xn--'.");
		domain.focus();
		return false;
	}
	if(formulario!="lista_dominios")event.target.submit();
}

//-----------------------------------------------------------------------------
function contratar()
{
	var numTotal   = $ES("tr.do_whois").length;
	var numPend    = $ES("td.DispVerif").length;
	var numLibres  = $ES("td.Disponible").length;
	var strDom     = $("orig_dom").value;
	var strOrigTld = $("orig_tld").value;
	strDom = Url.encode(strDom);
	
	if (numLibres == 0) {
		alert("No hay dominios libres, por favor, busque otro nombre que esté disponible.");
		return;
	}

	var free = $ES("td.Disponible input");
	var url_contrata = false;

	free.each(function(el){
		if (el.checked) {
			url_contrata = true;
		}
	});
	
	if (url_contrata) {
		document.forms['lista_dominios'].submit();
	} else {
		alert("Debes seleccionar un dominio a registrar...");
		return false;
	}
}



//-----------------------------------------------------------------------------
function makeForms(){
	var formulario="";
	$$("form").each(function(el) {
		//el.addEvent("submit", submitForm);
		$$("form").addEvent('submit', function(e) { 
			formulario=$$(this).getProperty("name"); 
		});
		el.addEvent("submit", function (e) { submitForm(e,formulario); } );
	});
	$ES("button").each(function(butt){
			butt.addEvents({
				mouseover:	function() { this.addClass("hover"); },
				mouseout:	function() { this.removeClass("hover"); }
			});
		});
}


//------------------------------------------------------------------------------
/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },

    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
//----------------
function openwindow(url) {
    window.open(url, "_blank", "height=450, width=720,scrollbars=yes,status=no,location=no,menubar=no,resize=yes");
}
