var IMG_WIDTH = 175;
var IMG_HEIGHT = 175;
var IMG_SMALL_WIDTH = 30;
var IMG_SMALL_HEIGHT = 30;
var MAX_WAIT = 30;

var paisPorDefecto = getPais(getCookie('CLAS_IDPAIS'));
if(paisPorDefecto == ''){
	setCookieIDPais(document, getIDPais('España'));
	paisPorDefecto=getPais(getCookie('CLAS_IDPAIS'));
}

//hace aparecer la busqueda avanzada 
function busqueAvanzada(){
	if (document.getElementById('busqueMas').style.display == 'none'){
		document.getElementById('buscaBox').style.height = '200px';
		document.getElementById('busqueMas').style.display = 'block';
	}
	else{ 
		if (document.getElementById('busqueMas').style.display == 'block'){
		document.getElementById('buscaBox').style.height = '190px';
		document.getElementById('busqueMas').style.display = 'none';
		}
	}
}

function SeleccionaCategoria(cat, form) {			
	form.elements['TIPO'].value = cat;
	
	for(var i=0; i<form.length; i++) {
		if(form.elements[i].type == 'text') {
			form.elements[i].value = quitarEspacios(form.elements[i].value);
		}
	}
	Recargar(form);
}

function cambiar_selects(ID, TIPO, VALOR, FORZAR) {
	if ((TIPO == "comunidades")
	 || (TIPO == "provincias")
	 || (TIPO == "poblaciones")) 
		cambiar_selects_cpp(ID, TIPO, VALOR, FORZAR);
	else 
		cambiar_selects_cats(ID, TIPO, VALOR);
}


function cambiar_selects_cpp(ID,TIPO,VALOR,FORZAR) {
	document.getElementById(ID).innerHTML = "";
	C=crear('rnd','option',ID,'AB'); C.innerHTML = "Cargando, espere...";
	document.getElementById(ID).disabled = true;
	fecha = new Date();
	rnd = fecha.getTime();
	if (!(FORZAR) || (FORZAR == 'NO'))

		URL = "http://www.profesor-particular.com/comunidadProvinciaPoblacion.xsql?ID=" + VALOR + "&TIPO=" + TIPO + "&PARA_CACHE=" + rnd;
	else
		URL = "http://www.profesor-particular.com/comunidadProvinciaPoblacion.xsql?ID=" + VALOR + "&TIPO=" + TIPO + "&FORZAR_PAIS=" + FORZAR + "&PARA_CACHE=" + rnd;
		
	ajax(URL, "paso_intermedio", ID);
}


function cambiar_selects_cats(ID, NIVEL, IDPADRE) {
	document.getElementById(ID).innerHTML = "";
	C = crear('rnd', 'option', ID, 'AB');
	C.innerHTML = "Cargando...";
	document.getElementById(ID).disabled = true;
	fecha = new Date();
	rnd = fecha.getTime();
	URL = "listCategorias.xsql?CATEGORIA=" + NIVEL + "&PADRE=" +IDPADRE+ "&NOW=" + rnd;
	ajax(URL, "paso_intermedio", ID + ',N');
}

function paso_intermedio(CONTENIDO, ID, DEBE_BORRAR_ULTIMO) {
	B = document.getElementById(ID);
	B.innerHTML = "";
	A = CONTENIDO.split("\n");
	Cont = A.join("");
	A = Cont.split("  ");
	Cont = A.join("");
	A = Cont.split("///");
	
	for(i=0; A[i]; i++) {
		partes = A[i].split("//");
		C = crear('rnd', 'option', ID, 'AB');
		C.innerHTML = partes[1];
		D = partes[0].split(" ");
		partes[0] = D.join("");
		C.value = partes[0];
	}
	if(DEBE_BORRAR_ULTIMO == 'S')
		borrar(B.lastChild);

	if (B.childNodes.length > 2) {
		B.disabled = false;
		V = URLvar(ID);
		if (V && V != '')
			setTimeout("document.getElementById('"+ID+"').value = '"+V+"';", 200);
			
		if (V && (ID == 'ID1'))
			lanzar_ID2(V);
		else if (V && (ID == 'IDPROVINCIA'))
			lanzar_poblacion(V);
		else ya('ajax_selects');
	}
	else {
		B.disabled = true;
		B.innerHTML = "";
		C = crear('rnd', 'option', ID, 'AB');
		C.innerHTML = "Sin Subcategorias";
		ya('ajax_selects');
	}
	A = null; 
	B = null;
}

