/*
 *Version 1.0.1
IDENTIFICAR EL NAVEGADOR QUE USA EL CLIENTE
*/
navegador = 1;
if( navigator.userAgent.indexOf("MSIE 6") >= 0 ) {
	navegador = 6;
}
if( navigator.userAgent.indexOf("MSIE 7") >= 0 ) {
	navegador = 7;
}

/*****************************************************************************************
OBJETO AJAX
*****************************************************************************************/
function XHConn() {
	var xmlhttp, bComplete = false, aaa;
	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("Content-Type","application/x-www-form-urlencoded");
				xmlhttp.send(sVars);
			}
			xmlhttp.onreadystatechange = function() {
				if (xmlhttp.readyState == 4 && !bComplete) {
					bComplete = true;
					fnDone(xmlhttp);
				}
			};
			xmlhttp.send(sVars);
		}
		catch(z) { return false; }
		return true;
	};
	return this;
}

/*****************************************************************************************
LLAMADA AL OBJETO AJAX
*****************************************************************************************/
function ajax1(archivo,destino,variables,respuesta) {
	if ( !respuesta ) {
		respuesta = 'escribir';
	}
	
	if ( destino != '' ) {
		mensaje_espera = '<img src="load_black.gif" alt="Espere..." />';
		document.getElementById(destino).innerHTML = mensaje_espera;
	}
	var myConn = new XHConn();
	if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
	
	var peticion = function (oXML) {
		regreso = oXML.responseText;
		
		if ( respuesta == 'escribir' ) {
			document.getElementById(destino).innerHTML = regreso;
		}
		else {
			// buscar si devielve un error
			errores = new Array();
			errores = regreso.split('|');
			// si el primer elemento es #Error#, ocurrio un error en php
			if ( errores[0] == '#Error#' ) {
				escribir_mensaje('div_mensajes', errores[1], 'rojo')
			}
			else {
				switch (respuesta) {
					case 'datos_cliente': desplegar_datos_cliente(regreso); break;					
					case 'datos_factura': desplegar_datos_factura(regreso); break;
					case 'eliminar_orden': eliminar_orden(1,errores[1],0); break;
				}
			}
		}
	};
	
	myConn.connect( archivo, "POST", variables, peticion );
	
}

/************************************************************************************
NOMBRE:
	ajax_obtener_planes
ENDTRADAS:
	plan_id -> id del plan a buscar
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	Imprime las opciones necesarias para realizar la contratacion de un plan (exepto dominio y hosting)
************************************************************************************/
function ajax_obtener_planes(plan_id) {
	// id del div donde se desplegara la informacion
	destino = 'datos_contratacion';
	//  indicador de espera
	document.getElementById(destino).innerHTML = '<img src="load_black.gif" alt="Cargando informacion" />';
	
	var myConn = new XHConn();
	if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
	
	var peticion = function (oXML) {
		regreso = oXML.responseText;
		document.getElementById(destino).innerHTML = regreso;
	};
	
	variables = 'accion=obtener_planes&plan_id='+plan_id;
	
	myConn.connect( 'includes/contratar/ajax.php', "POST", variables, peticion );
}

/************************************************************************************
NOMBRE:
	cambiar_categorias
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	Llama al ajax para desplegar las opciones de contratacion segun el producto seleccionado
************************************************************************************/
function cambiar_categorias() {
	if ( document.getElementById('cmbCategorias') ) {
		categoria = document.getElementById('cmbCategorias').value;
		// ocultar todos los divs, no se sabe cual es el que se debera mostrar
		document.getElementById('catego_Seguridad').style.display = 'none';
		document.getElementById('catego_Otros').style.display = 'none';
		document.getElementById('catego_Propiedad_Intelectual').style.display = 'none';
		document.getElementById('catego_Upgrade').style.display = 'none';
		document.getElementById('catego_SEO').style.display = 'none';
		// desplegar solo el seleccionado
		document.getElementById('catego_' + categoria).style.display = '';
		// obtener el id del plan seleccionado
		plan_id = document.getElementById('cmbPlanes_'+categoria).value;
		ajax_obtener_planes(plan_id);
	}
}

/************************************************************************************
NOMBRE:
	cambiar_hosting
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	cambia los planes de hosting dependiendo del tipo que se ha solicitado
************************************************************************************/
function cambiar_hosting() {
	if ( document.getElementById('cmbTipos') ) {
		categoria = document.getElementById('cmbTipos').value;
		// ocultar todos los divs, no se sabe cual es el que se debera mostrar
		document.getElementById('catego_Linux').style.display = 'none';
		document.getElementById('catego_Windows').style.display = 'none';
		document.getElementById('catego_Reseller').style.display = 'none';
		// desplegar solo el seleccionado
		document.getElementById('catego_' + categoria).style.display = '';
		
		cambiar_precios_host('cmbPlan_'+categoria);
	}
}



/************************************************************************************
NOMBRE:
	cambiar_precio
ENDTRADAS:
	pos -> ID de los elementos que intervienen en la actualziacion de los precios por periodicidad
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	Actualiza los precios a cobrar en la pagina, e invoca al ajax para actualizar el carrito de comrpa
************************************************************************************/
function cambiar_precio( pos_i,pos_j ) {
	// deben existir los elementos web que intervienen en el cambio
	if ( document.getElementById('cmbPeriodicidad_'+pos_i+'_'+pos_j) && document.getElementById('precio_'+pos_i+'_'+pos_j) ) {
		// obtener la posicion del elemento seleccionado
		seleccionado = document.getElementById('cmbPeriodicidad_'+pos_i+'_'+pos_j).selectedIndex;
		// buscar en el arreglo el valor del elemento seleccionado
		nuevo_precio = arreglo_carrito[pos_i][pos_j][seleccionado+2];
		// obtener el precio actual
		precio_actual = document.getElementById('hidSub_'+pos_i+'_'+pos_j).value;
		// al total de compra restar el precio actual, ya que cambiara
		total_pagar -= precio_actual;
		// sumar el nuevo precio al precio actual
		total_pagar += nuevo_precio;
		// imprimir los cambios
		document.getElementById('precio_'+pos_i+'_'+pos_j).innerHTML = '$ '+number_format(nuevo_precio,2,'.',',');
		document.getElementById('div_total_pagar').innerHTML =  number_format(total_pagar,2,'.',',');
		// actualizar los campos de formulario
		document.getElementById('hidSub_'+pos_i+'_'+pos_j).value = nuevo_precio;
		document.getElementById('hidTotalPagar').value = total_pagar;
	}
}

/************************************************************************************
NOMBRE:
	cambiar_precios_dom
ENDTRADAS:
	id_combo -> ID del combo donde se obtendran los precios
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	Actualiza los precios a cobrar en la pagina
************************************************************************************/
function cambiar_precios_dom(id_combo) {
	if ( document.getElementById(id_combo) ) {
		// obtener la id del dominio pues es la posicion del arreglo que contiene los precios
		id_dominio = document.getElementById(id_combo).value;
		// leer los precios desde el arreglo que contiene  todos los precios
		precio_registro_con = arreglo_precios_dominios[id_dominio]["precio_con"]; // precio nuevo con host
		precio_registro_sin = arreglo_precios_dominios[id_dominio]["precio_sin"]; // precio nuevo sin host
		precio_transf_con = arreglo_precios_dominios[id_dominio]["precio_t_con"]; // precio transf con host
		precio_transf_sin = arreglo_precios_dominios[id_dominio]["precio_t_sin"]; // precio transf sin host
		
		// imprimir los precios seleccionados
		document.getElementById('precio_r_dh').innerHTML = number_format( precio_registro_con, 2, '.', ' ' );
		document.getElementById('precio_t_dh').innerHTML = number_format( precio_transf_con, 2, '.', ' ' );
		document.getElementById('precio_r_d').innerHTML = number_format( precio_registro_sin, 2, '.', ' ' );
		document.getElementById('precio_t_d').innerHTML = number_format( precio_transf_sin, 2, '.', ' ' );
		
		// actualizar la variable con el id del dominio seleccionado
		dominio_seleccionado = id_dominio;
		
		// actualizar los precios de los productos seleccionados
		actualizar_totales_dh();
	}
}

/************************************************************************************
NOMBRE:
	cambiar_precios_host
ENDTRADAS:
	id_combo -> ID del combo donde se obtendran los precios
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	Actualiza los precios a cobrar en la pagina
************************************************************************************/
function cambiar_precios_host(id_combo) {
	var c = 0;
	
	if ( document.getElementById(id_combo) ) {
		// obtener la categoria seleccionada
		datos_host = document.getElementById(id_combo).value;
		
		for ( c=0; c<arreglo_precios_hosting.length; c++ ) {
			comparar = arreglo_precios_hosting[c]["plan_id"]+'|'+arreglo_precios_hosting[c]["plan_costo"];
			if ( comparar == datos_host ) {
				total_hosting = arreglo_precios_hosting[c]["plan_costo"];
				plan_id = arreglo_precios_hosting[c]["plan_id"];
			}
		}
		actualizar_totales_dh();
	}
	else {
		categoria = document.getElementById('cmbTipos').value;
		datos_host = document.getElementById('cmbPlan_'+categoria).value;
		arreglo_datos_host = datos_host.split('|');
		total_hosting = arreglo_datos_host[1];
		plan_id = arreglo_datos_host[0];
		
		// sumar para crear los totales
		total_seleccionado = total_dominio + total_hosting;
		
		// imprimir los totales
		document.getElementById('total_dominio').innerHTML = number_format(total_dominio,2,'.',' ');
		document.getElementById('total_hosting').innerHTML = number_format(total_hosting,2,'.',' ');
	}
}

