function createNewOption(v, t)
{
   var nuevaOpcion=document.createElement("option"); 
   nuevaOpcion.value = v; 
   nuevaOpcion.innerHTML = t;
   
   return nuevaOpcion;
}

function _cargaComboSubcat(cat, ndestino)
{
	var selectDestino=document.getElementById('categoria' + ndestino);
   
    selectDestino.length=1;
    selectDestino.disabled = false;

   	if (cat != '' && typeof(subcats[cat]) != "undefined" && subcats[cat].length > 0)
   	{	   
	   for (i = 0; i < subcats[cat].length; i++)
	   {
		   selectDestino.appendChild( createNewOption(subcats[cat][i].id, subcats[cat][i].text) ); 
	   }
	   document.getElementById('bloque_' + ndestino).style.display="";
	}
	else
	{
	   document.getElementById('bloque_' + ndestino).style.display="none";
    }

	var base = ndestino - (ndestino % 10);

	for (j = (ndestino % 10) + 1; j <= 4; j++)
	{
		document.getElementById('categoria'+(base + j)).length=1;
		document.getElementById('bloque_'+(base + j)).style.display="none";
	}
	
	if ( base == 0 && (typeof (nuw) == "undefined") )
	{
		var ultimo = (cat != '' && typeof(subcats[cat]) != "undefined" && subcats[cat].length > 0) ? ndestino: ndestino-1;		
		var extra = (135 * (4 - ultimo)) / ultimo;

		for (j = 1; j <= ultimo; j++)
		{
			document.getElementById('categoria'+ j).style.width = Math.min(135 + extra, 135*2) + 'px';
		}		
	}
}

function cargaComboSubcat(cat, ndestino)
{
	_cargaComboSubcat(cat, ndestino);

	updateSubcat( cat, ndestino, true );
}

function cargarComboMarcas(categoria, categoriaPadre, sufijo)
{
	var indice;
	if ( typeof(marcas[categoria.id]) != "undefined" )
	{
		indice = categoria.id;
	}
	else if ( categoriaPadre != null)
	{
		indice = categoriaPadre.id;
		
		if ( typeof(marcas[categoriaPadre.id]) != "undefined" )
		{
			return;
		}
	}
	else
	{
		var cmarcas = document.getElementById('marca'+sufijo);
		cmarcas.length = 1;	
		
		var tmarca = document.getElementById('tmarca'+sufijo);
		tmarca.style.display = 'none';
		return;
	}
//	window.alert('marcas2');	
	
	var cmarcas = document.getElementById('marca'+sufijo);
	cmarcas.length = 1;
	
	if ( typeof(marcas[indice]) != "undefined" )
	{	
		cmarcas.style.display = '';

		var tmarca = document.getElementById('tmarca'+sufijo);
		tmarca.style.display = 'none';	

		for (i = 0; i < marcas[indice].length; i++)
	   	{
			cmarcas.appendChild( createNewOption( marcas[indice][i].idMarca, marcas[indice][i].nombre) ); 
	   	}
		cmarcas.appendChild( createNewOption(-1, "&laquo; Otra marca &raquo;") ); 		
		mostrarTextoMarca( cmarcas, sufijo );			
	}
	else
	{
		cmarcas.style.display = 'none';

		var tmarca = document.getElementById('tmarca'+sufijo);
		tmarca.style.display = 'none';

		var modelo = document.getElementById('modelo'+sufijo);
		modelo.value = '';
		modelo.style.display = 'none';	
	}
}


function mostrarTextoMarca( cmarcas, sufijo )
{
	var h_marca = document.getElementById('hint_marca');
	var tmarca = document.getElementById('tmarca'+sufijo);
	var h_tmarca = document.getElementById('hint_tmarca');
	
	if ( cmarcas.selectedIndex == cmarcas.length-1 )
	{
		h_marca.style.display = "none";
		tmarca.style.display = "";
		h_tmarca.style.display = "";
	}
	else
	{
		h_marca.style.display = "";
		tmarca.style.display = "none";
		tmarca.value = "";		
		h_tmarca.style.display = "none";
	}
}