function switchHidden(id) {
	var elem = document.getElementById(id).style.display;
	var img = 'http://www.profesor-particular.com/Images/arrow_'
	var diff;
	var arrow;
	switch (elem) {
		case '':
		case 'block':
			elem = 'none';
			diff = 'block';
			arrow = 'down';
			break;
		case 'none':
			elem = 'block';
			diff = 'none';
			arrow = 'up';
			break;
		default:
			break;
	}
	document.getElementById(id).style.display = elem;
	document.getElementById(id + '_div').innerHTML = '<img src="/Images/arrow_' + arrow + '.gif"/>';
	// document.getElementById(id + '_arrow').src = img + arrow + '';				
}


function setTipo(type) {
	document.getElementById('OFERTADEMANDA').value = type;
}

function inicio_pagina() {	
	if (document.getElementById('miAgil')) if (geoip_country_code()!='ES') document.getElementById('miAgil').style.height='1px';

	if (document.getElementById('PAIS')) {
			mostrarSelect(paisPorDefecto);
	}
	myFavs('Prof', "Mi lista", "Eliminar de Mi lista");	
	
	var browserName= navigator.appName;
	var version= navigator.appVersion;
	if (browserName == 'Netscape'){ 
		if ($('idiomaUl') != null){
			$('idiomaUl').style.marginLeft= '30px';
			$('top').style.marginTop= '-15px';
		}
	}
	
	if ($('linkMapBox')) {
		if (GM_country_ID.match('TOD') != null)
			$('linkMapBox').hide();
	}
	
	var browserName= navigator.appName;
	var version= navigator.appVersion;
	if (browserName == 'Netscape'){ 
		if ($('idiomaUl') != null){
			$('idiomaUl').style.marginLeft= '30px';
		}
	}
				
}

function inicio_pagina_home() {
	
	if (document.getElementById('miAgil')) if (geoip_country_code()!='ES') document.getElementById('miAgil').style.height='1px';
	
	var browserName= navigator.appName;
	var version= navigator.appVersion;
	if (browserName == 'Netscape'){ 
		if ($('idiomaUl') != null){
			$('idiomaUl').style.marginLeft= '30px';
			$('top').style.marginTop= '-15px';
		}
	}
	if ($('inputBuscador').value != '' ){
		if ($('busqueMas') != null){
			$('busqueMas').style.display = 'block';
			$('buscaBox').style.height = '200px';		
			}
	}
	if (document.getElementById('PAIS')) {
			mostrarSelect(paisPorDefecto);
	}
	myFavs('Prof', "Mi lista", "Eliminar de Mi lista");
	
	//cambiar_selects('TIPO', 'TIPO', 'SINPADRE');
	espera('ajax_selects', 'cambiar_selects(\\\'IDPROVINCIA\\\', \\\'provincias\\\', \\\'\\\');');
}			

function ForgotPassword(form) {
	var msg = '';
	
	if (form.elements['USER'].value == '') {
		msg += "Para que se le envíen sus datos de acceso, por favor introduzca su dirección de correo electrónico en la casilla 'email' y vuelva a pulsar sobre el enlace 'Olvidé mi contraseña'.\n\nMuchas gracias.\n"
		form.elements['USER'].style.border = '2px solid #C00';
	}
	else {
		if (!checkEmail(form.elements['USER'].value)) {
			msg += 'La dirección de correo electrónico no tiene el formato correcto: direccion@servidor.ext.\n';
			form.elements['USER'].style.border = '1px solid red';
		}
	}
	
	if (msg == '') {
		form.action = "OlvidoLoginSave.xsql";
		SubmitForm(form);
	}
	else
		alert(msg);
}