/************************************************************************************
NOMBRE:
	actualizar_totales_dh
ENDTRADAS:
	id_combo -> ID del combo donde se obtendran los precios
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	Actualiza los totales segun los productos seleccionados en la forma de contratacion de dominio y hosting
************************************************************************************/
function actualizar_totales_dh() {
	var c;
	// obtener el tipo de contratacion (dominio, hostng, registrar, apuntar, etc)
	total_radios = document.frmContratar.radTipo.length;
	for ( c=0; c<total_radios; c++ ) {
		if ( document.frmContratar.radTipo[c].checked === true ) {
			tipo_contratacion = document.frmContratar.radTipo[c].value;
			break;
		}
	}
	
	// mostrar div de host, no se sabe la opcion
	document.getElementById('planes_hosting').style.display = '';
	
	// en base al tipo, obtener las cantidades necesarias
	switch ( tipo_contratacion ) {
		// registrar contratar dominio hosting
		case 'r-dh':
			total_dominio = arreglo_precios_dominios[dominio_seleccionado]["precio_con"];
			// verifricar la disponibilidad del dominio dependiendo del cambio
			if ( dom_op != 'r' ) {
				verificar_dominio_dh();
				dom_op = 'r';
			}
			// actualizar precios en base al evento
			cambiar_precios_host();
			break;
		// transferir dominio hosting
		case 't-dh':
			total_dominio = arreglo_precios_dominios[dominio_seleccionado]["precio_t_con"];
			
			// verifricar la disponibilidad del dominio dependiendo del cambio
			if ( dom_op != 't' && dom_op != 'a' ) {
				verificar_dominio_dh();
				dom_op = 't';
			}
			// actualizar precios en base al evento
			cambiar_precios_host();
			break;
		// apuntar dominio, solo hosting
		case 'a-h':
			total_dominio = 0;
			// verifricar la disponibilidad del dominio dependiendo del cambio
			if ( dom_op != 't' && dom_op != 'a' ) {
				verificar_dominio_dh();
				dom_op = 'a';
			}
			// actualizar precios en base al evento
			cambiar_precios_host();
			break;
		// registrar solo dominio
		case 'r-d':
			total_dominio = arreglo_precios_dominios[dominio_seleccionado]["precio_sin"];
			total_hosting = 0; // no hay hosting por lo que el precio es 0
			plan_id = 0; // no hay hosting
			// ocultar el div de hosting
			document.getElementById('planes_hosting').style.display = 'none';
			
			// verifricar la disponibilidad del dominio dependiendo del cambio
			if ( dom_op != 'r' ) {
				verificar_dominio_dh();
				dom_op = 'r';
			}
			break;
		// transferir solo dominio
		case 't-d':
			total_dominio = arreglo_precios_dominios[dominio_seleccionado]["precio_t_sin"];
			total_hosting = 0; // no hay hosting por lo que el precio es 0
			plan_id = 0; // no hay hosting
			// ocultar el div de hosting
			document.getElementById('planes_hosting').style.display = 'none';
			
			// verifricar la disponibilidad del dominio dependiendo del cambio
			if ( dom_op != 't' && dom_op != 'a' ) {
				verificar_dominio_dh();
				dom_op = 't';
			}
			
			break;
	}
	// sumar para crear los totales
	total_seleccionado = total_dominio + total_hosting;
	
	// imprimir los totales
	document.getElementById('total_dominio').innerHTML = number_format(total_dominio,2,'.',' ');
	document.getElementById('total_hosting').innerHTML = number_format(total_hosting,2,'.',' ');
}

/************************************************************************************
NOMBRE:
	contratar_hosting
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	crea la llave con ajax para evitar inyeccion de codigo
************************************************************************************/
function contratar_hosting(destino) {
	var datos = '';
	
	// si el dominio se ha validado correctamente, enviar los datos
	if ( dom_ok ) {
		// valores necesarios para la creacion de la llave
		dominio = document.getElementById('txtDominio').value;
		extension = document.getElementById('cmbExtensiones').value;
		plan = plan_id;
		// obtener el tipo de contratacion
		total_radios = document.frmContratar.radTipo.length;
		for ( c=0; c<total_radios; c++ ) {
			if ( document.frmContratar.radTipo[c].checked === true ) {
				tipo_contratacion = document.frmContratar.radTipo[c].value;
				break;
			}
		}
		// crear la cadena con los datos que se van a enviar a la creacion de la llave
		datos = "dominio="+dominio+","+"extension="+extension+","+"plan="+plan_id+","+"tipo="+tipo_contratacion+","+"prov="+window.location;
		// crear las variables que se enviaran
		variables = 'accion=crear_llave&datos='+escape(datos)+'&param1=DOMXHOST';
		
		// conectar a ajax para enviar la llave
		var myConn = new XHConn();
		if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
		document.getElementById('link_comprar').innerHTML = '<img src="load_black.gif" />';
		var peticion = function (oXML) {
			regreso = oXML.responseText;
			//escribir_mensaje('div_mensajes', regreso, 'amarillo')
			//document.getElementById('link_comprar').innerHTML = regreso;
			document.frmContratar.datos.value = regreso;
			//document.getElementById('datos').value = regreso;
			document.frmContratar.action = 'Contratacion_Paso_1.php';			
			document.frmContratar.submit();
		}
		myConn.connect( 'includes/contratar/ajax.php', "POST", variables, peticion );
		
	}
	// sino, intentar revalidar
	else {
		document.location.href = '#contratacion';
		//escribir_mensaje('div_mensajes', 'Verifica que tu dominio sea el adecuado', 'rojo');
	}
}



/************************************************************************************
NOMBRE:
	continuar_compra
ENDTRADAS:
	accion -> define la siguiente pagina despues del proceso de actualizacion del carrito de compra
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	Obtiene la accion a realizar, crea la llave unica para actualizar el carrito de compra
************************************************************************************/
function continuar_compra(accion) {
	var datos = '';
	
	if ( accion == 1 ) {
		document.getElementById('hidAccion').value = 'agregar_mas';
	}
	if ( accion == 2 ) {
		document.getElementById('hidAccion').value = 'fin_compra';
	}
	if ( accion == 3 ) {
		document.getElementById('hidAccion').value = 'eliminar_elememto';
	}
	
	arreglo_inputs = document.getElementsByTagName('INPUT');
	ereg = /^hidSub_/;
	for ( x=0; x<arreglo_inputs.length; x++ ) {
		if ( ereg.test(arreglo_inputs[x].id) ) {
			datos += arreglo_inputs[x].name + '=' + arreglo_inputs[x].value + ',';
		}
	}
	
	arreglo_inputs = document.getElementsByTagName('SELECT');
	ereg = /^cmbPeriodicidad_/;  
	for ( x=0; x<arreglo_inputs.length; x++ ) {
		if ( ereg.test(arreglo_inputs[x].id) ) {
			datos += arreglo_inputs[x].name + '=' + arreglo_inputs[x].value + ',';
		}
	}
	
	if ( arreglo_inputs.length > 1 ) {
		datos = datos.substr( 0, datos.length-1 );
	}
	
	variables = 'accion=crear_llave&datos='+escape(datos)+'&param1=FINXCOM';
	// si no hay seleccionados para compra
	if ( accion == 1) {
                url_ret = 'Contratacion_Hosting.php'
                document.location.href = url_ret;
	}
	else {
                if ( datos == '') {
			alert ( 'Su orden esta vacia' );
                        return;
		}
		var myConn = new XHConn();
		if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
		document.getElementById('acciones_carrito').innerHTML = '<img src="load_black.gif" />';
		var peticion = function (oXML) {
			regreso = oXML.responseText;
			//alert(regreso);
			document.getElementById('hidDatos').value = regreso;
			//alert(document.getElementById('hidDatos').value);
			document.frmCarrito.submit();
		}
		myConn.connect( 'includes/contratar/ajax.php', "POST", variables, peticion );
	}
}

/************************************************************************************
NOMBRE:
	eliminar_orden
ENDTRADAS:
	session_id -> indentificador de la sesion
	orden -> num de orden a eliminar (nota que no es la orden de adminx sino del carrito de compra)
	posicion -> posicion que toma la orden en el listado final
	----- despues del ajax
	session_id -> debera ser 1 para identiffica que viene de respuesta de ajax
	orden -> cadena con resultado de ajax
	posicion -> nulo
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	Obtiene la accion a realizar, crea la llave unica para actualizar el carrito de compra
************************************************************************************/
function eliminar_orden(session_id,orden,posicion) {
	if ( session_id == 1 ) {
		arreglo = orden.split(',');
		la_posicion = arreglo[0];
		num_productos = parseInt(arreglo[1]);
		el_total = parseFloat(arreglo[2]);
		
		total_pagar = el_total;
		
		// vaciar el contenido del div
		document.getElementById('orden_'+la_posicion).innerHTML = '';
		// eliminar el div
		document.getElementById('orden_'+la_posicion).style.display = 'none';
		
		
		// si no hay productos
		if ( num_productos == 0 ) {
			// poner mensaje de orden vacia
			document.getElementById('orden_'+la_posicion).innerHTML = 'Su orden est&aacute; vacia';
			document.getElementById('orden_'+la_posicion).style.border = '1px solid #DDDDDD';
			document.getElementById('orden_'+la_posicion).style.borderTop = '0px solid #DDDDDD';
			// restaurar el div
			document.getElementById('orden_'+la_posicion).style.display = '';
		}
		
		document.getElementById('div_total_pagar').innerHTML = number_format(total_pagar,2,'.',' ');
	}
	// si no es 1, debera venir de la pagina
	else {
		archivo = '../../includes/contratar/ajax.php';
		variables = 'accion=eliminar_orden&session_id='+escape(session_id)+'&orden='+escape(orden)+'&poss='+escape(posicion);
		ajax1 ( archivo, 'eliminar_'+posicion, variables, 'eliminar_orden' );
	}
}



/************************************************************************************
NOMBRE:
	verificar_dominio
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	llama al whois y regresa un error o acierto dependiendo de la operacion que se desea realizar
************************************************************************************/
function verificar_dominio_dh() {
	// poner la bandera en false. no se sabe aun el resultado de la validacion
	dom_ok = false;
	// obtener el tipo de contratacion
	total_radios = document.frmContratar.radTipo.length;
	for ( c=0; c<total_radios; c++ ) {
		if ( document.frmContratar.radTipo[c].checked === true ) {
			tipo_contratacion = document.frmContratar.radTipo[c].value;
			break;
		}
	}
	
	// validar la sintaxis del dominio	
	var ereg = /^[a-zA-Z0-9]+(\-[a-zA-Z0-9]|[a-zA-Z0-9])*$/;
	
	dominio = document.getElementById('txtDominio').value;
	extension = arreglo_precios_dominios[dominio_seleccionado]["nombre"];
	// si se ha escrito un dominio, continuar con el proceso.  sino, no hagas nada
	if ( dominio.length > 0 ) {
		if ( ereg.test(dominio) ) {
			variables = "accion=whois&dominio="+escape(dominio)+"&extension="+extension;
			// poner el mensaje de espera
			escribir_mensaje('div_mensajes', '<br>Verificando la existencia del dominio <strong>'+dominio+'.'+extension+'</strong>. Por favor espere', 'amarillo')
			
			var myConn = new XHConn();
			if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
			var peticion = function (oXML) {
				regreso = oXML.responseText;
				arreglo_disponibilidad = regreso.split('|');
				
				if ( arreglo_disponibilidad[0] != 'Error' ) {
					switch ( tipo_contratacion ) {
						// estos tipos requieren que el dominio no exista
						case 'r-dh':
						case 'r-d':
							
							if ( arreglo_disponibilidad[1] == 'Disponible' ) {
								escribir_mensaje('div_mensajes', 'El dominio <strong>'+dominio+'.'+extension+'</strong> est&aacute; disponible para ser registrado', 'verde');
								dom_ok = true;
							}
							else {
								escribir_mensaje('div_mensajes', 'El dominio <strong>'+dominio+'.'+extension+'</strong> NO est&aacute; disponible. Indica otro por favor', 'rojo');
							}
							
							break;
						// estos tipos requieren que el dominio SI exista
						case 't-dh':
						case 't-d':
						case 'a-h':
							if ( arreglo_disponibilidad[1] == 'No Disponible' ) {
								escribir_mensaje('div_mensajes', 'Se ha validado la existencia del dominio <strong>'+dominio+'.'+extension+'</strong>', 'verde');
								dom_ok = true;
							}
							else {
								escribir_mensaje('div_mensajes', 'El dominio <strong>'+dominio+'.'+extension+'</strong> no existe.<br />Es necesario indicar un dominio existente para transferir o apuntar', 'rojo');
							}
							break;
					}
				}
				else {
					escribir_mensaje('div_mensajes', arreglo_disponibilidad[1], 'rojo');
				}
			}
			myConn.connect( 'includes/contratar/ajax.php', "POST", variables, peticion );
		}
		else {
			escribir_mensaje('div_mensajes', '<div align="left">El dominio que has escrito es incorrecto:<br /><ul><li>Solo puede contener numeros, letras y guiones medios.</li><li>No puede haber dos giones seguidos.</li><li>No puede empezar o terminar en gui�n.</li></ul></div>', 'rojo');
		}
	}
}

