



function submitAd()
{
	var f = document.adForm;
	var edit = f.id;
	
	
	if (!f.companyID || f.unique.value == 0)
	{
		f.name.value = trim(f.name.value);
		if (f.phone)
		{
			f.phone.value = trim(f.phone.value);
			f.mobile.value = trim(f.mobile.value);
		}
		if (f.cityName)
			f.cityName.value = trim(f.cityName.value);
		f.email.value = trim(f.email.value);
	}
	f.title.value = trim(f.title.value);
	f.text.value = trim(f.text.value);
	
	var catID = 0, typID = 0;

	if (!edit)
	{
		
		if (f.admin)
		{
			catID = selectedVal(f.category);
			if (f.type.length)
			{
				for (var i=0; i<f.type.length; i++)
				{
					if (f.type[i].checked)
					{
						typID = f.type[i].value;
						break;	
					}	
				}
			}
			else
				typID = f.type.value;	
		}
		else
		{
			catID = f.category.value;
			typID = f.type.value;	
		}
		if (catID <= 0)
		{
			alert("Necesita escoger una categoría.");
			f.category.focus();
			return false;	
		}
		if (categories[catID].mainID == 0)
		{
			alert("No puede escoger una categoría principal (la de letras mayúsculas).");
			f.category.focus();
			return false;
		}
		if (typID == 0)
		{
			alert("Necesita escoger un tipo.");
			return false;	
		}
	}
	
	
	if (catID == 515 && f.subCategory && f.subCategory.selectedIndex == 0)
	{
		alert("Necesita especificar el tipo de trabajo.");
		f.subCategory.focus();
		return false;
	}
	
	else if (f.knowledge)
	{
		var selectedKnowlede = false;
		for (var i=0; i<f.knowledge.options.length; i++)
		{
			if (f.knowledge.options[i].selected)
			{
				selectedKnowlede = true;
				break;
			}
		}
		if (!selectedKnowlede)
		{
			alert("Necesita seleccionar uno o más opciones de expertis.");
			f.knowledge.focus();
			return false;
		}
		if (f.age.value <= 0)
		{
			alert("Necesita especificar su edad.");
			f.age.focus();
			return false;
		}
		if (f.sex.selectedIndex == 0)
		{
			alert("Necesita especificar si es hombre o mujer.");
			f.sex.focus();
			return false;
		}
		if (f.education.selectedIndex == 0)
		{
			alert("Necesita especificar su nivel académico.");
			f.education.focus();
			return false;
		}
		if (f.experience.selectedIndex == 0)
		{
			alert("Necesita especificar cuantos años de experiencia tiene.");
			f.experience.focus();
			return false;
		}
	}
	
	else if (typID == 1 && (catID >= 20 && catID <= 40 || catID == 80))
	{
		if (f.year && f.year.value.length == 0)
		{
			alert("Necesita llenar el campo año.");
			f.year.focus();
			return false;
		}
	}
	
	else if (catID > 320 && catID <= 380)
	{
		if (!f.admin && catID != 370 && f.area && f.area.value.length == 0)
		{
			alert("Necesita llenar el campo colonia.");
			f.area.focus();
			return false;
		}
		else
			f.area.value = fixName(f.area.value);
			
		if (catID < 360 && f.rooms && f.rooms.value.length == 0)
		{
			alert("Necesita llenar el campo recamaras.");
			f.rooms.focus();
			return false;
		}
	}
	
	
	var title = f.title.value;
	
	if (title == "")
	{
		alert("Necesita especificar un título.");
		f.title.focus();
		return false;	
	}
	
	
	if (f.year && f.year.value.length > 0)
	{
		var year = f.year.value;
		var re = new RegExp(year + "|[-'´` ]" + year.substring(2,4));
		if (re.exec(title) != null)
		{
			alert("El año del vehículo no puede estar escrito en el título, se agrega automaticamente.");
			f.title.focus();
			return false;
		}
	}
	var titleLow = title.toLowerCase();
	var noTitleWords = "oferta,ofrezco,demanda,demando,vendo,vende,vender,venta,remato,urge,barato,bara,barata,baratisimo,baratisima,oportunidad,regalado,regalada,negociable".split(",");
	for (var i=0; i<noTitleWords.length; i++) 
	{
		var word = noTitleWords[i];
		var index = titleLow.indexOf(word);
		if (index != -1)
		{
			if ( (index == 0 || !isLowerCase(titleLow.charAt(index-1))) && 
				  (index + word.length >= titleLow.length || !isLowerCase(titleLow.charAt(index + word.length))) ) {
				alert("No puede usar la palabra '" + word + "' en el título.");
				f.title.focus();
				return false;
			}
		}
	}
	if (checkCapitals(title, 8, 0.5) == 1)
		f.title.value = fixName(title);
	else
		f.title.value = title.charAt(0).toUpperCase() + title.substring(1, title.length);
	
	
	var text = f.text.value;
	if (text == "")
	{
		alert("Necesita especificar una descripción.");
		f.text.focus();
		return false;
	}
	if (checkCapitals(text, 8, 0.5) != 0)
		f.text.value = fixCapitals(text, false);	
	else
		f.text.value = text.charAt(0).toUpperCase() + text.substring(1, text.length);
	
	
	if (!f.companyID) {
		
	
	if (!edit && f.password.value == "")
	{
		alert("Necesita especificar una contraseña.");
		f.password.focus();
		return false;	
	}
	
	
	if (!edit && f.admin)
	{
		var noCompany = true;
		for (var i = 0; i < f.company.length; i++)
		{
			if (f.company[i].checked)
			{
				noCompany = false;
				break;
			}
		}
		if (noCompany)
		{
			alert("Nececita especificar si es particular o negocio.");
			return false;	
		}
	}
	
	} if (!f.companyID || f.unique.value == 0) {
	
	
	if (f.name.value.length == 0)
	{
		alert("Necesita especificar su nombre.");
		f.name.focus();
		return false;	
	}
	f.name.value = fixName(f.name.value);
	
	
	if (f.email.value.length > 0 && !checkEmail(f.email.value))
	{
		alert("Ha ingresado un e-mail equivocado.");
		f.email.focus();
		return false;	
	}
	if (f.admin || f.companyID && f.unique.value == 0)
	{
		if (f.phone && f.phone.value.length == 0 && f.mobile.value.length == 0 && f.email.value.length == 0)
		{
			alert("Necesita especificar un teléfono o e-mail para poder ser contactado.");
			f.phone.focus();
			return false;	
		}	
	}
	else
	{
		if (f.email.value.length == 0)
		{
			alert("Necesita especificar su e-mail.");
			f.email.focus();
			return false;	
		}
		f.email.value = f.email.value.toLowerCase();
	}
	
	
	if (f.phone && f.phone.value.length > 0 && f.phone.value == f.mobile.value)
	{
		alert("Su celular no puede ser igual a su teléfono. Observe que no es necesario especificarlo.");
		f.phone.focus();
		return false;	
	}
	
	if (f.admin)
	{
		
		if (selectedVal(f.region) <= 0)
		{
			alert("Necesita escoger su estado.");
			f.region.focus();
			return false;	
		}
		
		
		if (f.cityID.selectedIndex == 0)
		{
			alert("Necesita escoger su municipio.");
			f.cityID.focus();
			return false;	
		}
		
		if (selectedVal(f.cityID) == (selectedVal(f.region) * 100 + 99)) 
		{
			if (f.cityName.value.length == 0 || f.cityName.value == "Nombre de su municipio")
			{
				alert("Necesita especificar su municipio.");
				f.cityName.focus();
				return false;
			}
			if (f.cityName.value.length > 2)
				f.cityName.value = fixName(f.cityName.value);
		}
	}
	
	}  
		
	
	var b = getObj("reviewButton");
	b.style.width = "320px";
	b.onclick = null;
	b.value = "Por favor espere, su anuncio se está enviando...";

	return true;
}