function buscarCategoria(cat)
{
	for (var idPadre in subcats)
	{	
		for ( i = 0; i < subcats[idPadre].length; i++)
		{
			if (subcats[idPadre][i].id == cat)
			{
				return subcats[idPadre][i];
			}
		}
	}
	
	return null;
}

function updateExt(categoria, sufijo)
{	
	var campos_extras = false;
		
	var cmarcas = document.getElementById('marca'+sufijo);
	if ( cmarcas.length > 1 || categoria.marca > 0 )
	{
		//window.alert( document.getElementById('marca').length );
		var dest = document.getElementById("f_marca"+sufijo);
		dest.style.display="";
		campos_extras = true;

		if ( cmarcas.length <= 1 )
		{
			cmarcas.style.display = 'none';
		}

		mostrarTextoMarca( cmarcas, sufijo );
		document.getElementById('modelo'+sufijo).style.display = '';
		
		// Si hay marca no hay titulo
		var dest = document.getElementById("f_titulo");
		dest.style.display="none";
	}
	else
	{
		// Si NO hay marca hay titulo
		var dest = document.getElementById("f_titulo");		
		dest.style.display="";		
	}
	
	var om = document.getElementById('oblig_modelo');

	if ( categoria.modelo == 2 )
	{
		om.style.display = '';
	}
	else
	{
		om.style.display = 'none';				
	}

	if ( categoria.anio )
	{
		var dest = document.getElementById("f_anio"+sufijo);
		dest.style.display="";				
		campos_extras = true;		
	}

	if ( categoria.km )
	{
		var dest = document.getElementById("f_km"+sufijo);
		dest.style.display="";				
		campos_extras = true;		
	}

	if ( categoria.combustible )
	{
		var dest = document.getElementById("f_comb"+sufijo);
		dest.style.display="";				
		campos_extras = true;		
	}

/*	if ( subcats[cat_sel][subcat].precio )
	{
		var dest = document.getElementById("f_precio");
		dest.style.display="";				
	}*/
	if ( categoria.superficie )
	{
		var dest = document.getElementById("f_super");
		dest.style.display="";				
		campos_extras = true;		
	}
	if ( categoria.habitaciones )
	{
		var dest = document.getElementById("f_hab");
		dest.style.display="";				
		campos_extras = true;
	}
	if ( categoria.areacp )
	{
		var dest = document.getElementById("f_area_cp");
		dest.style.display="";
		campos_extras = true;
	}
	if ( categoria.terreno )
	{
		var dest = document.getElementById("f_terr");
		dest.style.display="";				
		campos_extras = true;		
	}
	if ( categoria.salario )
	{
		document.getElementById("lprecio").innerHTML = "Salario:";	
/*		var dest = document.getElementById("f_salario");
		dest.style.display="";*/
	}
	else
	{
		document.getElementById("lprecio").innerHTML = "Precio:";
	}
	
	if ( campos_extras )
	{
		document.getElementById("f_campos_extra").style.display = "";
	}
}

function updateExt_basic(categoria)
{
	if ( categoria.anio )
	{
		var dest = document.getElementById("f_anio");
		dest.style.display="";				
	}
	if ( categoria.km )
	{
		var dest = document.getElementById("f_km");
		dest.style.display="";				
	}
	if ( categoria.precio )
	{
		var dest = document.getElementById("f_precio");
		dest.style.display="";				
	}
	if ( categoria.superficie )
	{
		var dest = document.getElementById("f_super");
		dest.style.display="";				
	}
	if ( categoria.habitaciones )
	{
		var dest = document.getElementById("f_hab");
		dest.style.display="";				
	}
	if ( categoria.terreno )
	{
		var dest = document.getElementById("f_terr");
		dest.style.display="";				
	}
}
	