/************************************************************************************
NOMBRE:
	verificar_cliente_bd
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	busca un si un cliente existe en la base de datos
************************************************************************************/
function reenviar_clave() {
	escribir_mensaje('div_mensajes', 'Espera un momento mientras se obtienen tus datos de acceso' , 'amarillo');
	
	mail = document.getElementById('txtEmail').value;
	
	if ( trim(mail) != '' ) {
		variables = 'accion=recuperar_clave&correo='+escape(mail);
		
		var myConn = new XHConn();
		if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
		
		var peticion = function (oXML) {
			regreso = oXML.responseText;
			if ( regreso == 'La clave ha sido enviada a tu correo' ) { colorm = 'verde'; }
			else { colorm = 'rojo'; }
			escribir_mensaje('div_mensajes', regreso , colorm);
		};
		
		myConn.connect( 'includes/contratar/ajax.php', "POST", variables, peticion );
	}
	else {
		escribir_mensaje('div_mensajes', 'Escribe tu correo electronico' , 'rojo');
		document.getElementById('txtEmail').focus();
	}
	
}

/************************************************************************************
NOMBRE:
	verificar_cliente_bd
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	busca un si un cliente existe en la base de datos
************************************************************************************/
function verificar_cliente_bd() {
	// lipiar cualquier posible mensaje
	document.getElementById('div_mail').innerHTML = '';
	// obtener los datos y crear las variables post
	correo_nuevo = document.getElementById('txtMail').value;
	variables = 'accion=buscar_cliente_bd&correo='+escape(correo_nuevo);
	
	// eliminar los espacios en blanco al inicio y fin de la cadena
	if ( trim(correo_nuevo) != '' ) {
		// poner imagen de espera
		document.getElementById('div_mail').innerHTML = '<img src="load_black.gif" />';
		var myConn = new XHConn();
		if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
		// funcion de regreso
		var peticion = function (oXML) {
			regreso = oXML.responseText;
			if ( regreso == 'existe' ) {
				// si exiete, apagar la bandera de cliente ok y limpiar los text del mail. notificar.
				cliente_ok = false;
				document.getElementById('txtMail').value = '';
				document.getElementById('txtMailConfirm').value = '';
				
				document.getElementById('txtMail').focus();
				document.getElementById('div_mail').innerHTML = 'El correo ya esta registrado.';
			}
			else {
				document.getElementById('div_mail').innerHTML = '';
			}
		};
		
		myConn.connect( 'includes/contratar/ajax.php', "POST", variables, peticion );
	}
}


/************************************************************************************
NOMBRE:
	verificar_cliente
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	busca un si un cliente existe en la base de datos
************************************************************************************/
function verificar_cliente() {
	// limpiar la seccion de mensajes
	escribir_mensaje('div_mensajes', '', '');
	// obtener los datos necesarios para autenticar al cliente
	mail = document.getElementById('txtEmail').value;
	pass = document.getElementById('txtPass').value;
	
	// desactivar la casilla de factura
	document.getElementById('chkFactura').checked = false;
	document.getElementById('chkFactura').disabled = 'disabled';
	// si es basura explorer 7
	if ( navegador == 7 ) {
		document.getElementById('chkFactura').disabled = true;
	}
	// cambiar el posible combo de rfc's y poner la id de factura por default
	document.getElementById('div_rfc_combo').innerHTML = '';
	document.getElementById('div_rfc_combo').style.display = 'none';
	document.getElementById('div_rfc_text').style.display = '';
	document.getElementById('hidFFactura').value = '0';
	
	limpiar_divs_error();
	limpiar_divs_errorfactura();
	
	if ( mail == '' || pass == '' ) {
		escribir_mensaje_2('div_mensajes', 'Por favor escribe tu E-Mail o Contrase&ntilde;a', 'rojo');
	}
	else {
		//escribir_mensaje_2('div_mensajes', 'Por favor espera un momento mientras te buscamos en nuestra base de datos', 'amarillo');
		escribir_mensaje('div_mensajes', '&nbsp;', 'amarillo');
		variables = 'accion=buscar_cliente&mail='+escape(mail)+'&pass='+escape(pass);
		ajax1('includes/contratar/ajax.php','',variables,'datos_cliente');
	}
}

/************************************************************************************
NOMBRE:
	desplegar_datos_cliente
ENDTRADAS:
	datos_ajax -> cadena con los datos que regresa el php
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	parsea una cadena recibida mediante ajax y posteriormente lo despliega en los campos de formulario correspondientes
************************************************************************************/
function desplegar_datos_cliente(datos_ajax) {
	//desplegar el mensaje de login correcto
	escribir_mensaje('div_mensajes', 'Tus datos de acceso son correctos. Hemos cargado tu informaci&oacute;n personal a la orden de compra.', 'verde');
	// obtener los valores
	var arreglo_datos = new Array();
	arreglo_datos = datos_ajax.split('|');
	nombre = arreglo_datos[0];   // nombre del cliente
	apellidos = arreglo_datos[1];   // apellidos del cliente
	email = arreglo_datos[2];   // mail del cliente
	empresa = arreglo_datos[3];   // empresa del cliente
	direccion = arreglo_datos[4];   // direccion del cliente
	pais = arreglo_datos[5];   // pais(combobox) del cliente
	estado = arreglo_datos[6];   // estado(combobox) del cliente
	ciudad = arreglo_datos[7];   // ciudad del cliente
	cp = arreglo_datos[8];   // cp del cliente
	telefono = arreglo_datos[9];   // telefono del cliente
	cliente_id = arreglo_datos[10];   // telefono del cliente
	distribuidor_descuento = arreglo_datos[11];   // telefono del cliente	
	domainer = arreglo_datos[12];   // descuento de domainer
		
	// cargar los valores en el formulario
	document.getElementById('txtNombre').value = html_entity_decode( nombre );
	document.getElementById('txtApellidos').value = html_entity_decode( apellidos );
	document.getElementById('txtMail').value = email;
	document.getElementById('txtMailConfirm').value = email;
	document.getElementById('txtEmpresa').value = html_entity_decode( empresa );
	document.getElementById('txtDireccion').value = html_entity_decode( direccion );
	document.getElementById('div_combo_pais').innerHTML = pais;
	document.getElementById('div_combo_estado').innerHTML = estado;
	document.getElementById('txtCiudad').value = html_entity_decode( ciudad );
	document.getElementById('txtCp').value = cp;
	document.getElementById('txtTelefono').value = telefono;
	
	
	/*document.getElementById('txtNombre').innerHTML = html_entity_decode( nombre );
	document.getElementById('txtApellidos').innerHTML = html_entity_decode( apellidos );
	document.getElementById('txtMail').innerHTML = email;
	document.getElementById('txtMailConfirm').innerHTML = email;
	document.getElementById('txtEmpresa').innerHTML = html_entity_decode( empresa );
	document.getElementById('txtDireccion').innerHTML = html_entity_decode( direccion );
	document.getElementById('div_combo_pais').innerHTML = pais;
	document.getElementById('div_combo_estado').innerHTML = estado;
	document.getElementById('txtCiudad').innerHTML = html_entity_decode( ciudad );
	document.getElementById('txtCp').innerHTML = cp;
	document.getElementById('txtTelefono').innerHTML = telefono;*/
	
	// actualizar el id del cliente
	document.getElementById('hidCliente').value = cliente_id;
	// cada vez que se valide un cliente, se deben reiniciar los datos de facturacion
	
	if ( domainer=="no" && distribuidor_descuento != '0' ) {
            document.getElementById('span_indicador_descuento').innerHTML = 'Aplicar&aacute; '+distribuidor_descuento+' % de descuento en hosting';
	}
        else if (domainer == "si")
        {
            document.getElementById('span_indicador_descuento').innerHTML = 'Aplicar&aacute; descuento por domainer';
        }
	
	// bloquea los campos
	//bloquear_datos_cliente('si');
	// enciende la bandera
	cliente_ok = true;	
	
	// habilitar la casilla de facturacion
	document.getElementById('chkFactura').checked = false;
	document.getElementById('chkFactura').disabled = '';
	// si es basura explorer 7
	if ( navegador == 7 ) {
		document.getElementById('chkFactura').disabled = false;
	}
	
	// limpiar los datos de facturacion  (si para indicar que deseo reiniciar el arreglo de facturas)
	limpiar_datos_factura('si');
	
	/*alert(document.getElementById('txtNombre').value);
	alert(document.getElementById('txtApellidos').value);
	alert(document.getElementById('txtMail').value);
	alert(document.getElementById('txtMailConfirm').value);
	alert(document.getElementById('txtEmpresa').value);
	alert(document.getElementById('txtDireccion').value);
	alert(document.getElementById('txtCiudad').value);
	alert(document.getElementById('txtCp').value);
	alert(document.getElementById('txtTelefono').value);*/
}