function checkInvoice(f)
{
	if (!f.invoice || !f.invoice.checked)
		return true;

	if (f.invoice_name.value.length == 0)
	{
		alert("Necesita especificar la razón social de la empresa.");
		f.invoice_name.focus();
		return false;
	}
	if (f.invoice_orgNo.value.length == 0)
	{
		alert("Necesita especificar el RFC de la empresa.");
		f.invoice_orgNo.focus();
		return false;
	}
	if (f.invoice_orgNo.value.length < 12)
	{
		alert("Ha ingresado un RFC equivocado.");
		f.invoice_orgNo.focus();
		return false;
	}
	if (f.invoice_street.value.length == 0)
	{
		alert("Necesita especificar la calle de la empresa.");
		f.invoice_street.focus();
		return false;
	}
	if (f.invoice_area.value.length == 0)
	{
		alert("Necesita especificar la colonia de la empresa.");
		f.invoice_area.focus();
		return false;
	}
	if (f.invoice_zip.value.length == 0)
	{
		alert("Necesita especificar el código postal de la empresa.");
		f.invoice_zip.focus();
		return false;
	}
	if (f.invoice_zip.value.length != 5)
	{
		alert("Ha ingresado un código postal equivocado.");
		f.invoice_zip.focus();
		return false;
	}
	if (selectedVal(f.invoice_region) <= 0)
	{
		alert("Necesita escoger el estado de la empresa.");
		f.invoice_region.focus();
		return false;
	}
	if (f.invoice_cityID.selectedIndex == 0)
	{
		alert("Necesita escoger el municipio de la empresa.");
		f.invoice_cityID.focus();
		return false;
	}
	if (selectedVal(f.invoice_cityID) == (selectedVal(f.invoice_region) * 100 + 99)) 
	{
		if (f.invoice_cityName.value.length == 0 || f.invoice_cityName.value == "Nombre de su municipio")
		{
			alert("Necesita especificar el municipio de la empresa.");
			f.invoice_cityName.focus();
			return false;
		}
		if (f.invoice_cityName.value.length > 2)
			f.invoice_cityName.value = fixName(f.invoice_cityName.value);
	}
	return true;
}