function modCheckWeb (elem) {
		if (elem.value != ''){
			if(elem.value.substring(0,7) != 'http://') {
				elem.value = 'http://' + elem.value;
			}
			if(!checkURL(elem))
				return false;
			else
				return true;
		}
		else
			return true;
}



function errorCheck(formu) {

	var msg = '';
	
	if (formu.elements['TITULO_ANUNCIO'] && formu.elements['TITULO_ANUNCIO'].value == '') {
		msg += '* El titulo es obligatorio.<br />';
	}

	if (formu.elements['CAT'] && formu.elements['CAT'].value == '') {
		msg += '* El nivel es obligatorio.<br />';
	}
	if (formu.elements['CPOSTAL'] && formu.elements['CPOSTAL'].value == '') {
		msg += '* El codigo postal es obligatorio.<br />';
	}

	if (formu.elements['TEXTO_01'] && formu.elements['TEXTO_01'].value == '') {
		if (formu.elements['OFFER'] == 'D') {
			msg += '* Descripción es obligatorio.<br />';
		}
	}
	

	if (formu.elements['IDPAIS'] && formu.elements['IDPAIS'].value == '') {
		msg += '* Pais es obligatorio.<br />';
	}
	if (formu.elements['IDPROVINCIA'] && formu.elements['IDPROVINCIA'].value == '') {
		msg += '* Provincia es obligatorio.<br />';
	}
	if (formu.elements['IDPOBLACION'] && formu.elements['IDPOBLACION'].value == '') {
		msg += '* Poblacion es obligatorio.<br />';
	}
	
	
	// if all fields are filled, check if they are filled correctly
	


	if (formu.elements['WEB'] && formu.elements['WEB'].value != 'http://') {
		if (formu.elements['WEB'].value != ''){
			if(formu.elements['WEB'].value.substring(0,7) != 'http://') {
				formu.elements['WEB'].value = 'http://' + formu.elements['WEB'].value;
			}
			if(!checkURL(formu.elements['WEB']))
				msg += '* El formato correcto de la página web es http://www.dominio.com<br />'
		}
	}
	
	if (formu.elements['WEB'].value == 'http://') {
		formu.elements['WEB'].value = '';
	}
	
	if (formu.elements['TELEFONO'] && formu.elements['TELEFONO'].value != '') {
		if (!checkPhone(formu.elements['TELEFONO'].value)) {
			msg += '* El número de teléfono no tiene el formato correcto.<br />';
		}
	}
	
	
	if (formu.elements['CPOSTAL'] && formu.elements['CPOSTAL'].value != '') {
		if (isNaN(formu.elements['CPOSTAL'].value)) {
			msg += '* El codigo postal no tiene el formato correcto.<br />';
		}
	}
	
	if (formu.elements['OFFER']) {
		if (formu.elements['OFFER'].value == 'O') {
			formu.elements['PRECIO'].value = formu.elements['PRECIO_OFERTA'].value;
		}
		else {
			formu.elements['PRECIO'].value = formu.elements['PRECIO_DEMANDA'].value;
		}
	}
	
	if (formu.elements['PRECIO']) {
		if (formu.elements['PRECIO'].value != '') {
			if ( reemplazaCaracteres(formu.elements['PRECIO'].value, ',', '.') < 0 || isNaN(reemplazaCaracteres(formu.elements['PRECIO'].value, ',', '.')) ) {
				msg += '* El valor del precio no es válido<br />';
			}
			else {
				if (formu.elements['PRECIO'].value != 0 && !cropNumber(reemplazaCaracteres(formu.elements['PRECIO'].value, ',', '.'), 2)) {
					msg += '* El valor del precio no es válido<br />';
				}
				else {
					if (getHostname() == 'www.profesor-particular.com') {
						formu.elements['PRECIO'].value = reemplazaCaracteres(cropNumber(reemplazaCaracteres(formu.elements['PRECIO'].value, ',', '.'), 2), '.', ',');
					}
					else
						formu.elements['PRECIO'].value = cropNumber(reemplazaCaracteres(formu.elements['PRECIO'].value, ',', '.'), 2);
				}
			}
		}
	}

	if (msg != '') {
		msg = 'Por favor, comprueba las siguientes incidencias:<br /><br />' + msg;
		displayMessage(msg);
		return true;
	}
	else
		return false;
}