/************************************************************************************
NOMBRE:
	verificar_factura
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	busca si un cliente existe en la base de datos tiene datos de facturacion, o bien
************************************************************************************/
function verificar_factura() {
	// si la casilla esta activa, solicitar las facturas
	if ( document.getElementById('chkFactura').checked == true ) {
		// si los datos del cliente son correctos
		if ( document.getElementById('radClientereg').checked == false ) {
			datos_correctos_de_cliente = validar_datos_cliente();
		}
		else {
			datos_correctos_de_cliente = true;
		}
		
		if ( datos_correctos_de_cliente ) {
			// si las facturas no estan cargadas, solicitar al php la informacion
			if ( info_facturas == false ) {
				// obtener el id del cliente
				cliente_id = document.getElementById('hidCliente').value;
				// si no es cliente nuevo, llamar al php
				if ( cliente_id != 0 ) {
					// limpiar la seccion de mensajes
					escribir_mensaje('div_mensajes_factura', '', '');
					//escribir_mensaje('div_mensajes_factura', 'Por favor espera un momento mientras te buscamos en nuestra base de datos', 'amarillo');
					escribir_mensaje('div_mensajes_factura', '&nbsp;', 'amarillo');
					variables = 'accion=buscar_factura&cliente='+escape(cliente_id);
					ajax1('includes/contratar/ajax.php','',variables,'datos_factura');
				}
				else {
					factura_ok = false;
					bloquear_datos_factura('no');
					document.getElementById('txtFRfc').focus();
				}
			}
			// si ya estan cargadas, solo llamar al desplegador
			else {
				desplegar_datos_factura(cadena_datos_facturas);
			}
		}
		else {
			document.getElementById('chkFactura').checked = false;
			factura_ok = true;
		}
	}
	else{		
		document.getElementById('div_rfc_combo').style.display = 'none';
		document.getElementById('div_rfc_text').style.display = '';		
		document.getElementById('div_mensajes_factura').innerHTML = '';
		limpiar_datos_factura('si');
		bloquear_datos_factura('si');
                //$('#chkModFact').attr("checked",false);
                //$('#chkModFact').attr("disabled",true);
	}
}

/************************************************************************************
NOMBRE:
	desplegar_datos_factura
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	muestra la informacion de las factruras regresada por ajax
************************************************************************************/
function desplegar_datos_factura(datos_ajax) {
	//$('#chkModFact').removeAttr("disabled");
	// asignar los datos
	cadena_datos_facturas = datos_ajax;
	info_facturas = true;
	// variables de arreglos
	var arreglo_datosfacturas = new Array();
	arreglo_datosfacturas = datos_ajax.split('|');
	
	// si no trae ninguna alerta
	if ( arreglo_datosfacturas[0] != '#Advertencia#' ) {
		opciones_combo = '';
		// recorrer el arreglo de las facturas obtenidas
		for ( f=0; f<arreglo_datosfacturas.length; f++ ) {
			// arreglo global de las facturas
			arreglo_facturas[f] = new Array();
			// obtener los datos de la factura actual
			arreglo_datos_factura = new Array();
			arreglo_datos_factura = arreglo_datosfacturas[f].split("}");
			// llenar el arreglo global
			arreglo_facturas[f]['id'] = html_entity_decode( arreglo_datos_factura[0] );
			arreglo_facturas[f]['rfc'] = html_entity_decode( arreglo_datos_factura[1] );
			arreglo_facturas[f]['nombre'] = html_entity_decode( arreglo_datos_factura[2] );
			arreglo_facturas[f]['calle'] = html_entity_decode( arreglo_datos_factura[3] );
			arreglo_facturas[f]['num_ext'] = html_entity_decode( arreglo_datos_factura[4] );
			arreglo_facturas[f]['num_int'] = html_entity_decode( arreglo_datos_factura[5] );
			arreglo_facturas[f]['colonia'] = html_entity_decode( arreglo_datos_factura[6] );
			arreglo_facturas[f]['municipio'] = html_entity_decode( arreglo_datos_factura[7] );
			arreglo_facturas[f]['ciudad'] = html_entity_decode( arreglo_datos_factura[8] );
			arreglo_facturas[f]['estado'] = html_entity_decode( arreglo_datos_factura[9] );
			arreglo_facturas[f]['cp'] = html_entity_decode( arreglo_datos_factura[10] );
			
			// construir los elementos del combo para seleccionar la factura
			opciones_combo += '<option value="'+f+'">' + arreglo_facturas[f]['rfc'] + '</option>';
			
		}
		// agregar la opcion de 'otro RFC'
		opciones_combo += '<option value="99999">Otro RFC</option>';
		
		// limpiar el mensaje de espera de las facturas
		document.getElementById('div_mensajes_factura').innerHTML = '';
		// poner el combo en su lugar
		document.getElementById('div_rfc_combo').innerHTML = '<select id="cmbFRfc" name="cmbFRfc" onchange="cambiar_rfc()">'+opciones_combo+'</select>';
		document.getElementById('div_rfc_combo').style.display = '';
		document.getElementById('div_rfc_text').style.display = 'none';
		// llenar el resto de los campos con la info que le corresponde al rfc seleccionado (por defecto el primero)
		document.getElementById('hidFFactura').value = arreglo_facturas[0]['id']; 
		document.getElementById('txtFNombre').value = arreglo_facturas[0]['nombre']; 
		document.getElementById('txtFCalle').value = arreglo_facturas[0]['calle']; 
		document.getElementById('txtFNumext').value = arreglo_facturas[0]['num_ext']; 
		document.getElementById('txtFNumint').value = arreglo_facturas[0]['num_int']; 
		document.getElementById('txtFColonia').value = arreglo_facturas[0]['colonia']; 
		document.getElementById('txtFMunicipio').value = arreglo_facturas[0]['municipio']; 
		document.getElementById('txtFCiudad').value = arreglo_facturas[0]['ciudad']; 
		document.getElementById('cmbFEstado').value = arreglo_facturas[0]['estado']; 
		document.getElementById('txtFCp').value = arreglo_facturas[0]['cp'];
                $('#sp_mod_rfc').show();
                $('#txtFRfc').val($('#cmbFRfc option:selected').text());
                $('#div_rfc_combo').show();
                $('#sp_mod_rfc').show();
                $('#div_rfc_text').hide();
                $('#sp_canc_rfc').hide();

                bloquear_datos_factura('no');

	}
	else {
		document.getElementById('div_mensajes_factura').innerHTML = arreglo_datosfacturas[1];
		if ( arreglo_datosfacturas[1] == 'No tienes datos de facturacion registrados en el sistema' ) {
			bloquear_datos_factura ('no');
			document.getElementById('txtFRfc').focus();
		}
	}
}

function cambiar_rfc() {
	// obtener la posicion del arreglo
	pos_rfc = document.getElementById('cmbFRfc').value;
	pos_rfc = parseInt(pos_rfc);
        $('#chkModFact').attr('checked',false);
	// quitar cualquier posible error
	limpiar_divs_errorfactura();
	// verificar que se trata de un rfc registrado o uno nuevo
	if ( pos_rfc == 99999 ) {
		//document.getElementById('div_rfc_text').style.display = '';
		document.getElementById('hidFFactura').value = '0'; 
		bloquear_datos_factura('no');
		limpiar_datos_factura('no'); // (no) para indicarle que no deseo reiniciar el arreglo de las facturas
		//document.getElementById('txtFRfc').focus();

                $('#sp_mod_rfc').hide();
                $('#txtFRfc').val('');
                $('#div_rfc_combo').hide();
                $('#sp_mod_rfc').hide();
                $('#div_rfc_text').show();
                $('#sp_canc_rfc').show();
	}
	else {
                $('#sp_mod_rfc').show();
                $('#txtFRfc').val($('#cmbFRfc option:selected').text());
		// llenar el resto de los campos con la info que le corresponde al rfc seleccionado (por defecto el primero)
		//document.getElementById('div_rfc_text').style.display = 'none';
		//bloquear_datos_factura('si');
		document.getElementById('hidFFactura').value = arreglo_facturas[pos_rfc]['id']; 
		document.getElementById('txtFNombre').value = arreglo_facturas[pos_rfc]['nombre']; 
		document.getElementById('txtFCalle').value = arreglo_facturas[pos_rfc]['calle']; 
		document.getElementById('txtFNumext').value = arreglo_facturas[pos_rfc]['num_ext']; 
		document.getElementById('txtFNumint').value = arreglo_facturas[pos_rfc]['num_int']; 
		document.getElementById('txtFColonia').value = arreglo_facturas[pos_rfc]['colonia']; 
		document.getElementById('txtFMunicipio').value = arreglo_facturas[pos_rfc]['municipio']; 
		document.getElementById('txtFCiudad').value = arreglo_facturas[pos_rfc]['ciudad']; 
		document.getElementById('cmbFEstado').value = arreglo_facturas[pos_rfc]['estado']; 
		document.getElementById('txtFCp').value = arreglo_facturas[pos_rfc]['cp'];
	}
}

/************************************************************************************
NOMBRE:
	cambiar_tipo_cliente
ENDTRADAS:
	sid -> sufijo de la id del radiobutton
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	parsea una cadena recibida mediante ajax y posteriormente lo despliega en los campos de formulario correspondientes
************************************************************************************/
function cambiar_tipo_cliente(sid) {
	document.getElementById('span_indicador_descuento').innerHTML = '';
	if ( document.getElementById('radClientereg') && document.getElementById('radClientenew') ) {
		// si se pone a jugar entre las opciones, limpiar los datos
		limpiar_datos_cliente('todos');
		limpiar_datos_factura('si'); // si para indicarle que si deseo reiniciar el arreglo de las facturas
		limpiar_divs_error();
		// desactivar la check de requerir factura
		document.getElementById('chkFactura').checked = false;
		// cambiar el posible combo de rfc's y poner la id de factura por default
		document.getElementById('div_rfc_combo').innerHTML = '';
		document.getElementById('div_rfc_combo').style.display = 'none';
		document.getElementById('div_rfc_text').style.display = '';
		document.getElementById('hidFFactura').value = '0';
		
		
		// si selecciona la opcion de cliente registrado, desmarcar el de nuevo
		if ( sid == 'reg' ) {
			document.getElementById('radClientereg').checked = 'checked';
			document.getElementById('radClientenew').checked = '';
			document.getElementById('hidTipocliente').value = 'reg';
			desbloquear_cliente_registrado();
			// deshabilitar la casilla de facturacion
			document.getElementById('chkFactura').disabled = 'disabled';
			// si es basura explorer 7
			if ( navegador == 7 ) {
				document.getElementById('chkFactura').disabled = true;
			}
		}
		if ( sid == 'new' ) {
			// bloquear los controles de login
			document.getElementById('radClientenew').checked = 'checked';
			document.getElementById('radClientereg').checked = '';
			document.getElementById('hidTipocliente').value = 'new';
			// desbloquear los controles de datos de cliente
			desbloquear_cliente_nuevo();
			// habilitar la casilla de facturacion
			document.getElementById('chkFactura').disabled = '';
			// si es basura explorer 7
			if ( navegador == 7 ) {
				document.getElementById('chkFactura').disabled = false;
			}
			// dejan de ser validos los datos del cliente
			cliente_ok = false;
		}
	}
}