function fixCommas(s)
{
	s = s.replace(/ {1,},/g, ',');
	s = s.replace(/ {1,}[.]/g, '.');
	s = s.replace(/,\s*/g, ', ');
	return s.replace(/[.]\s*/g, '. ');
}

function submitTips()
{
	var f = document.tipsForm;
	if (f.name.value.length == 0)
	{
		alert("Necesita especificar su nombre.");
		f.name.focus();
		return;	
	}
	if (f.email.value.length == 0)
	{
		alert("Necesita especificar su e-mail.");
		f.email.focus();
		return;	
	}
	if (!checkEmail(f.email.value))
	{
		alert("Ha ingresado un e-mail equivocado.");
		f.email.focus();
		return;	
	}
	f.submit();
}



function showCity(region, city, name, defval, onch)
{
	if (!name) name = "city";
	var s = "<select name=" + name + "ID onChange='";
	if (region != 9)
		s += "showCityOther(this,\"" + name + "\");";
	if (onch)
		s += onch;
	s += "' style='width: 200px'><option value=-1>";
	if (defval)
		s += defval;
	if (region <= 0)
		s += "<option value=0>Seleccione su estado primero";
	else
	{
		var c = cities[region-1];
		for (var i=0; i<c.length; i++)
			s += "<option value=" + c[i].id + ((city == c[i].id) ? " selected" : "") + ">" + c[i].name;
		
		if (region != 9)
			s += "<option value=" + region + "99" + ((city == region*100+99) ? " selected" : "") + ">Otro";
	}
	s += "</select>";
	getObj("hidden_" + name + "ID").innerHTML = s;
	if (city != region*100+99)
		getObj("hidden_" + name + "Name").style.display = 'none'
}


function setDefaultCity(field)
{
	if (field.value == '')
		field.value = 'Nombre de su municipio';
	else if (field.value == 'Nombre de su municipio')
		field.value = '';
}


function showCityOther(sel, name)
{
	if (!name) name = "city";
	var obj = getObj("hidden_" + name + "Name");
	if (selectedVal(sel) > 0 && sel.selectedIndex + 1 == sel.options.length)
		obj.style.display = 'block';
	else
		obj.style.display = 'none';
}