function updateSubcat( cat, ndestino, cargarMarcas )
{
	var sufijo = '';
	if ( ndestino > 10)
	{
		sufijo = (ndestino - (ndestino % 10));
	}
//	window.alert('NDESTINO: '+ndestino+', CAT: '+cat);

	var destino = 'categoria'+ndestino;		
	var divos = new Array( "f_campos_extra", "f_marca"+sufijo, "f_anio"+sufijo, "f_km"+sufijo,"f_comb"+sufijo /*,"f_precio"*/ ,"f_area_cp","f_super","f_terr","f_hab"/*,"f_salario"*/);

	for (j = 0; j < divos.length; j++)
	{		
		var dest = document.getElementById(divos[j]);
		dest.style.display="none";				
	}

	if ( cat != -1 && cat != '')
	{
		var categoria = buscarCategoria(cat);		
		//window.alert('CAT: '+cat+', DESTINO: '+destino+', NOMBRE CAT: '+categoria.text);

		var categoriaPadre = null;

		if ( categoria.idPadre != -1 )
		{
			categoriaPadre = buscarCategoria(categoria.idPadre);
		}

		if ( cargarMarcas )
		{
			cargarComboMarcas( categoria, categoriaPadre, sufijo );
		}

//		window.alert(categoria.text);
		updateExt( categoria, sufijo );

		if ( destino.length > 0 )
		{
			var hint = document.getElementById('hint_'+destino);
			var oblig = document.getElementById('oblig_'+destino);
			
			if ( hint != null && oblig != null )
			{
				if ( categoria.eshoja == 1  )
				{		
					if (cat != '' && typeof(subcats[cat]) != "undefined" && subcats[cat].length > 0)
					{
	//					hint.innerHTML = "Seleccionar si procede (opcional)";
						hint.style.display = "";
						oblig.style.display = "none";
					}
					else
					{
//						hint.innerHTML = "";
						hint.style.display = "none";
						oblig.style.display = "";					
					}
				}
				else
				{			
//					hint.innerHTML = "";				
					hint.style.display = "none";
					oblig.style.display = "";				
				}
			}
		}
	}
	else if ( (ndestino % 10) > 2 )
	{
		var destino2 = 'categoria'+(ndestino-2);

		var obj = document.getElementById(destino2);
		updateSubcat( obj.options[obj.selectedIndex].value, ndestino-1, true);
	}
}

function updateSubcat_basic2(cat_subcat, ndestino)
{
	_cargaComboSubcat(cat_subcat, ndestino);
	updateSubcat_basic(cat_subcat, ndestino);
}

function updateSubcat_basic(cat_subcat, ndestino)
{
	var divos = new Array( "f_anio", "f_km", "f_precio","f_super","f_terr","f_hab" );
	var sels = new Array( "am_m", "am_x", "km_m", "km_x", "nd_m", "nd_x", "sf_m", "sf_x", "tr_m", "tr_x" );

	for (j = 0; j < divos.length; j++)
	{		
		var dest = document.getElementById(divos[j]);
		dest.style.display="none";
	}

	for (i = 0; i < sels.length; i++)
	{		
		var dest = document.getElementById( sels[i] );
		dest.selectedIndex = 0;
	}

	// Show asociated controls
	if ( cat_subcat == '' && ndestino != -1 )
	{
		tmp = document.getElementById('categoria'+ (ndestino-2)).value;
	}
	else
	{
		tmp = cat_subcat;
	}
	
	var categoria = buscarCategoria(tmp);
	updateExt_basic( categoria );
}

function updateSubcatBody()
{
	var s1 = document.getElementById("categoria1");
	var s2 = document.getElementById("categoria2");
	var s3 = document.getElementById("categoria3");
	var s4 = document.getElementById("categoria4");
	
	//window.alert('s1:' + s1.selectedIndex + ', s2:' + s2.selectedIndex + ', s3:' + s3.selectedIndex + ', s4:' + s4.selectedIndex );

	if ( s1.selectedIndex != 0 )
	{
		updateSubcat(s1.options[s1.selectedIndex].value, 2, false);	
		
		if ( s2.selectedIndex != 0 )
		{		
			updateSubcat(s2.options[s2.selectedIndex].value, 3, false);
	
			if ( s3.selectedIndex != 0 )
			{		
				updateSubcat(s3.options[s3.selectedIndex].value, 4, false);
				
				if ( s4.selectedIndex != 0 )
				{
					updateSubcat(s4.options[s4.selectedIndex].value, "", false);
				}
			}
		}
	}
}

function updateSubcatBody_basic()
{
	var s2 = document.getElementById("sb");
	updateSubcat_basic(s2.selectedIndex-1, -1);
}