/************************************************************************************
NOMBRE:
	desbloquer_cliente_registrado
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	bloquea los campos para introducir los datos de cliente nuevo y desbloquea los de cliente registrado
************************************************************************************/
function desbloquear_cliente_registrado() {
	// limpiar datos
	limpiar_datos_cliente();
	// bloquear campos 
	bloquear_datos_cliente('si');
	// poner el foco en el text de correo
	//document.getElementById('txtEmail').focus();//por fer 26/04/10 para nuevo dise�o 
}

/************************************************************************************
NOMBRE:
	desbloquer_cliente_registrado
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	bloquea los campos para introducir los datos de cliente nuevo y desbloquea los de cliente registrado
************************************************************************************/
function desbloquear_cliente_nuevo() {
	// limpiar datos
	limpiar_datos_cliente('todos');
	// bloquear campos 
	bloquear_datos_cliente('no');
	document.getElementById('div_mensajes').innerHTML = '';
	// poner el foco en el text de correo
	document.getElementById('txtNombre').focus();
}

/************************************************************************************
NOMBRE:
	limpiar_datos_cliente
ENDTRADAS:
	todos -> indica si incluye tambien el formulario de login
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	limpia los campos donde el cliente debe introducir sus datos, o bien, son cargados por default
************************************************************************************/
function limpiar_datos_cliente(todos) {
	if ( todos == 'todos' ) {
		document.getElementById('txtEmail').value = '';
		document.getElementById('txtPass').value = '';
	}
	
	document.getElementById('txtNombre').value = '';
	document.getElementById('txtApellidos').value = '';
	document.getElementById('txtMail').value = '';
	document.getElementById('txtMailConfirm').value = '';
	document.getElementById('txtEmpresa').value = '';
	document.getElementById('txtDireccion').value = '';
	document.getElementById('txtCiudad').value = '';
	document.getElementById('txtCp').value = '';
	document.getElementById('txtTelefono').value = '';
	document.getElementById('cmbPais').selected = 0;
	document.getElementById('cmbEstado').selected = 0;
	document.getElementById('hidCliente').value = 0;
}

/************************************************************************************
NOMBRE:
	limpiar_datos_factura
ENDTRADAS:
	reiniciar -> indica si se desea reiniciar el arreglo de las facturas la cargadas
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	limpia los campos donde el cliente debe introducir sus datos de facturacion, o bien, son cargados por default
************************************************************************************/
function limpiar_datos_factura(reiniciar) {
	// limpiar los campos del formulario	
	document.getElementById('txtFNombre').value = '';
	document.getElementById('txtFCalle').value = '';
	document.getElementById('txtFNumext').value = '';
	document.getElementById('txtFNumint').value = '';
	document.getElementById('txtFColonia').value = '';
	document.getElementById('txtFMunicipio').value = '';
	document.getElementById('txtFCiudad').value = '';
	document.getElementById('txtFCp').value = '';
	document.getElementById('cmbFEstado').selected = 0;
	// reiniciar las banderas de factura
	factura_ok = true;
	info_facturas = false;
	if ( reiniciar == 'si' ) {
		cliente_facturas = 0;
		arreglo_facturas = new Array();
	}
}

/************************************************************************************
NOMBRE:
	bloquear_datos_cliente
ENDTRADAS:
	accion -> indica si se bloquean o desbloquean los campos (si para bloquear, no para desbloquear)
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	bloquea los campos donde el cliente debe introducir sus datos, o bien, son cargados por default
************************************************************************************/
function bloquear_datos_cliente(accion) {
	estado_c = 'disabled';
	combos = true;
	// esto lo necesita el IE7
	if ( navegador == 7 ) {
		estado_c = true;	// disabled = true
	}
	// si la accion es no, significa que se desbloquean
	if ( accion == 'no' ) {
		estado_c = '';
		combos = false;
		if ( navegador == 7 ) {
			estado_c = false;	// disabled = true
		}
		document.getElementById('txtEmail').disabled = 'disabled';
		document.getElementById('txtPass').disabled = 'disabled';
		//document.getElementById('btnVerificar').disabled = 'disabled';
		//document.getElementById('btnResend').disabled = 'disabled';
	}
	else {
		document.getElementById('txtEmail').disabled = '';
		document.getElementById('txtPass').disabled = '';
		//document.getElementById('btnVerificar').disabled = '';
		//document.getElementById('btnResend').disabled = '';
	}
	// bloquear los controles
	document.getElementById('txtNombre').disabled = estado_c;
	document.getElementById('txtApellidos').disabled = estado_c;
	document.getElementById('txtMail').disabled = estado_c;
	document.getElementById('txtMailConfirm').disabled = estado_c;
	document.getElementById('txtEmpresa').disabled = estado_c;
	document.getElementById('txtDireccion').disabled = estado_c;
	document.getElementById('cmbPais').disabled = combos;
	document.getElementById('cmbEstado').disabled = combos;
	document.getElementById('txtCiudad').disabled = estado_c;
	document.getElementById('txtCp').disabled = estado_c;
	document.getElementById('txtTelefono').disabled = estado_c;
}

/************************************************************************************
NOMBRE:
	bloquear_datos_factura
ENDTRADAS:
	accion -> indica si se bloquean o desbloquean los campos (si para bloquear, no para desbloquear)
SALIDAS: 
	<< ninguna >>
DESCRIPCION:
	bloquea los campos donde el cliente debe introducir sus datos de facturacion, o bien, son cargados por default
************************************************************************************/
function bloquear_datos_factura(accion) {
	estado_c = true;
	combos = true;
	// esto lo necesita el IE7
	if ( navegador == 7 ) {
		estado_c = true;	// disabled = true
	}
	// si la accion es no, significa que se desbloquean
	if ( accion == 'no' ) {
		estado_c = '';
		// esto lo necesita el IE7
		if ( navegador == 7 ) {
			estado_c = false;	// disabled = true
		}
		combos = false;
	}
	
	// bloquear los controles
	//if(document.getElementById('div_rfc_text').style.display != 'none')
	document.getElementById('txtFRfc').disabled = estado_c;
	document.getElementById('txtFNombre').disabled = estado_c;
	document.getElementById('txtFCalle').disabled = estado_c;
	document.getElementById('txtFNumint').disabled = estado_c;
	document.getElementById('txtFNumext').disabled = estado_c;
	document.getElementById('txtFColonia').disabled = estado_c;
	document.getElementById('txtFMunicipio').disabled = combos;
	document.getElementById('txtFCiudad').disabled = combos;
	document.getElementById('txtFCp').disabled = estado_c;
	document.getElementById('cmbFEstado').disabled = combos;
}


/************************************************************************************
NOMBRE:
	terminar_compra
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	realizar las validaciones necesarias para continuar al paso 3 de contratacion y envia los datos al mismo
************************************************************************************/

function terminar_compra_2(validarEnc) {	
		// validar que los datos del cliente sean correctos
		if ( document.getElementById('radClientereg').checked == false ) {
			datos_correctos_de_cliente = validar_datos_cliente();
		}
		else {
			datos_correctos_de_cliente = true;
		}
		if ( !datos_correctos_de_cliente ) {
			cliente_ok = false;
		}
		// si los datos del cliente son correctos, verificar los datos de facturacion
		else {
			if ( !validar_datos_factura() ) {
				factura_ok = false;				
			}
		}
	
		// si todos los datos estan bien, subir el formulario
	if ( cliente_ok && factura_ok ) {		
		document.getElementById('div_mensajes_factura').innerHTML = '';		
		if(validarEnc == 'si')
			validoBien = ValidaEncuesta();
		else
			validoBien = true;
		if(validoBien !== false){			
			if ( document.getElementById('chkTerminos').checked == true ) {				
				var datos = '';
				// si el cliente existe, solo concatenar el id
				if ( document.getElementById('hidCliente').value != '0' ) {
					datos += 'cliente=' + document.getElementById('hidCliente').value + ',';
					datos += 'tipocliente=reg,';
				}
				// si es nuevo, poner el resto de los datos
				else {
					datos += 'nombre=' + document.getElementById('txtNombre').value + ',';
					datos += 'apellidos=' + document.getElementById('txtApellidos').value + ',';
					datos += 'email=' + document.getElementById('txtMail').value + ',';
					datos += 'empresa=' + document.getElementById('txtEmpresa').value + ',';
					datos += 'direccion=' + document.getElementById('txtDireccion').value + ',';
					datos += 'pais=' + document.getElementById('cmbPais').value + ',';
					datos += 'estado=' + document.getElementById('cmbEstado').value + ',';
					datos += 'ciudad=' + document.getElementById('txtCiudad').value + ',';
					datos += 'cp=' + document.getElementById('txtCp').value + ',';
					datos += 'telefono=' + document.getElementById('txtTelefono').value + ',';
					datos += 'tipocliente=new,';
				}
				
				// verificar si existe factura
				if ( document.getElementById('chkFactura').checked == true ) {
					// si la factura existe, solo concatenar el id
					if ( document.getElementById('hidFFactura').value != '0' ) {
						datos += 'factura=' + document.getElementById('hidFFactura').value + ',';
						datos += 'tipofactura=reg,';
					}
					// si es nueva, poner el resto de los datos
					else {
						datos += 'f_rfc=' + document.getElementById('txtFRfc').value + ',';
						datos += 'f_nombre=' + document.getElementById('txtFNombre').value + ',';
						datos += 'f_calle=' + document.getElementById('txtFCalle').value + ',';
						datos += 'f_numext=' + document.getElementById('txtFNumext').value + ',';
						datos += 'f_numint=' + document.getElementById('txtFNumint').value + ',';
						datos += 'f_colonia=' + document.getElementById('txtFColonia').value + ',';
						datos += 'f_municipio=' + document.getElementById('txtFMunicipio').value + ',';
						datos += 'f_ciudad=' + document.getElementById('txtFCiudad').value + ',';
						datos += 'f_estado=' + document.getElementById('cmbFEstado').value + ',';
						datos += 'f_cp=' + document.getElementById('txtFCp').value + ',';
						datos += 'tipofactura=new,';
					}
				}
				else {
					document.getElementById('hidFFactura').value = '0';
					datos += 'factura=' + document.getElementById('hidFFactura').value + ',';
					datos += 'tipofactura=no,';
				}
				
				// quitar la ultima coma
				datos = datos.substr( 0, datos.length-1 );
				variables = 'accion=crear_llave&datos=' + escape(datos) + '&param1=FINXFIN';
				
				var myConn = new XHConn();
				if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
				document.getElementById('botones_compra').innerHTML = '<img src="load_black.gif" />';
				var peticion = function (oXML) {
					regreso = oXML.responseText;
					document.getElementById('hidDatos').value = regreso;
					document.getElementById('contesto').value = validarEnc;
					//document.getElementById('botones_compra').innerHTML = regreso;
					document.frmDatoscliente.submit();
				}
				myConn.connect( 'includes/contratar/ajax.php', "POST", variables, peticion );
			}
			else {
				alert ( 'Para continuar, selecciona la casilla de\n"He leido y acepto el contrato general de servicios"' );
			}
		}else alert('Para concluir por favor indique el medio por el que se enter� de nosotros');
	}	
}