function showAdOptions(make, model, year, km, cc, area, rooms, m2int, m2ext)
{
	var f = document.forms[0];
	var edit = f.id;
	var cat;
	var typ = 0;
	var hidden_opt = getObj("hidden_options");
	var disabled = (edit && !f.admin) ? "disabled" : "";
	
	if (f.category.options)
	{
		cat = selectedVal(f.category);
		if (f.type.length)
			for (var i=0; i<f.type.length; i++)
			{
				if (f.type[i].checked)
				{
					typ = f.type[i].value;
					break;	
				}	
			}
		else
			typ = f.type.value;
	}
	else
	{
		cat = f.category.value;
		typ = f.type.value;
	}
	if (typ == 0)
	{
		hidden_opt.innerHTML = "";
		hidden_opt.style.display = "none";
		return;
	}
	var s = null;
	
	
	
	
	if (cat == 515)
	{
		s = "<table cellpadding=0 cellspacing=0><tr>";
		if (typ == 5)
			s += "<td width=150 valign=top class=addHeading>Área de expertis *</td><td><select name=knowledge multiple size=7>";
		else
			s += "<td width=130 class=addHeading>Tipo de Empleo *</td><td><select name=subCategory><option value=-1>";

		
		s += "<option value=10>Administración<option value=20>Chofer - Mensajero<option value=30>Compras<option value=40>Contabilidad - Finanzas<option value=50>Derecho - Legal<option value=55>Diseñador Gráfico<option value=57>Edecan - Modelo<option value=60>Educación<option value=70>Estética - Moda<option value=80>Hotelería - Turismo - Gastronomía<option value=90>Informática - Sistemas - Técnico<option value=100>Ingeniería - Arquitectura<option value=110>Medicina - Salud<option value=120>Mercadotecnia - Promoción<option value=130>Producción - Manufactura<option value=140>Recursos Humanos<option value=150>Secretaria - Recepcionista<option value=160>Seguridad - Vigilancia<option value=190>Ventas<option value=200>Otro</select>";
		
		if (typ == 5)
		{
			
			s += "<br>(Seleccione multiples con CTRL)</td></tr>" +
				"<tr style='padding-top: 6px'><td class=addHeading>Sexo *</td><td><input name=sex id=man type=radio value=0><label for=man>Hombre</label>&nbsp;&nbsp;&nbsp;<input name=sex id=woman type=radio value=1><label for=woman>Mujer</label></td></tr></tr>" +
				"<tr style='padding-top: 6px'><td class=addHeading>Edad *</td><td><input size=4 maxlength=2 name=age onKeypress='return numbersOnly(event)'></td></tr>" +
				"<tr style='padding-top: 6px'><td class=addHeading>Nivel académico *</td><td><select name=education><option><option value=1>Secundaria<option value=2>Bachillerato<option value=3>Estudios universitarios sin terminar<option value=4>Técnico titulado<option value=5>Estudios universitarios - no titulado<option value=6>Estudios universitarios - titulado<option value=7>Diplomado<option value=8>Maestría<option value=9>Doctorado</td></tr>" +
				"<tr style='padding-top: 6px'><td class=addHeading>Años de experiencia *</td><td><select name=experience><option><option value=0>0<option value=1>1-2<option value=2>3-5<option value=3>6-10<option value=4>Más de 10</select></td></tr>" +
				"<tr style='padding-top: 6px'><td valign=top style='padding-top: 8px' class=addHeading>Currículum</td><td><input type=file style='width: 330px' name=cv><br>Acceptamos doc, pdf, rtf, xls, ppt, htm y txt.</td></tr>" +
				"</table>";
		}
		hidden_opt.innerHTML = s;
		hidden_opt.style.display = "block";
	}
	
	
	else if (cat >= 20 && cat <= 50 || cat == 80)
	{
		if (make == null) make = f.make ? selectedVal(f.make) : -1;
		if (model == null) model = f.model ? selectedVal(f.model) : -1;
		if (year == null) year = f.year ? f.year.value : -1;
		if (km == null) km = f.km ? extractNumbers(f.km.value) : -1;
		if (cat == 50)
		{
			if (!cc) cc = f.cc ? f.cc.value : -1;
			s = "<table cellpadding=4 cellspacing=0 style='margin-left: -4px; margin-top: -4px'><tr>";
			s += "<td " + disabled + " width=93 class=addHeading>Subcategoría</td><td><select " + disabled + " name=subCategory style='width: 150px'><option value=-1>";
	
			
			s += "<option value=210>Deportivo<option value=220>Cruiser/Chopper<option value=230>Cuatrimoto<option value=240>Cross/Enduro<option value=250>Scooter<option value=260>Go Kart<option value=270>Accesorio</select></td></tr>";
			
			s += "<tr><td " + disabled + " width=93 class=addHeading>Marca</td><td><select id=make_id name=make " + disabled + " style='width: 150px'><option value=-1><option value=-1>Cargando...</select></td></tr>";
			s += "<tr><td " + disabled + " style='padding-top: 6px' class=addHeading>Año</td><td><table cellpadding=0 cellspacing=0 style='margin-top: 2px'><tr>";
			s += "<td " + disabled + " width=80><input maxlength=4 name=year " + disabled + " value='" + (year > 0 ? year : "") + "' style='width: 60px' onKeyPress='return numbersOnly(event)' onChange='fixYear(this)'></td>";
			s += "<td " + disabled + " class=addHeading style='padding-right: 10px'>CC</td><td width=80><input maxlength=4 name=cc " + disabled + " value='" + (cc > 0 ? cc : "") + "' style='width: 60px' onKeyPress='return numbersOnly(event)'></td>";
			s += "<td class=addHeading style='padding-right: 10px'>Km</td><td><input name=km value='" + (km > 0 ? formatNumbers(km) : "") + "' style='width: 60px' onKeyPress='return numbersOnly(event)' onChange='formatField(this)'></td>";
			s += "</tr></table>";
			hidden_opt.innerHTML = s;
			hidden_opt.style.display = "block";
			setMakes(make, model);
		}
		else
		{
			s = "<table cellpadding=4 cellspacing=0 style='margin-left: -4px; margin-top: -4px'><tr>";
			s += "<td " + disabled + " width=93 class=addHeading>Marca</td><td width=600><select id=make_id name=make " + disabled + " style='width: 150px' onChange='setModels()'><option value=-1><option value=-1>Cargando...</select>";
			if (!edit || f.admin)
				s += "&nbsp;Si no encuentra su marca/modelo talvez está en la";
			s += "</td></tr>";
			s += "<tr><td " + disabled + " class=addHeading>Modelo</td><td><select id=model_id name=model style='width: 150px'><option value=-1><option value=-1>-Seleccione marca-</select>";
			if (!edit || f.admin)
				s += "&nbsp;categoría <span id=catLink></span>.";
			s += "</td></tr>";
			s += "<tr><td width=92 style='padding-top: 6px' class=addHeading>Año *</td><td><table cellpadding=0 cellspacing=0 style='margin-top: 2px'><tr>";
			s += "<td width=80><input maxlength=4 name=year " + disabled + " value='" + (year > 0 ? year : "") + "' style='width: 60px' onKeyPress='return numbersOnly(event)' onChange='fixYear(this)'></td>";
			s += "<td class=addHeading style='padding-right: 10px'>Km</td><td><input name=km value='" + (km > 0 ? formatNumbers(km) : "") + "' style='width: 60px' onKeyPress='return numbersOnly(event)' onChange='formatField(this)'></td>";
			s += "</tr></table>";
			hidden_opt.innerHTML = s;
			hidden_opt.style.display = "block";
			changeCategory(cat, make, model);
		}
	}
	
	
	else if (cat >= 325 && cat <= 380)
	{
		if (!area) area = f.area ? f.area.value : "";
		if (!rooms) rooms = f.rooms ? f.rooms.value : -1;
		if (!m2int) m2int = f.m2int ? extractNumbers(f.m2int.value) : -1;
		if (!m2ext) m2ext = f.m2ext ? extractNumbers(f.m2ext.value) : -1;
		s = "<table cellpadding=4 cellspacing=0 style='margin-left: -4px; margin-top: -4px'><tr>";
		s += "<td width=92 class=addHeading>Colonia" + (cat != 370 ? " *" : "" )+ "</td><td><input name=area value='" + area + "' style='width: 250px'></td></tr>";
		if (cat == 370)
			s += "<tr><td " + disabled + " class=addHeading>m² *</td><td><input name=m2ext " + disabled + " value='" + (m2ext > 0 ? formatNumbers(m2ext) : "") + "' style='width: 60px' onChange='formatField(this)'></td>";
		else
		{
			s += "<tr><td " + disabled + " style='padding-top: 6px' class=addHeading>";
			if (cat == 360) s += "Cuartos";
			else if (cat == 380) s += "m² const.";
			else s += "Recamaras *";
			s += "</td><td><table cellpadding=0 cellspacing=0 style='margin-top: 2px'><tr><td " + disabled + " width=80>";
			if (cat != 380)
			{
				s += "<input name=rooms " + disabled + " value='" + (rooms > 0 ? rooms : "") + "' style='width: 60px' onKeyPress='return numbersOnly(event)'></td>";
				s += "<td " + disabled + " class=addHeading style='padding-right: 10px'>m² const.</td><td width=80>";
			}
			s += "<input name=m2int " + disabled + " value='" + (m2int > 0 ? formatNumbers(m2int) : "") + "' style='width: 60px' onKeyPress='return numbersOnly(event)' onChange='formatField(this)'></td>";
			if (cat != 360)
				s += "<td " + disabled + " class=addHeading style='padding-right: 10px'>m² terreno</td><td><input name=m2ext " + disabled + " value='" + (m2ext > 0 ? formatNumbers(m2ext) : "") + "' style='width: 60px' onKeyPress='return numbersOnly(event)' onChange='formatField(this)'></td>";
		}
		s += "</tr></table>";
		hidden_opt.innerHTML = s;
		hidden_opt.style.display = "block";
	}
	else
	{
		hidden_opt.innerHTML = "";
		hidden_opt.style.display = "none";
	}
}