function updateLabelOwner()
{
	var elem = document.f_publicar.esParticular;
	if (elem[0].checked)
	{
		document.getElementById("lnombre").innerHTML = "Nombre particular:";
	}
	else
	{
		document.getElementById("lnombre").innerHTML = "Nombre empresa:";	
	}
}

/*function eraseImage( n )
{
	switch(n)
	{
	  case 0: document.f_publicar.urlImagen0.value="" ; break;
	  case 1: document.f_publicar.urlImagen1.value="" ; break;
	  case 2: document.f_publicar.urlImagen2.value="" ; break;
	  case 3: document.f_publicar.urlImagen3.value="" ; break;
	  case 4: document.f_publicar.urlImagen4.value="" ; break;
	  case 5: document.f_publicar.urlImagen5.value="" ; break;
	  case 6: document.f_publicar.urlImagen6.value="" ; break;
	  case 7: document.f_publicar.urlImagen7.value="" ; break;	  
	}

  if ( document.f_publicar.action.indexOf('?') == -1)
  {
    document.f_publicar.action = document.f_publicar.action + "?ei=";
  }
  else
  {
    document.f_publicar.action = document.f_publicar.action + "&ei=";	  
  }
  document.f_publicar.submit() ;
}*/

function showId(control, mostrar)
{
	var obj = document.getElementById(control);
	if (mostrar)
	{
		obj.style.display="";
	}
	else
	{
		obj.style.display="none";
	}
}

function hideAndShow(hideControl, showControl)
{
	var obj1 = document.getElementById(hideControl);
	obj1.style.display="none";
	
	var obj2 = document.getElementById(showControl);
	obj2.style.display="";
}

var dims = new Array();
function DIM(width, height) 
{
	this.width = width;
	this.height = height;
}

function resizeMainImage(target, src_img) 
{
	var w = 500;
	var h = 375;
	var newImg = new Image();
	newImg.src = src_img;

	if ( typeof(dims[src_img]) == 'undefined' )
	{
		dims[src_img] = new DIM(newImg.width, newImg.height);
	}

	var width  = dims[src_img].width;
	var height = dims[src_img].height;
	
	var image = document.getElementById(target);

	if ( width <= w && height <= h)
	{
		image.width = width;
		image.height = height;
		
		image.style.display='';
		return;
	}				

	var ratiox = w / width;
	var ratioy = h / height;

	if ( ratiox < ratioy )
	{
		image.width  = Math.min(w, width);
		image.height = (w / width) * height;
	}
	else
	{
		image.width  = (h / height) * width;
		image.height = Math.min(h, height);				
	}

	image.style.display='';
	return;
};
	
function showMainImage(target, src_img)
{
	dims = new Array();		// clear array
	resizeMainImage(target, src_img);
}
	
function showImage(target, src_img)
{
	var obj = document.getElementById(target);
	
	obj.onload = function() {
		resizeMainImage(target, src_img);
	};
	obj.src = src_img;
}

function nextImage(vimages, img_actual)
{
	for (j = 0; j < vimages.length; j++)
	{
		if (vimages[j] == img_actual.src)
		{
			index = j + 1;
			break;
		}
	}
	
	if (index >= vimages.length)
	{
		index = 0;
	}
	
	return vimages[index];
}

function getIndexImage(vimages, img_actual)
{
	for (j = 0; j < vimages.length; j++)
	{
		if (vimages[j] == img_actual.src)
		{
			return j;
		}
	}
	
	return -1;
}

function styleThumbs(prefijo, n, index, genStyle, selStyle)
{
	for (i = 0; i < n; i++)
	{
		var name = prefijo + i;
		
		var obj = document.getElementById(name);
		obj.className = genStyle;
	}
	
	var obj2 = document.getElementById(prefijo + index);
	obj2.className = selStyle;
}

function showInfo(prefijo, ctrl)
{
	for( i = 0; i < ctrl.length; i++)
	{
		var name = prefijo + i;
		var obj = document.getElementById(name);
		
		if(ctrl[i].checked) 
		{
			obj.style.display="";	
		}
		else
		{
			obj.style.display="none";				
		}
	}
}