function terminar_compra() {
	// validar que los datos del cliente sean correctos
	if ( document.getElementById('radClientereg').checked == false ) {
		datos_correctos_de_cliente = validar_datos_cliente();
	}
	else {
		datos_correctos_de_cliente = true;
	}
	if ( !datos_correctos_de_cliente ) {
		cliente_ok = false;
	}
	// si los datos del cliente son correctos, verificar los datos de facturacion
	else {
		if ( !validar_datos_factura() ) {
			factura_ok = false;
		}
	}
	
	// si todos los datos estan bien, subir el formulario
	if ( cliente_ok && factura_ok ) {
		if ( document.getElementById('chkTerminos').checked == true ) {
			var datos = '';
			// si el cliente existe, solo concatenar el id
			if ( document.getElementById('hidCliente').value != '0' ) {
				datos += 'cliente=' + document.getElementById('hidCliente').value + ',';
				datos += 'tipocliente=reg,';
			}
			// si es nuevo, poner el resto de los datos
			else {
				datos += 'nombre=' + document.getElementById('txtNombre').value + ',';
				datos += 'apellidos=' + document.getElementById('txtApellidos').value + ',';
				datos += 'email=' + document.getElementById('txtMail').value + ',';
				datos += 'empresa=' + document.getElementById('txtEmpresa').value + ',';
				datos += 'direccion=' + document.getElementById('txtDireccion').value + ',';
				datos += 'pais=' + document.getElementById('cmbPais').value + ',';
				datos += 'estado=' + document.getElementById('cmbEstado').value + ',';
				datos += 'ciudad=' + document.getElementById('txtCiudad').value + ',';
				datos += 'cp=' + document.getElementById('txtCp').value + ',';
				datos += 'telefono=' + document.getElementById('txtTelefono').value + ',';
				datos += 'tipocliente=new,';
			}
			
			// verificar si existe factura
			if ( document.getElementById('chkFactura').checked == true ) {
				// si la factura existe, solo concatenar el id
				if ( document.getElementById('hidFFactura').value != '0' ) {
					datos += 'factura=' + document.getElementById('hidFFactura').value + ',';
					datos += 'tipofactura=reg,';
				}
				// si es nueva, poner el resto de los datos
				else {
					datos += 'f_rfc=' + document.getElementById('txtFRfc').value + ',';
					datos += 'f_nombre=' + document.getElementById('txtFNombre').value + ',';
					datos += 'f_calle=' + document.getElementById('txtFCalle').value + ',';
					datos += 'f_numext=' + document.getElementById('txtFNumext').value + ',';
					datos += 'f_numint=' + document.getElementById('txtFNumint').value + ',';
					datos += 'f_colonia=' + document.getElementById('txtFColonia').value + ',';
					datos += 'f_municipio=' + document.getElementById('txtFMunicipio').value + ',';
					datos += 'f_ciudad=' + document.getElementById('txtFCiudad').value + ',';
					datos += 'f_estado=' + document.getElementById('cmbFEstado').value + ',';
					datos += 'f_cp=' + document.getElementById('txtFCp').value + ',';
					datos += 'tipofactura=new,';
				}
			}
			else {
				document.getElementById('hidFFactura').value = '0';
				datos += 'factura=' + document.getElementById('hidFFactura').value + ',';
				datos += 'tipofactura=no,';
			}
			
			// quitar la ultima coma
			datos = datos.substr( 0, datos.length-1 );
			variables = 'accion=crear_llave&datos=' + escape(datos) + '&param1=FINXFIN';
			
			var myConn = new XHConn();
			if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
			document.getElementById('botones_compra').innerHTML = '<img src="load_black.gif" />';
			var peticion = function (oXML) {
				regreso = oXML.responseText;
				document.getElementById('hidDatos').value = regreso;
				//document.getElementById('botones_compra').innerHTML = regreso;
				document.frmDatoscliente.submit();
			}
			myConn.connect( 'includes/contratar/ajax.php', "POST", variables, peticion );
		}
		else {
			alert ( 'Para continuar, selecciona la casilla de\n"He leido y acepto el contrato general de servicios"' );
		}
	}
}