function setCVOptions(age, sex, experience, education, knowledge)
{
	var f = document.adForm;
	f.age.value = age;
	f.sex[sex].checked = true;
	f.sex.selectedIndex = sex + 1;
	f.experience.selectedIndex = experience + 1;
	f.education.selectedIndex = education;
	var know_opt = f.knowledge.options;
	for (var i=knowledge.length-1; i>=0; i--)
	{
		for (var j=0; j<know_opt.length; j++)
		{
			if (know_opt[j].value == knowledge[i])
				know_opt[j].selected = true;	
		}
	}
}


function setMakes(makeID, modelID)
{
	var xmlhttp = getXMLHttpRequestObject();
	var f = document.adForm;
	if (makeID == null) makeID = (f.make) ? selectedVal(f.make) : -1;
	if (modelID == null) modelID = (f.model) ? selectedVal(f.model) : -1;
	var catID = (f.category.options) ? selectedVal(f.category) : f.category.value;
	var sel = getObj("make_id");
	sel.selectedIndex = 0;
	sel.length = 2;
	sel[1].value = -1;
	sel[1].text = "Cargando...";
	xmlhttp.onreadystatechange = function() {
		if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
		{
			var array = xmlhttp.responseText.split("|");
			if (array.length < 2) return;
			sel.length = array.length/2+1;
			for (var i=0,j=1; i<array.length; i+=2,j++)
			{
				sel[j].value = array[i];
				if (makeID == array[i])
					sel.selectedIndex = j;
				sel[j].text = array[i+1];
			}
			setModels(modelID);
		}
	};
	xmlhttp.open("GET", "/getMakes.jsp?all=1&cat=" + catID, true);
	xmlhttp.send(null);
}