function DebugMessages(formu) {
	var msg = '';

	msg += '-------------------------------------------\n';
	msg += '|     MESSAGES FOR DEBUGGING PURPOSES     |\n';
	msg += '-------------------------------------------\n';
	msg += '\n\n';

	if (formu.elements['IDUSUARIO'])
		msg += 'IDUSUARIO:       ' + formu.elements['IDUSUARIO'].value + '\n';
	if (formu.elements['IDPROYECTO'])
		msg += 'IDPROYECTO:      ' + 'Prof' + '\n';
	if (formu.elements['EMPRESA'])
		msg += 'EMPRESA:         ' + formu.elements['EMPRESA'].value + '\n';
	if (formu.elements['TITULO_ANUNCIO'])
		msg += 'TITULO_ANUNCIO:  ' + formu.elements['TITULO_ANUNCIO'].value + '\n';
	if (formu.elements['OFFER'])
		msg += 'OFFER:            ' + formu.elements['OFFER'].value + '\n';
	if (formu.elements['CAT'])
		msg += 'CAT:            ' + formu.elements['CAT'].value + '\n';
	if (formu.elements['DIRECCION'])
		msg += 'DIRECCION:       ' + formu.elements['DIRECCION'].value + '\n';
	if (formu.elements['IDPAIS'])
		msg += 'IDPAIS:    			 ' + formu.elements['IDPAIS'].value + '\n';
	if (formu.elements['IDPROVINCIA'])
		msg += 'IDPROVINCIA:     ' + formu.elements['IDPROVINCIA'].value + '\n';
	if (formu.elements['IDPOBLACION'])
		msg += 'IDPOBLACION:       ' + formu.elements['IDPOBLACION'].value + '\n';
	if (formu.elements['CPOSTAL'])
		msg += 'CPOSTAL:         ' + formu.elements['CPOSTAL'].value + '\n';
	if (formu.elements['TELEFONO'])
		msg += 'TELEFONO:        ' + formu.elements['TELEFONO'].value + '\n';
	if (formu.elements['FAX'])
		msg += 'FAX:             ' + formu.elements['FAX'].value + '\n';
	if (formu.elements['PRECIO'])
		msg += 'PRECIO:          ' + formu.elements['PRECIO'].value + '\n';
	if (formu.elements['ID_01'])
		msg += 'ID_01:           ' + formu.elements['ID_01'].value + '\n';
	if (formu.elements['ID_02'])
		msg += 'ID_02:           ' + formu.elements['ID_02'].value + '\n';
	if (formu.elements['ID_05'])
		msg += 'ID_05:           ' + formu.elements['ID_05'].value + '\n';
	if (formu.elements['TEXTO_05'])
		msg += 'TEXTO_05:        ' + formu.elements['TEXTO_05'].value + '\n';
	if (formu.elements['TEXTO_06'])
		msg += 'TEXTO_06:        ' + formu.elements['TEXTO_06'].value + '\n';
	if (formu.elements['TEXTO_07'])
		msg += 'TEXTO_07:        ' + formu.elements['TEXTO_07'].value + '\n';
	if (formu.elements['TEXTO_08'])
		msg += 'TEXTO_08:        ' + formu.elements['TEXTO_08'].value + '\n';
	if (formu.elements['TEXTO_01'])
		msg += 'TEXTO_01:        ' + formu.elements['TEXTO_01'].value + '\n';
	if (formu.elements['WEB'])
		msg += 'URL:             ' + formu.elements['WEB'].value + '\n';

		
	msg += '\n\n';
	msg += '-------------------------------------------\n';
	msg += '|     MESSAGES FOR DEBUGGING PURPOSES     |\n';
	msg += '-------------------------------------------\n';

	
	alert(msg);
}