/************************************************************************************
NOMBRE:
	validar_datos_cliente
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	realiza una validacion de los datos introducidos por los clientes
************************************************************************************/
function validar_datos_cliente() {
	// bandera de errores
	errores = 0;
	// obtener los datos escritos por el cliente
	nombre = trim( document.getElementById('txtNombre').value );
	apellidos = trim( document.getElementById('txtApellidos').value );
	email = trim( document.getElementById('txtMail').value );
	email2 = trim( document.getElementById('txtMailConfirm').value );
	empresa = trim( document.getElementById('txtEmpresa').value );
	direccion = trim( document.getElementById('txtDireccion').value );
	ciudad = trim( document.getElementById('txtCiudad').value );
	cp = trim( document.getElementById('txtCp').value );
	telefono = trim( document.getElementById('txtTelefono').value );
	pais = trim( document.getElementById('cmbPais').value );
	//estado = trim( document.getElementById('cmbEstado').value );
	
	// borrar rastros de errores
	limpiar_divs_error();
	
	// validar el nombre
	if ( !validar_nombre(nombre) ) {
		document.getElementById('div_nombre').innerHTML = '* Escribe un nombre correcto';
		errores ++;
	}
	// validar el apellidos
	if ( !validar_nombre(apellidos) ) {
		document.getElementById('div_apellidos').innerHTML = '* Escribe un apellido correcto';
		errores ++;
	}
	// validar el mail
	if ( !validar_correo(email) ) {
		document.getElementById('div_mail').innerHTML = '* Escribe un E-Mail correcto';
		errores ++;
	}
	else {
		if ( email != email2 ) {
			document.getElementById('div_mailconfirm').innerHTML = '* Los correos no coinciden';
			errores ++;
		}
	}
	// validar el direccion
	exp_dir = /^[a-z0-9�������#_\-\.\:\,\/ ]{3,130}$/i
	if ( !exp_dir.test(direccion) ) {
		document.getElementById('div_direccion').innerHTML = '* El formato de Direccion es incorrecto';
		errores ++;
	}
	// validar el ciudad
	if ( !validar_nombre(ciudad) ) {
		document.getElementById('div_ciudad').innerHTML = '* Escribe una ciudad correcta';
		errores ++;
	}
	
	exp_cp = /^[a-z0-9\- ]{3,10}$/i;
	//if ( isNaN(cp) || cp.length < 5 ) {
	if ( !exp_cp.test(cp) ){
		document.getElementById('div_cp').innerHTML = '* Escribe un codigo postal correcto';
		errores ++;
	}
	if ( isNaN(telefono) || telefono.length < 7 ) {
		document.getElementById('div_telefono').innerHTML = '* Escribe un telefono correcto';
		errores ++;
	}
	
	if ( errores > 0 ) {
		document.location.href = '#a_datos_cliente';
		return (false);
	}
	else {
		cliente_ok = true;
		return (true);
	}
}

/************************************************************************************
NOMBRE:
	validar_datos_factura
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	realiza una validacion de los datos introducidos por los clientes
************************************************************************************/
function validar_datos_factura() {
	if(document.getElementById('chkFactura').checked == true){
		rfc = trim( document.getElementById('txtFRfc').value );
		if ( document.getElementById('hidFFactura').value == '0' ) {
		}
		else{
                      /*  if(!$('#chkModFact').is(':checked'))
                        {
                            //si el rfc que eligio es uno de los que tiene guardados con anterioridad
                            var indice = document.getElementById('cmbFRfc').selectedIndex;
                            rfc = document.getElementById('cmbFRfc').options[indice].text;
                        }*/
		}
		cad_err = validar_datos_rfc_2(rfc,document.getElementById('txtFNombre').value,document.getElementById('txtFCalle').value,document.getElementById('txtFNumext').value,document.getElementById('txtFColonia').value,document.getElementById('txtFCiudad').value,document.getElementById('cmbFEstado').value,document.getElementById('txtFCp').value,'html');
		if(!cad_err){
			factura_ok = true;
			return (true);
		}
		else{
			document.getElementById('div_mensajes_factura').innerHTML = cad_err;
			document.location.href = '#a_datos_factura';
			factura_ok = false
			return (false);
		}
	}
	else{
		factura_ok = true;
		return (true);
	}	
	/*// bandera de errores
	errores = 0;
	if ( document.getElementById('chkFactura').checked == true ) {
		limpiar_divs_errorfactura();
		// si se trata de un nuevo RFC
		rfc = trim( document.getElementById('txtFRfc').value );
		if ( document.getElementById('hidFFactura').value == '0' ) {
			rfc = trim( document.getElementById('txtFRfc').value );			
			if ( rfc.length < 12 || rfc.length > 13 ) { 
				document.getElementById('div_frfc').innerHTML = '* Escribe un RFC correcto';
				errores ++;
			}
		}
		else{
			//si el rfc que eligio es uno de los que tiene guardados con anterioridad
			var indice = document.getElementById('cmbFRfc').selectedIndex;
			rfc = document.getElementById('cmbFRfc').options[indice].text;
		}
		// validar el nombre
		nombre = trim( document.getElementById('txtFNombre').value );
		if ( nombre.length < 1 ) {
			document.getElementById('span_fnombre').innerHTML = '* Escribe la Raz&oacute;n Social';
			errores ++;
		}
		// validar calle
		calle = trim( document.getElementById('txtFCalle').value );
		if ( calle.length < 1 ) {
			document.getElementById('span_fcalle').innerHTML = '* Escribe el nombre de la calle';
			errores ++;
		}
		// validar el num. ext
		num = trim( document.getElementById('txtFNumext').value );
		if ( num.length < 1 ) {
			document.getElementById('span_fnumext').innerHTML = '* Escribe el n&uacute;mero exterior';
			errores ++;
		}
		// validar la colonia
		colonia = trim( document.getElementById('txtFColonia').value );
		if ( colonia.length < 1 ) {
			document.getElementById('span_fcolonia').innerHTML = '* Escribe el nombre de la colonia';
			errores ++;
		}
		
		// validar el ciudad
		ciudad = trim( document.getElementById('txtFCiudad').value );
		if ( ciudad.length < 1 ) {
			document.getElementById('span_fciudad').innerHTML = '* Escribe ciudad o localidad';
			errores ++;
		}
		// validar el cp
		cp = trim( document.getElementById('txtFCp').value );
		if ( isNaN(cp) || cp.length < 5 ) {
			document.getElementById('span_fcp').innerHTML = '* Escribe un c&oacute;digo postal correcto';
			errores ++;
		}
	}
	
	if ( errores > 0 ) {
		document.location.href = '#a_datos_factura';
		factura_ok = false
		return (false);
	}
	else{
		if(document.getElementById('chkFactura').checked == true){
			cad_err = validar_datos_rfc_2(rfc,document.getElementById('txtFNombre').value,document.getElementById('txtFCalle').value,document.getElementById('txtFNumext').value,document.getElementById('txtFColonia').value,document.getElementById('txtFCiudad').value,document.getElementById('cmbFEstado').value,document.getElementById('txtFCp').value,'html');
			if(!cad_err){
				factura_ok = true;
				return (true);
			}
			else{
				document.getElementById('div_mensajes_factura').innerHTML = cad_err;
				document.location.href = '#a_datos_factura';
				factura_ok = false
				return (false);
			}
		}else{
			factura_ok = true;
			return (true);
		}
	}*/
}

/************************************************************************************
NOMBRE:
	limpiar_divs_error
ENDTRADAS:
	<< ninguna >>
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	limpia el contenido de posibles errores se�alados en los divs destinados para ello
************************************************************************************/
function limpiar_divs_error() {
	// limpiar los mensajes de error
	document.getElementById('div_nombre').innerHTML = '';
	document.getElementById('div_apellidos').innerHTML = '';
	document.getElementById('div_mail').innerHTML = '';
	document.getElementById('div_mailconfirm').innerHTML = '';
	document.getElementById('div_direccion').innerHTML = '';
	document.getElementById('div_ciudad').innerHTML = '';
	document.getElementById('div_cp').innerHTML = '';
	document.getElementById('div_telefono').innerHTML = '';
}
function limpiar_divs_errorfactura() {
	// limpiar los mensajes de error
	document.getElementById('div_mensajes_factura').innerHTML = '';
	document.getElementById('div_frfc').innerHTML = '';
	document.getElementById('span_fnombre').innerHTML = '';
	document.getElementById('span_fcalle').innerHTML = '';
	document.getElementById('span_fnumext').innerHTML = '';
	document.getElementById('span_fnumint').innerHTML = '';
	document.getElementById('span_fcolonia').innerHTML = '';
	document.getElementById('span_fmunicipio').innerHTML = '';
	document.getElementById('span_fciudad').innerHTML = '';
	document.getElementById('span_fcp').innerHTML = '';
}


/************************************************************************************
*	FUNCIONES DE USO GENERAL														*
************************************************************************************/

/************************************************************************************
NOMBRE:
	cambiar_estados
ENDTRADAS:
	pos -> ID de los elementos que intervienen en la actualziacion de los precios por periodicidad
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	Actualiza los precios a cobrar en la pagina, e invoca al ajax para actualizar el carrito de comrpa
************************************************************************************/
function cambiar_estados() {
	if ( document.getElementById('cmbPais').value ) {
		codigo_pais = document.getElementById('cmbPais').value;
		variables = 'accion=cambiar_estados&codigo_pais='+codigo_pais;
		ajax1('includes/contratar/ajax.php','div_combo_estado',variables,'escribir');
	}
}


/************************************************************************************
NOMBRE:
	escribir_mensaje
ENDTRADAS:
	div -> indica el id del div donde se va a desplegar el mensaje
	msg -> texto con el mensaje que se desea desplegar
	color -> indica el color del marco del mensaje
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	crea un cuadro de texto con un mensaje para notificar de alguna accion al usuario
************************************************************************************/
function escribir_mensaje(div, msg, color){
	if ( div == '' ) {
		return false;
	}
	else {
		if(msg == "")
			document.getElementById(div).innerHTML = "";
		else if(color == "amarillo")
			document.getElementById(div).innerHTML = 
			'<div style="margin:5px; padding:3px; background-color:#FAEA32;" align="center"><div style="background-color:#FFF; border:1px solid #EF9B52; padding:5px;"><img src="load_black.gif" />'+msg+'</div></div>';	
		else if(color == "rojo")
			document.getElementById(div).innerHTML = 
			'<div style="margin:5px; padding:3px; background-color:#D02626;" align="center"><div style="background-color:#FFF; border:1px solid #D05616; padding:5px;">'+msg+'</div></div>';	
		else
			document.getElementById(div).innerHTML = 
			'<div style="margin:5px; padding:3px; background-color:#5FA83C;" align="center"><div style="background-color:#FFF; border:1px solid #9CD65E; padding:5px;">'+msg+'</div></div>';	
	}
}

/*****************************************************************************
NOMBRE:
	sin_errores
ENDTRADAS:
	texto -> es el codigo HTML regresado por un ajax donde se buscara si se regreso error o no
SALIDAS: 
	true si se detecta que no hay errores; false si se detecta alguno
DESCRIPCI�N:
	verifica que el resultado de un ajax tenga recuadro verde que indica que todo esta bien
*****************************************************************************/
function sin_errores(cadena){
	var verde = "load1";
	
	// Si la cadena contiene verde indicar �xito
	if(cadena.match(verde))
		return true;
	return false;
}

/*******************************************************************
FUNCION:		trim
ENTRADAS:
	cadena		->	Cadena de caracteres a evaluar
SALIDAS:
	cadena		->	Sin espacios en las orillas
DESCRIPCI�N:
	Quita los espacios al principio y al final sde una cadena
*******************************************************************/
function trim(cadena){
	for(i=0; i<cadena.length; ){
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(i+1, cadena.length);
		else
			break;
	}
	for(i=cadena.length-1; i>=0; i=cadena.length-1){
		if(cadena.charAt(i)==" ")
			cadena=cadena.substring(0,i);
		else
			break;
	}
	return(cadena);
}

/************************************************************************************
NOMBRE:
	number_format
ENDTRADAS:
	number -> el numero que se desea dar formato
	decimals -> el numero de lugares decimales
	dec_point -> caracter separador de decimales
	thousands_sep -> caracter separador de miles
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	Actualiza los precios a cobrar en la pagina, e invoca al ajax para actualizar el carrito de comrpa
************************************************************************************/
function number_format (number, decimals, dec_point, thousands_sep) {
    var n = number, prec = decimals;
 
    var toFixedFix = function (n,prec) {
        var k = Math.pow(10,prec);
        return (Math.round(n*k)/k).toString();
    };
 
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep;
    var dec = (typeof dec_point === 'undefined') ? '.' : dec_point;
 
    var s = (prec > 0) ? toFixedFix(n, prec) : toFixedFix(Math.round(n), prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = toFixedFix(Math.abs(n), prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    var decPos = s.indexOf(dec);
    if (prec >= 1 && decPos !== -1 && (s.length-decPos-1) < prec) {
        s += new Array(prec-(s.length-decPos-1)).join(0)+'0';
    }
    else if (prec >= 1 && decPos === -1) {
        s += dec+new Array(prec).join(0)+'0';
    }
    return s;
}


/*****************************************************************************
FUNCION:	html_entity_decode
UTILIDAD:	Convierte todas las entidades HTML a sus car�cteres correspondientes
ENTRADAS:
	string		-> Cadena con entidades HTML
	quote_style	-> Permite especificar la acci�n que se realizar� con las comillas
					dobles y sencillas. La opci�n predeterminada es ENT_COMPAT.
						ENT_COMPAT -> Convierte las comillas dobles e ignora las comillas sencillas.
						ENT_QUOTES -> Convierte ambos tipos de comillas.
						ENT_NOQUOTES ->	Ignora ambos tipos de comillas. 
NOTA:	Depende de la funci�n get_html_translation_table.
SALIDAS:	
	Cadena con sus car�cteres correspondientes a las entidades HTML que tuviese.
*****************************************************************************/
function html_entity_decode( string, quote_style ) 
{
	// +   original by: john (http://www.jd-tech.net)
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net), marc andreu
	// +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   bugfixed by: Onno Marsman, Brett Zamir (http://brett-zamir.me)
	// +      input by: Ratheous, ger
	// -    depends on: get_html_translation_table

	var hash_map = {}, symbol = '', tmp_str = '', entity = '';
	tmp_str = string.toString();

	if (false === (hash_map = this.get_html_translation_table('HTML_ENTITIES', quote_style))) {
		return false;
	}

	for (symbol in hash_map) {
		entity = hash_map[symbol];
		tmp_str = tmp_str.split(entity).join(symbol);
	}
	tmp_str = tmp_str.split('&#039;').join("'");

	return tmp_str;
}


/*****************************************************************************
FUNCION:	get_html_translation_table
UTILIDAD:	Crea una tabla de equivalencias de los caracteres especiales HTML o las entidades HTML.
ENTRADAS:
	table	-> Sirve para especificar la tabla que se desea obtener. El valor predeterminado
				es HTML_SPECIALCHARS.
					HTML_ENTITIES -> Para obtener la tabla de las entidades HTML
					HTML_SPECIALCHARS -> Para obtener la tabla de los caracteres especiales HTML.
	quote_style	-> Permite especificar como ser�n incluidas las comillas dobles y sencillas
					en la tabla. La opci�n predeterminada es ENT_COMPAT.
						ENT_COMPAT -> Las comillas dobles ser�n incluidas e ignora las comillas sencillas.
						ENT_QUOTES -> Ambos tipos de comillas ser�n incluidas.
						ENT_NOQUOTES ->	Ignora ambos tipos de comillas. 
SALIDAS:	
	Tabla en forma de arreglo con las equivalencias pedidas en el par�metro table.
*****************************************************************************/
function get_html_translation_table(table, quote_style) 
{
	// http://kevin.vanzonneveld.net
	// +   original by: Philip Peterson
	// +    revised by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +   bugfixed by: noname, Alex, Marco, madipta, KELAN, Brett Zamir, T.Wild
	// +   improved by: Brett Zamir (http://brett-zamir.me)
	// +      input by: Frank Forte, Ratheous

	var entities = {}, hash_map = {}, decimal = 0, symbol = '';
	var constMappingTable = {}, constMappingQuoteStyle = {};
	var useTable = {}, useQuoteStyle = {};

	// Translate arguments
	constMappingTable[0]      = 'HTML_SPECIALCHARS';
	constMappingTable[1]      = 'HTML_ENTITIES';
	constMappingQuoteStyle[0] = 'ENT_NOQUOTES';
	constMappingQuoteStyle[2] = 'ENT_COMPAT';
	constMappingQuoteStyle[3] = 'ENT_QUOTES';

	useTable       = !isNaN(table) ? constMappingTable[table] : table ? table.toUpperCase() : 'HTML_SPECIALCHARS';
	useQuoteStyle = !isNaN(quote_style) ? constMappingQuoteStyle[quote_style] : quote_style ? quote_style.toUpperCase() : 'ENT_COMPAT';

	if (useTable !== 'HTML_SPECIALCHARS' && useTable !== 'HTML_ENTITIES') {
		throw new Error("Table: "+useTable+' not supported');
		// return false;
	}

	entities['38'] = '&amp;';
	if (useTable === 'HTML_ENTITIES') {
		entities['160'] = '&nbsp;';
		entities['161'] = '&iexcl;';
		entities['162'] = '&cent;';
		entities['163'] = '&pound;';
		entities['164'] = '&curren;';
		entities['165'] = '&yen;';
		entities['166'] = '&brvbar;';
		entities['167'] = '&sect;';
		entities['168'] = '&uml;';
		entities['169'] = '&copy;';
		entities['170'] = '&ordf;';
		entities['171'] = '&laquo;';
		entities['172'] = '&not;';
		entities['173'] = '&shy;';
		entities['174'] = '&reg;';
		entities['175'] = '&macr;';
		entities['176'] = '&deg;';
		entities['177'] = '&plusmn;';
		entities['178'] = '&sup2;';
		entities['179'] = '&sup3;';
		entities['180'] = '&acute;';
		entities['181'] = '&micro;';
		entities['182'] = '&para;';
		entities['183'] = '&middot;';
		entities['184'] = '&cedil;';
		entities['185'] = '&sup1;';
		entities['186'] = '&ordm;';
		entities['187'] = '&raquo;';
		entities['188'] = '&frac14;';
		entities['189'] = '&frac12;';
		entities['190'] = '&frac34;';
		entities['191'] = '&iquest;';
		entities['192'] = '&Agrave;';
		entities['193'] = '&Aacute;';
		entities['194'] = '&Acirc;';
		entities['195'] = '&Atilde;';
		entities['196'] = '&Auml;';
		entities['197'] = '&Aring;';
		entities['198'] = '&AElig;';
		entities['199'] = '&Ccedil;';
		entities['200'] = '&Egrave;';
		entities['201'] = '&Eacute;';
		entities['202'] = '&Ecirc;';
		entities['203'] = '&Euml;';
		entities['204'] = '&Igrave;';
		entities['205'] = '&Iacute;';
		entities['206'] = '&Icirc;';
		entities['207'] = '&Iuml;';
		entities['208'] = '&ETH;';
		entities['209'] = '&Ntilde;';
		entities['210'] = '&Ograve;';
		entities['211'] = '&Oacute;';
		entities['212'] = '&Ocirc;';
		entities['213'] = '&Otilde;';
		entities['214'] = '&Ouml;';
		entities['215'] = '&times;';
		entities['216'] = '&Oslash;';
		entities['217'] = '&Ugrave;';
		entities['218'] = '&Uacute;';
		entities['219'] = '&Ucirc;';
		entities['220'] = '&Uuml;';
		entities['221'] = '&Yacute;';
		entities['222'] = '&THORN;';
		entities['223'] = '&szlig;';
		entities['224'] = '&agrave;';
		entities['225'] = '&aacute;';
		entities['226'] = '&acirc;';
		entities['227'] = '&atilde;';
		entities['228'] = '&auml;';
		entities['229'] = '&aring;';
		entities['230'] = '&aelig;';
		entities['231'] = '&ccedil;';
		entities['232'] = '&egrave;';
		entities['233'] = '&eacute;';
		entities['234'] = '&ecirc;';
		entities['235'] = '&euml;';
		entities['236'] = '&igrave;';
		entities['237'] = '&iacute;';
		entities['238'] = '&icirc;';
		entities['239'] = '&iuml;';
		entities['240'] = '&eth;';
		entities['241'] = '&ntilde;';
		entities['242'] = '&ograve;';
		entities['243'] = '&oacute;';
		entities['244'] = '&ocirc;';
		entities['245'] = '&otilde;';
		entities['246'] = '&ouml;';
		entities['247'] = '&divide;';
		entities['248'] = '&oslash;';
		entities['249'] = '&ugrave;';
		entities['250'] = '&uacute;';
		entities['251'] = '&ucirc;';
		entities['252'] = '&uuml;';
		entities['253'] = '&yacute;';
		entities['254'] = '&thorn;';
		entities['255'] = '&yuml;';
	}

	if (useQuoteStyle !== 'ENT_NOQUOTES') {
		entities['34'] = '&quot;';
	}
	if (useQuoteStyle === 'ENT_QUOTES') {
		entities['39'] = '&#39;';
	}
	entities['60'] = '&lt;';
	entities['62'] = '&gt;';

	// ascii decimals to real symbols
	for (decimal in entities) {
		symbol = String.fromCharCode(decimal);
		hash_map[symbol] = entities[decimal];
	}

	return hash_map;
}




function ValidaEncuesta(){
	if( document.getElementById("ch_int").checked || document.getElementById("ch_blog").checked ||
		document.getElementById("ch_busc").checked || document.getElementById("ch_espect").checked ||
		document.getElementById("ch_event").checked || document.getElementById("ch_not_p").checked ||
		document.getElementById("ch_pbus").checked || document.getElementById("ch_pcast").checked ||
		document.getElementById("ch_rad").checked || document.getElementById("ch_recom").checked ||
		document.getElementById("ch_redsoc").checked || document.getElementById("ch_rev").checked )
		return true; 
	else if( document.getElementById("ch_otros").checked && trim(document.getElementById("t_otros").value) != '' )
	return true;
	else return false;	
}

// -------------------------------------------------------------- para los otros produtcos ------------------------------------------------------------------
/************************************************************************************
NOMBRE:
	cambiar_tipo_plan
ENDTRADAS:
	
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	cambia el combo de planes desplegado en la pagina y selecciona el primer plan del tipo seleccionado para actualizar los valores
************************************************************************************/
function cambiar_tipo_plan() {
	tipo_sel = document.getElementById('cmbTipos').value;
	
	// ocultar todos los combos de planes
	for ( i=0; i<arreglo_tipos.length; i++ ) {
		document.getElementById('Plan_'+arreglo_tipos[i]).style.display = 'none';
	}
	// ahora mostrar el plan seleccionado
	document.getElementById('Plan_'+tipo_sel).style.display = '';
	// actualizar el txt de plan
	document.getElementById('txtPlan').value = document.getElementById('Plan_'+tipo_sel).value;
	
	cambiar_plan(document.getElementById('Plan_'+tipo_sel));
}

/************************************************************************************
NOMBRE:
	cambiar_plan
ENDTRADAS:
	elem -> elemento desde donde se toma el tipo de plan
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	actualiza los valores en la pagina acordes al plan seleccionado, tambien muestra u oculta la seccion para pedir el dominio
************************************************************************************/
function cambiar_plan(elem) {
	document.getElementById('txtPlan').value=elem.value
	plan_sel = parseInt(elem.value);
	tipo_sel = document.getElementById('cmbTipos').value;
	var	periodicidad = '';
	// recorrer todos los planes de ese tipo
	for ( i=0; i<arreglo_planes[tipo_sel].length; i++ ) {
		// cuando el plan seleccionado sea igual al actual del recorrido, hacer las operaciones respectivas
		if ( plan_sel == arreglo_planes[tipo_sel][i]['id'] ) {
			// si el plan requiere dominio, mostrar el div para introducirlo e indicar en el input
			if ( arreglo_planes[tipo_sel][i]['requiere_dominio'] == 'si' ) {
				document.getElementById('dominio_plan').style.display = '';
				document.getElementById('txtReqDom').value = 'si';
			}
			// si el plan NO requiere dominio, mostrar el div para introducirlo e indicar en el input
			else {
				document.getElementById('dominio_plan').style.display = 'none';
				document.getElementById('txtReqDom').value = 'no';
			}
			
			// obtener el costo total del plan, as� como su periodicidad
			costo_plan = number_format(arreglo_planes[tipo_sel][i]['costo'],2,'.',',');
			
			if ( arreglo_planes[tipo_sel][i]['periodicidad'] == 12 ) {
				periodicidad = 'anuales';
				document.getElementById('txtPeriodicidad').value = 12;
			}
			else if ( arreglo_planes[tipo_sel][i]['periodicidad'] == 1 ) {
				periodicidad = 'mensuales';
				document.getElementById('txtPeriodicidad').value = 1;
			}
			else {
				periodicidad = 'por activaci&oacute;n';
				document.getElementById('txtPeriodicidad').value = 0;
			}
		}
	}
	
	document.getElementById('costo').innerHTML = costo_plan;
	document.getElementById('periodicidad').innerHTML = periodicidad;
}

/************************************************************************************
NOMBRE:
	contratar_otros
ENDTRADAS:
	
SALIDAS: 
	<< ninguna >>
DESCRIPCI�N:
	valida y envia el formulario de contratacion de otros productos a la primera p�gina del carrito de compra
************************************************************************************/
function contratar_otros() {
	errores = '';
	var periodicidad = '';
	// si se requiere dominio, validarlo
	if ( document.getElementById('txtReqDom').value == 'si' ) {
		ereg = /^[a-zA-Z0-9]+(\-[a-zA-Z0-9]|[a-zA-Z0-9])*$/
		if ( !ereg.test(document.getElementById('txtDominio').value) ) {
			errores += 'Por favor verifica la sintaxis de tu dominio';
		}
	}
	
	if ( errores == '' ) {
		dominio = document.getElementById('txtDominio').value;
		extension = document.getElementById('txtExt').value;
		plan_id = document.getElementById('txtPlan').value;
		periodicidad = document.getElementById('txtPeriodicidad').value;
		
		// crear la cadena con los datos que se van a enviar a la creacion de la llave
		datos_l = "dominio="+dominio+","+"extension="+extension+","+"plan="+plan_id+",periodicidad="+periodicidad;
		// crear las variables que se enviaran
		variables = 'accion=crear_llave&datos='+escape(datos_l)+'&param1=OP';
		
		// conectar a ajax para enviar la llave
		var myConn = new XHConn();
		if (!myConn) alert("XMLHTTP no esta disponible. Intenta con un navegador mas reciente.");
		document.getElementById('link_comprar').innerHTML = '<img src="load_black.gif" />';
		var peticion = function (oXML) {
			regreso = oXML.responseText;
			//escribir_mensaje('div_mensajes', regreso, 'amarillo')
			//document.getElementById('link_comprar').innerHTML = regreso;
			document.frmContratacion.datos.value = regreso;
			//document.getElementById('datos').value = regreso;
			document.frmContratacion.action = 'Contratacion_Paso_1.php';
			document.frmContratacion.submit();
		}
		myConn.connect( 'includes/contratar/ajax.php', "POST", variables, peticion );
	}
	else {
		alert ( errores );
	}
}