function setModels(modelID)
{
	var sel = getObj("model_id");
	if (!sel) return;
	var f = document.adForm;
	var makeID = selectedVal(f.make);
	if (modelID == null) modelID = (f.model) ? selectedVal(f.model) : -1;
	var catID = (f.category.options) ? selectedVal(f.category) : f.category.value;
	sel.selectedIndex = 0;
	sel.length = 2;
	sel[1].value = -1;
	if (makeID < 0)
		sel[1].text = "-Seleccione marca-";
	else
	{
		sel[1].text = "Cargando...";
		var xmlhttp = getXMLHttpRequestObject();
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
			{
				var array = xmlhttp.responseText.split("|");
				if (array.length < 2) return;
				sel.length = array.length/2+1;
				for (var i=0,j=1; i<array.length; i+=2,j++)
				{
					sel[j].value = array[i];
					if (modelID == array[i])
						sel.selectedIndex = j;
					sel[j].text = array[i+1];
				}
			}
		};
		xmlhttp.open("GET", "/getModels.jsp?all=1&make=" + makeID + "&cat=" + catID, true);
		xmlhttp.send(null);
	}
}



function containsValue(array, val)
{
	for (var i in array)
	{
		if (array[i] == val)
			return true;
	}
	return false;
}


function setSubCategory(ids)
{
	var sub = document.adForm.subCategory;
	for (var i=0; i<sub.options.length; i++)
	{
		if (containsValue(ids, sub.options[i].value))
			sub.options[i].selected = true;
	}
}



function fixYear(field)
{
	var year = parseInt(field.value);
	if (year == 0 && field.value.charAt(0) == '0')
		year = parseInt(field.value.substring(1, field.value.length));
	if (year < 100)
	{
		if (year < 10) year += 2000;
		else year += 1900;
		field.value = year;
	}
}