function newAjax()
{ 
	/* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, por
	lo que se puede copiar tal como esta aqui */
	var xmlhttp=false;
	try
	{
		// Creacion del objeto AJAX para navegadores no IE
		xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			// Creacion del objet AJAX para IE
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(E)
		{
			if (!xmlhttp && typeof XMLHttpRequest!='undefined') xmlhttp=new XMLHttpRequest();
		}
	}
	return xmlhttp; 
}

function enviarAviso(id, tipo) 
{
	var ajax=newAjax();
	ajax.open("GET", 'avisar.php?id=' + id + '&t=' + tipo, true);
	ajax.onreadystatechange=function() 
	{ 
		if (ajax.readyState==1)
		{
		}
		if (ajax.readyState==4)
		{
			document.getElementById('notif_ad').style.display="none";
			document.getElementById('t_abusos').style.display="none";
			document.getElementById('resp_aviso').style.display="";
		} 
	}
	ajax.send(null);
}

function mostrarEspera(pos,id) 
{ 
	var puntos = ""; 
	pos %= 4; 
	for (var i = 0; i < pos; i++) 
		puntos += "."; 

	document.getElementById('puntos_cargando'+id).innerHTML = puntos; 
	pos++; 
	setTimeout('mostrarEspera('+pos+','+id+')', 500); 
} 

function mostrarMensajeEspera(id)
{
	document.getElementById('msg_espera'+id).style.display="inline";
	mostrarEspera(1, id);
}

function addfavoritos(url, titulo) {
   if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
      window.external.AddFavorite(url,titulo);
   }
   else {
      if(navigator.appName == "Netscape") {
         alert("Presione Crtl+D para agregar este sitio a sus Bookmarks");
      }
   }
}

function selectAdRow(obj, selected, esPar)
{
/*	if ( selected )
	{
		obj.style.backgroundColor = '#fefed2';
	}
	else
	{
		if (esPar)
		{
			obj.style.backgroundColor = '#FFFFFF';		
		}
		else
		{
			obj.style.backgroundColor = '#F5F5F5';
		}
	}*/
}

function popup(mylink, windowname, w, h)
{
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
   href=mylink;
else
   href=mylink.href;
window.open(href, windowname, 'width='+w+',height='+h+',scrollbars=yes');
return false;
}

function popupContactar(id)
{
	window.open('/contacto_anuncio.php?id='+id, '', 'toolbar=no, scrollbars=no, width=650, height=560, top=100, left=100');
}

function loadBlock(url, id)
{
	var ajax = newAjax();
	ajax.open("GET",url,true);
	
	ajax.onreadystatechange = function() {
		if(ajax.readyState==4)
		{
			document.getElementById(id).innerHTML=ajax.responseText;
			ponvalores();
		}
	}

	ajax.send(null);	
}

function loadSE(_url, id, tb, cat1, cat2, cat3, cat4, prm, prx, amm, amx, kmm, kmx, ndm, ndx, sfm ,sfx, trm, trx, prov, mun, ord)
{
	var url = _url+'?tb='+tb+'&categoria1='+cat1+'&categoria2='+cat2+'&categoria3='+cat3+'&categoria4='+cat4+"&pr_m="+prm+"&pr_x="+prx+"&am_m="+amm+"&am_x="+amx+"&km_m="+kmm+"&km_x="+kmx+"&nd_m="+ndm+"&nd_x="+ndx+"&sf_m="+sfm+"&sf_x="+sfx+"&tr_m="+trm+"&tr_x="+trx+"&prov="+prov+"&municipio="+mun+"&ord="+ord;
	
	loadBlock(url, id);
}

function loadMC(_url, id, uarea, cat1, cat2)
{
	var url = _url+'?uarea='+uarea+'&cat1='+cat1+'&cat2='+cat2;
	
	loadBlock(url, id);
}

function loadSEI(_url, id, prov)
{
	var url = _url+'?prov='+prov;

	loadBlock(url, id);
}

function ordenarPor(v)
{
	if(v=='precio_asc'){
		ord = '2';
	}else if(v=='precio_desc'){
		ord = '3';
	}else if(v=='fecha_desc'){
		ord = '';
	}

	document.forms[0].ord.value = ord;
	document.forms[0].submit();
}