function variar_localizacion_us(formu) {
	capa_usuario = document.getElementById('localizacion_del_usuario');
	
	if (capa_usuario.style.display == 'none') 
		return formu;		
	else {
		uspais = document.getElementById('loc_us_pais').innerHTML;
		usprovincia =document.getElementById('loc_us_provincia').innerHTML;
		uspoblacion = document.getElementById('loc_us_poblacion').innerHTML;
		
		formu.elements.IDPAIS.value = uspais;
		
		C = crear('rnd','option','IDPROVINCIA','AB');
		C.value = usprovincia;
		formu.elements.IDPROVINCIA.disabled = false;
		formu.elements.IDPROVINCIA.value = usprovincia;
		
		
		C=crear('rnd','option','IDPOBLACION','AB');
		C.value = uspoblacion;
		formu.elements.IDPOBLACION.disabled = false;
		formu.elements.IDPOBLACION.value = uspoblacion;

		return formu;
	}
}


function variar_localizacion_an(formu) {
	capa_anuncio = document.getElementById('localizacion_del_anuncio');
	
	if (capa_anuncio.style.display == 'none') 
		return formu;		
	else {
		anpais = document.getElementById('loc_an_pais').innerHTML;
		anprovincia =document.getElementById('loc_an_provincia').innerHTML;
		anpoblacion = document.getElementById('loc_an_poblacion').innerHTML;
		
		formu.elements.IDPAIS.value = anpais;
		
		C = crear('rnd','option','IDPROVINCIA','AB');
		C.value = anprovincia;
		formu.elements.IDPROVINCIA.disabled = false;
		formu.elements.IDPROVINCIA.value = anprovincia;
		
		
		C=crear('rnd','option','IDPOBLACION','AB');
		C.value = anpoblacion;
		formu.elements.IDPOBLACION.disabled = false;
		formu.elements.IDPOBLACION.value = anpoblacion;

		return formu;
	}
}

function GotoNextPage() {
	
	var msg = '';
	var i, j;
	var k, l;
	
	for (i=0; i<document.getElementsByName("TIPO").length; i++) {
		if  (document.getElementsByName("TIPO")[i].checked) {
			if (document.getElementsByName("TIPO")[i].value == 'O') {
				document.getElementById("displayOfertaYDemanda").style.display = 'block';
				
				document.getElementById("OFFER").value = 'O';							
				
				document.getElementById("oferta_idPrecio").style.display = 'block';
				document.getElementById("oferta_forPrecio").style.display = 'block';
				document.getElementById("oferta_inputDesc1_line1").style.display = 'block';
				document.getElementById("oferta_inputDesc1_line2").style.display = 'block';
				document.getElementById("oferta_inputDesc2_line1").style.display = 'block';
				document.getElementById("oferta_inputDesc2_line2").style.display = 'block';
				document.getElementById("oferta_ejPrecio").style.display = 'block';
				
				
				document.getElementById("demanda_idPrecio").style.display = 'none';
				document.getElementById("demanda_forPrecio").style.display = 'none';
				document.getElementById("demanda_inputDesc1_line1").style.display = 'none';
				document.getElementById("demanda_inputDesc1_line2").style.display = 'none';
				document.getElementById("demanda_inputDesc2_line1").style.display = 'none';
				document.getElementById("demanda_inputDesc2_line2").style.display = 'none';
			}
			else {
				document.getElementById("displayOfertaYDemanda").style.display = 'block';
				
				document.getElementById("OFFER").value = 'D';

				document.getElementById("oferta_idPrecio").style.display = 'none';
				document.getElementById("oferta_forPrecio").style.display = 'none';
				document.getElementById("oferta_inputDesc1_line1").style.display = 'none';
				document.getElementById("oferta_inputDesc1_line2").style.display = 'none';
				document.getElementById("oferta_inputDesc2_line1").style.display = 'none';
				document.getElementById("oferta_inputDesc2_line2").style.display = 'none';
				document.getElementById("oferta_ejPrecio").style.display = 'none';
				
				document.getElementById("demanda_idPrecio").style.display = 'block';
				document.getElementById("demanda_forPrecio").style.display = 'block';
				document.getElementById("demanda_inputDesc1_line1").style.display = 'block';
				document.getElementById("demanda_inputDesc1_line2").style.display = 'block';
				document.getElementById("demanda_inputDesc2_line1").style.display = 'block';
				document.getElementById("demanda_inputDesc2_line2").style.display = 'block';
			}
		}
	}
}