function showEmailBox(attachment)
{
	var obj = getObj("emailBox");
	
	if (obj.innerHTML == "")
	{
		var s =
			"<table cellpadding=0 cellspacing=0 width=423 style='margin-top: 10px'>" +
				"<tr><td colspan=2 bgcolor=#ffffff width=420 height=3></td></tr>" +
				"<tr>" +
					"<td colspan=2 width=400 style='padding-left: 20px; padding-top: 14px' valign=top bgcolor=#ffffff>" +
						"<table><tr><td><img src='/img/icon_mail.jpg'></td><td class=textb2l>Contactar " + name + "</td></tr></table>" +
						"<img src='/img/pxl.gif' width=1 height=10><br>" +
						"<span class=textr>Sólo se permiten respuestas al anuncio.<br>Enviar spam o publicidad está prohibido y será perseguido.</span><br>" +
						"<img src='/img/pxl.gif' width=1 height=10><br>" +
						"<form name=emailForm method=post enctype='multipart/form-data' action='/ad?choice=contact'>" +
						"<input type=hidden name=id value=" + id + ">" +
						"<table border=0 cellpadding=4 cellspacing=0>" +
							"<tr><td class=textb><b>Su nombre</b></td><td><input name=name class=greybox style='width: 240px'></td></tr>" +
							"<tr><td class=textb><b>Su e-mail</b></td><td><input name=email onKeyPress='return emailInput(event, null)' class=greybox style='text-transform: lowercase; width: 240px'></td></tr>" +
							"<tr><td class=textb><b>Asunto</b></td><td><input name=subject class=greybox style='width: 280px'></td></tr>" + ((attachment) ?
							"<tr><td class=textb><b>Archivo</b></td><td><input name=attachment type=file class=greybox style='width: 280px'></td></tr>" : "") +
							"<tr><td class=textb valign=top><b>Texto</b></td><td><textarea name=text class=greybox style='width: 280px; height: 120px'></textarea></td></tr>" +
							"<tr><td colspan=2 align=right><input type=button style='width: 70px' onClick='sendEmail(); return false' value='Enviar'></td></tr>" +
							"</td></tr></table>" +
						"</form>" +
					"</td>" +
					"<td rowspan=2 width=3 bgcolor=#b6bcc0></td>" +
				"</tr>" +
				"<tr>" +
					"<td bgcolor=#ffffff valign=bottom width=28 height=27><img width=28 height=27 src='/img/fold_lb.gif'></img></td>" +
					"<td bgcolor=#ffffff align=right valign=bottom width=382 style='padding-bottom: 6px; padding-right: 10px; border-bottom: 3px solid #b6bcc0'>&nbsp;" +
					"</td>" +
				"</tr>" +
			"</table>";
	
		obj.innerHTML = s;
		var f = document.emailForm;
		f.name.value = userName;
		f.email.value = userEmail;
		f.subject.value = "Re: " + title;
	}
	
	
	location.href = "#contact";
	var f = document.emailForm;
	
	if (f.name.value == "")
		f.name.focus();
	else if (f.email.value == "")
		f.email.focus();
	else if (f.subject.value == "")
		f.subject.focus();
	else if (f.text.value == "")
		f.text.focus();
}

function sendEmail()
{
	var f = document.emailForm;

	if (f.name.value == "")
	{
		alert("Necesita especificar su nombre.");
		f.name.focus();
		return;	
	}
	if (f.email.value == "")
	{
		alert("Necesita especificar su e-mail.");
		f.email.focus();
		return;
	}
	if (!checkEmail(f.email.value))
	{
		alert("Ha ingresado un e-mail equivocado.");
		f.email.focus();
		return;	
	}
	else if (f.subject.value == "")
	{
		alert("Necesita llenar el campo asunto.");
		f.subject.focus();
		return;
	}
	if (f.text.value == "")
	{
		alert("Necesita llenar el campo texto.");
		f.text.focus();
		return;
	}
	f.submit();
}


function printAd()
{
	getObj("print_frame").src = "/print.jsp?id=" + id + "&selectedPic=" + selectedPic;
}

function printAdd(title, price, tel, code)
{
	getObj("print_frame").src = "/print.jsp?type=add&menu=add&title=" + title + "&price=" + price + "&tel=" + tel + "&code=" + code;
}

function printIt(iframe)
{
	if (iframe.src.indexOf("print") != -1)
	{
		iframe.contentWindow.focus();
		iframe.contentWindow.print();
	}
}


function doFavorite(id)
{
	if (isFavorite)
	{
		removeFavorite(id);
		document.images.favorite.src = '/img/icon_fav_add.gif';
		getObj("favorite_link").className = "textgm";
		getObj("favorite_text").innerHTML = "Guardar anuncio en favoritos";
	}
	else
	{
		addFavorite(id);
		document.images.favorite.src = '/img/icon_fav_del.gif';
		getObj("favorite_link").className = "textr2m";
		getObj("favorite_text").innerHTML = "Borrar anuncio de favoritos";
	}
	isFavorite = !isFavorite;	
}


function addFavorite(id)
{
	var cookie = getCookie("favorites");
	
	if (cookie == null)
		cookie = "." + id + ".";
				
	else if (cookie.indexOf("." + id + ".") == -1)
		cookie += id + ".";
		
	else
		return; // already exists
		
	setCookie("favorites", cookie, 63072000);
}


function removeFavorite(id)
{
	var cookie = getCookie("favorites");
	if (cookie != null)
	{
		var begin = cookie.indexOf("." + id + ".");
		
		if (begin != -1)
		{
			var len = (""+id).length;
			var end = cookie.indexOf(".", begin + len + 2);
			
			if (end == -1)
			{
				if (begin == 0)
					delCookie("favorites");
				else
				{
					cookie = cookie.substring(0, begin + 1);
					setCookie("favorites", cookie, 63072000);
				}
			}
			else
			{
				if (begin == 0)
					cookie = cookie.substring(begin + len + 1, cookie.length);
				else
					cookie = cookie.substring(0, begin) +
								cookie.substring(begin + len + 1, cookie.length);
				setCookie("favorites", cookie, 63072000);
			}	
		}
	}
}

function showTypes(typID, disabled)
{
	var f = document.adForm;
	var catID = selectedVal(f.category);
	var catTypes = null;
	if (catID > 0)
		catTypes = categories[catID].types;
	if (catTypes == null)
		catTypes = defaultTypes;
	var obj = getObj("hidden_types");
	var s = "<table cellpadding=0 cellspacing=0><tr>";
	
	
	if (!typID && f.type)
	{
		for (var i=0; i<f.type.length; i++)
		{
			if (f.type[i].checked)
			{
				typID = f.type[i].value;
				break;
			}
		}
	}
	
	
	for (var i = 0; i < catTypes.length; i++)
	{
		var id = catTypes[i];
		var t = types[id];
		
		if (catID == 505)
		{
			if (i > 0 && i % 3 == 0)
				s += "</tr><tr>";
			s += "<td style='padding-right: 16px'>";
		}
		else
			s += "<td width=100>"
		s += "<input " + disabled + " type=radio " + ((id == typID || catTypes.length == 1) ? "checked " : "") + "onClick='showAdOptions()' name=type id=type" + i + " value=" + id + "><label style='white-space: nowrap' " + disabled + " for=type" + i + ">" + t.name + "</label></td>";
	}
	s += "</tr></table>";
	obj.innerHTML = s;
}


function hasUpsell(f)
{
	return f.upsell_print && f.upsell_print.checked ||
		f.upsell_print_photo && f.upsell_print_photo.checked ||
		f.upsell_print_frontpage && f.upsell_print_frontpage.checked ||
		f.upsell_top && f.upsell_top.checked ||
		f.upsell_print_photo_top && f.upsell_print_photo_top.checked;
}

function showInvoice(f, checked, city, verify)
{
	if (checked)
	{
		if (verify && !hasUpsell(f))
		{
			alert("Tiene que seleccionar una opción de mayor impacto primero.\nNo le podemos facturar 0 pesos.");
			f.invoice.checked = false;
			return;
		}
		show("hidden_invoice");
		showCity(f.invoice_region.value, city ? city : -1, 'invoice_city');
	}
	else
	{
		hide("hidden_invoice");
	}
}

function selectUpsell(obj, verifyInvoice)
{
	var f = obj.form;
	if (!obj.checked) 
	{
		if (verifyInvoice && !hasUpsell(f))
		{
			getObj("invoice").checked = false;
			hide("hidden_invoice");
		}
		return;
	}
	
	if (f.upsell_print && obj.name != "upsell_print")
		f.upsell_print.checked = false;
		
	if (f.upsell_print_photo && obj.name != "upsell_print_photo")
		f.upsell_print_photo.checked = false;
		
	if (f.upsell_print_frontpage && obj.name != "upsell_print_frontpage")
		f.upsell_print_frontpage.checked = false;

	if (f.upsell_top && obj.name != "upsell_top")
		f.upsell_top.checked = false;

	if (f.upsell_print_top && obj.name != "upsell_print_top")
		f.upsell_print_top.checked = false;

	if (f.upsell_print_photo_top && obj.name != "upsell_print_photo_top")
		f.upsell_print_photo_top.checked = false;
}

function showMap(lat, lng)
{
	window.open('/showMap.jsp?lat=' + lat + '&lng=' + lng,null,'width=800,height=500,status=no,toolbar=no,menubar=no,location=no,resizable=yes');	
}

function changeCategory(cat, make, model)
{
	document.adForm.category.value = cat;
	setMakes(make, model);
	var o = getObj("catName");
	var o2 = getObj("catLink");
	var link = "<a class=normal href='javascript:' onClick='changeCategory(";
	var carLink = link + "20)'>Autos</a>";
	var picLink = link + "30)'>Pickups</a>";
	var suvLink = link + "40)'>SUVs, Jeeps y Vans</a>";
	var trucLink = link + "80)'>Camiones</a>";
	var s;

	if (cat == 20)
	{
		s = picLink + ", " + suvLink + " o " + trucLink;
		if (o) o.innerHTML = "Autos";
	}
	else if (cat == 30)	
	{
		s = carLink + ", " + suvLink + " o " + trucLink;
		if (o) o.innerHTML = "Pickups";
	}
	else if (cat == 40)	
	{
		s = carLink + ", " + picLink + " o " + trucLink;
		if (o) o.innerHTML = "SUVs, Jeeps y Vans";
	}
	else if (cat == 80)	
	{
		s = carLink + ", " + picLink + " o " + suvLink;
		if (o) o.innerHTML = "Camiones";
	}
	if (o2) o2.innerHTML = s;
}
