/************************** SECCION AJAX *****************************/
	
var http = objetus(); // We create the HTTP Object
	
function actualizarCiudadProvincia() {	// Funcion que realiza la peticion cuando el campo pierde el foco....
  var zipValue = document.getElementById("zip").value;
  http.open("GET", url + escape(zipValue), true);
  http.onreadystatechange = handleHttpResponse;
  http.send(null);
}

function handleHttpResponse() {			// Funcion que detecta la respuesta del server y actualiza el formulario ...
	if (http.readyState == 4) {
	    // Aca podemos realizar acciones en javascript o DOM en base a los valores devueltos por el XMLHttpRequest
	    var results = http.responseText.split(",");
        var idObjetoPadre='miListadoOcultar';       // inicializamos el nodo padre donde crear la tabla

    	switch(results[0]){
    		case "Eliminado":
                if(document.getElementById('tablaMiListado')){
                    var mytable = document.getElementById('tablaMiListado');
                    var nodoPadre = mytable.parentNode;           // se para en el nodo padre de la tabla
					for (var i=0; i<nodoPadre.childNodes.length; i++) {  // Recorro los hijos del padre, hasta encontrar uno de tipoTABLE y lo borro
						var elmHIJO = nodoPadre.childNodes[i];         // 
						if(elmHIJO.nodeName == 'TABLE'){               // Si el nodo que miro es TABLE
							nodoPadre.removeChild(nodoPadre.childNodes[i])  // Elimina el hijo iésimo del nodoPadre
						}
					}
                }
    		break
    		
    		case "Agregado":
    			if(!document.getElementById('tablaMiListado')){	// Preguntamos si la tabla No existe par acrearla
                    document.getElementById("miListadoOcultar").style.display = "block";    // habilitamos el div contenedor
                    crearTablaSola(idObjetoPadre);              // Llamamos al función que crea la tabla
    			}
                insertarFila(results);                          // Inertamos UNA fila a la tabla...
			break
            
            case "Eliminar":
                    eliminarFila(results[2]);                   // elimina la propiedad por su IdPropiedad...
            break;
            
            case "NoAgregado":
            	alert (results[1]);
            break;
    	}
    	//alert (results[1]);     // Muestra el mensaje eviado por funciones.php de la operación realizada
	}
}


function objetus() {	// Funcion que permite realizar todo lo anterior ...
         try {
                 objetus = new ActiveXObject("Msxml2.XMLHTTP");
        } catch ( e) {
                 try { 
                         objetus= new ActiveXObject ("Microsoft.XMLHTTP");
                 } catch (E) {
                          objetus= false; 
                } 
        }
        if (! objetus && typeof XMLHttpRequest!= 'undefined') {
                 objetus = new XMLHttpRequest();
        } 
        return objetus
}

/************************************** OPCIONES DEL CARRITO **********************************/

function eliminarLista(){
  var url = "funcionessesion.php?op=delAll&rm=" + Math.random(); // Script php en el sevidor, junto al parámetro,,,
  http.open("GET", url , true);
  http.onreadystatechange = handleHttpResponse;
  http.send(null);
}


function agregarLista(form){
  var opciones="&id=" + form.id.value + "&refInm=" + form.refInm.value + "&tipoOp=" + form.tipoOp.value + "&tipoInm=" + form.tipoInm.value + "&zona=" + form.zona.value;
  var url = "funcionessesion.php?op=add" + opciones + "&rm=" + Math.random(); // Script php en el sevidor, junto al parámetro,,,
  http.open("GET", url , true);
  http.onreadystatechange = handleHttpResponse;
  http.send(null);
}

function agregarListaHref(opciones){
  var url = "funcionessesion.php?op=add" + opciones + "&rm=" + Math.random(); // Script php en el sevidor, junto al parámetro,,,
  http.open("GET", url , true);
  http.onreadystatechange = handleHttpResponse;
  http.send(null);
}


function eliminarPropiedad(idP){
  var opciones="&idP=" + idP;
  var url = "funcionessesion.php?op=delProp" + opciones + "&rm=" + Math.random(); // Script php en el sevidor, junto al parámetro,,,
  http.open("GET", url , true);
  http.onreadystatechange = handleHttpResponse;
  http.send(null);
}


/************************************* Funciones para manipular tablas con DOM ***************************/

function insertarFila(results) {
    var elmTR;
    var elmTD;
    var elmText;

	mytable = document.getElementById("tablaMiListado"); 
	//elmTBODY = mytable.getElementsByTagName("tbody");  
	elmTBODY = document.getElementById("tbodyMiListado");

    elmTR = document.createElement('tr');               // Crea el mnodo TR a insertar en la tabla
    elmTR.id = "idP_"+results[2];
    
    for (var i=3; i<=6; i++) {
        elmTD = document.createElement('td');           // Crea el nodo TD a insertar en el nodo TR
        elmText = document.createTextNode(results[i]);  // Crea la cadena de texto del nodo TD (elementos del vector de resultados: results)
        elmTD.appendChild(elmText);                     // Agrega el nodo de texo al nodo del TD
        elmTR.appendChild(elmTD);                       // Agrega el nodo TD al nodo TR
    }


    // Agregamos las celdas para las Funciones de: Eliminar y Ver mas info...
    elmTD = document.createElement('td');       // Crea el nodo TD
    
    anchor = document.createElement("a");       // Crea el nodo <a>
    anchor.href = "javascript:eliminarPropiedad(" + results[2] +")";    // Define la propiedad href del nodo <a>
    anchor.id = "del_"+results[2];              // Define la propiedad id del nodo <a>
    hometext = document.createTextNode("borrar");  // Crea el nodo de texto de la etiqueta <a>
    anchor.appendChild(hometext);               // Agrega el nodo de texto como hijo del nodo <a>
    // Agregamos la etiqueta <a> al td...
    elmTD.appendChild(anchor);                  // Agrega el nodo <a> como hijo del nodo TD
    elmTR.appendChild(elmTD);                   // Agrega el nodo TD como hijo del nodo TR
    
    // Repetimos el proceso anterior para el link de Ver as info de la Propiedad
    elmTD = document.createElement('td');       
    anchor = document.createElement("a");
    anchor.href = "ver-inmueble.php?id=" + results[2];
    anchor.id = "mod_"+ results[2];             // Id de la Propiedad
    hometext = document.createTextNode("mas info");
    anchor.appendChild(hometext);
    elmTD.appendChild(anchor);
    elmTR.appendChild(elmTD);
    /*-------------------------------------------------------------------------------*/
  
    elmTBODY.appendChild(elmTR);                 // Agrega el nodo TR com hijo del nodo TBODY de la tabla
    mytable.appendChild(elmTBODY);               // Agrega el nodo tHead como hijo del nodo TABLE
}

/*-----------------------------------------------------------------------------------*/
 
function eliminarFila(idP) {
	var mytable = document.getElementById("tablaMiListado"); 
	var elmTBODY = document.getElementById("tbodyMiListado");  

	var cont = 0  // Inicializo el contador de elementos TR en cero..
	//alert('HIjos del TBODY: '+elmTBODY.childNodes.length)
	var tam=elmTBODY.childNodes.length;

	for (var i=0; i<tam; i++) {  // Recorro todos los nodos hijos de tbody, hasta encontrar el TR indicado...
		var elmTR = elmTBODY.childNodes[i];         // 
		//alert('NOmbre nodo hijo TBODY: '+elmTR.nodeName);
		if(elmTR.nodeName=='TR'){cont++}            // Si el hijo de TBODY es un TR lo cuento
		if(elmTR.id == 'idP_' + idP){               // Si el nodo Tr actual es que estoy buscando
			posElm = i;   // Elimino el nodo nro i...
		}
	}
	elmTBODY.removeChild(elmTBODY.childNodes[posElm])
	//alert('Contador: '+cont);

	var nodoPadre = mytable.parentNode;           // se para en el nodo padre de la tabla
	//alert('Nodo padre: '+nodoPadre.nodeName)

	if(cont==1){                                    // Si se eliminó el único TR del TBODY, borro la tabla...    
		for (var i=0; i<nodoPadre.childNodes.length; i++) {  // Recorro los hijos del padre, hasta encontrar uno de tipoTABLE y lo borro
			var elmHIJO = nodoPadre.childNodes[i];         // 
			if(elmHIJO.nodeName == 'TABLE'){               // Si el nodo que miro es TABLE
				nodoPadre.removeChild(nodoPadre.childNodes[i])  // Elimina el hijo iésimo del nodoPadre
				//alert('Se eliminó la tabla también: '+ elmHIJO.nodeName)
			}
		}
	}
}


/*-----------------------------------------------------------------------------------*/

function crearTablaSola(idObjetoPadre){
    var myObject = document.getElementById(idObjetoPadre);  // Obtiene el nodo padre donde se insertará la tabla
    var mytable  = document.createElement("table");         // Crea el nodo TABLE
    mytable.id   = "tablaMiListado";                        // Define el id del nodo TABLE
    var mytablehead = document.createElement("thead");      // Crea el nodo tHead de la tabla
    var mytablebody = document.createElement("tbody");      // Crea el nodo tbody de la tabla
    mytablebody.id  = "tbodyMiListado";                    // Define el id del nodo TOBDY
    
    // Creamos el tHead de la tabla
    var vecValTh = new Array("Referencia","Operación","Inmueble","Zona"," ","");    // Vector con las cadenas de text de cada TH
    
    mycurrent_row = document.createElement("tr");           // Crea el nodo TR que va dentro del tHead
    for(var i = 0; i < vecValTh.length; i++) {              // THs del Head (uno por cada valor del vector vecValTh...
        mycurrent_cell = document.createElement("th");      // Crea el primer nodo TH
        currenttext = document.createTextNode(vecValTh[i]); // Crea el nodo de texto que va dentro del TH
        mycurrent_cell.appendChild(currenttext);            // Agrega el nodo de texto como hijo del nodo TH
        mycurrent_row.appendChild(mycurrent_cell);          // Agrega el nodo TH como hijo del nodo TR
    }
    mytablehead.appendChild(mycurrent_row);                 // Agrega el nodo TR com hijo del nodo tHead de l a tabla
    mytable.appendChild(mytablehead);                       // Agrega el nodo tHead como hijo del nodo TABLE
    mytable.appendChild(mytablebody);                       // Agregamos el tbody a la tabla    
    myObject.insertBefore(mytable,myObject.childNodes[0])   // Inserto la tabla en antes del mprimer nodo del DIV..
}


/*
Selector de provincias y localidades Ajax - non intrusive - Cross browser 
Copyright (C)Iñaki Gorostiza Esquerdeiro
http://www.hellogoogle.com
webmaster@hellogoogle.com 
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

var XmlHttpObj;


var Utf8 = {

    //Convierte de UTF-8 a ISO
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

function CreateXmlHttpObj()
{
	try
	{
		XmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
	
	}
	catch(e)
	{
		try
		{
			XmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			XmlHttpObj = null;
		}
	}
		if(!XmlHttpObj && typeof XMLHttpRequest != "undefined") 
	{
		XmlHttpObj = new XMLHttpRequest();
	}
}

function provinciaListOnChange() {
var to=document.getElementById("advice");
to.innerHTML="<img src='img/loading.gif' align='absmiddle'>";
    var provinciaList = document.getElementById("provinciaList");
 
    var selectedprovincia = provinciaList.options[provinciaList.selectedIndex].value;
    var requestUrl;

     requestUrl = "xml_data_provider.php" + "?filter=" + encodeURIComponent(selectedprovincia);
    
	CreateXmlHttpObj();
	
	if(XmlHttpObj)
	{
	
		XmlHttpObj.onreadystatechange = StateChangeHandler;
		XmlHttpObj.open( "POST", requestUrl, true );
		XmlHttpObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		XmlHttpObj.send('');		
	}
}


function StateChangeHandler()
{
	if(XmlHttpObj.readyState == 4)
	{
		if(XmlHttpObj.status == 200)
		{			
			PopulatelocalidadList(XmlHttpObj.responseXML.documentElement);
		}
		else
		{
			alert("Código de error: "  + XmlHttpObj.status);
		}
	}
}

function PopulatelocalidadList(localidadNode)
{	
    var localidadList = document.getElementById("localidadList");
	for (var count = localidadList.options.length-1; count >-1; count--)
	{
		localidadList.options[count] = null;
	}

	var localidadNodes = localidadNode.getElementsByTagName('localidad');
	var textValue; 
	var optionItem;
	for (var count = 0; count < localidadNodes.length; count++)
	{ 
   		textValue = Utf8.decode(GetInnerText(localidadNodes[count]));
		idValue=count;		
		optionItem = new Option( textValue, textValue,  false, false);
		localidadList.options[localidadList.length] = optionItem;
	}
var to=document.getElementById("advice");
to.innerHTML="";
}

function GetInnerText (node)
{
	 return (node.textContent || node.innerText || node.text) ;
}



/*Ajax*/
//**************************************************************************
//Obtiene una instancia del objeto XmlHttpRequest

function ObtenerObjetoAjax() {

var peticionHttp = null;

try {

//Comprobación para navegadores Firefox, Opera y Safari

if (window.XMLHttpRequest) {

peticionHttp = new XMLHttpRequest();

}

//Comprobación para navegadores IE

else if (window.ActiveXObject) {

//Comprobamos para JavaScript 5.0. Si da error, 

//creamos un objeto con la versión anterior

try {

peticionHttp = new ActiveXObject("Microsoft.XMLHTTP2");

}

catch (e1) {

peticionHttp = new ActiveXObject("Microsoft.XMLHTTP");

}

}

//Comprobación para IceBrowser

else if (window.createRequest) {

peticionHttp = window.createRequest();

}

//Si el navegador no soporta ajax retornamos null

else {

peticionHttp = null;

}

}

catch (e2) {

return null;

}

return peticionHttp;

}

// A continuación crearemos la función que envíe la petición al servidor:

 //Realiza una petición asíncronamente al servidor

//url: Url dónde realizar la petición

//tipoResultado: Puede set 'XML' o 'TEXT'

//metodo: Tipo de petición. Puede ser 'GET' o 'POST'

//parametrosPost: Parámetros para peticiones tipo POST

//cacheDatos: Indica si se cachearán las peticiones por GET en IE

//funcionPintarDatos: Función para manejar las acciones a realizar en 

//                    cada estado de la petición

function ObtenerDatosASinc(url, tipoResultado, metodo, parametrosPost, 

					cacheDatos, funcionPintarDatos) {

try {

//Obtenemos la instancia del objeto XmlHttpObject

var objAjax = ObtenerObjetoAjax();

 

//Nos suscribimos al evento onreadystatechange para manejar los 

//posibles estados de la petición para que se lance la 

//función recibida por parámetro


objAjax.onreadystatechange = function() {
switch (objAjax.readyState) {

 

//Petición no inicializada 

case 0:

break;

 

//Conexión con el servidor establecida 

//(llamada a send) 

case 1:

break;

 

//Enviando petición 

case 2:

//Aquí se podría mostrar un gif que indicase 

//que se está realizando la petición al servidor

//Habría que ocultarlo en el caso 4, 

//cuando ya se ha recibido la respuesta

break;

 

//Recibiendo petición 

case 3:

break;

 

//Respuesta del servidor recibida 

case 4:

//Si el status code de la respuesta es 200, 

//todo ha ido bien

if (objAjax.status == 200) {

switch (tipoResultado) {

case 'XML':

  funcionPintarDatos(objAjax.responseXML);

  break;

case 'TEXT':

  funcionPintarDatos(objAjax.responseText);

  break;

default:

  funcionPintarDatos(objAjax.responseText);

  break;

}

}

//Si no, no ha ido bien y retornamos el texto 

//equivalente al status code

else {

switch (tipoResultado) {

case 'XML':

funcionPintarDatos(

'<a>' + objAjax.statusText + '</a>');

break;

case 'TEXT':

funcionPintarDatos(objAjax.statusText);

break;

default:

funcionPintarDatos(objAjax.statusText);

break;

}

}

break;

 

//No hay más estados en la petición, 

//por lo que no hacemos nada 

default:

break;

}

 

};

 

//Si realizamos la petición por POST

if (metodo == 'POST') {

 

//Si no recibimos parámetros ponemos la variable a null

if (parametrosPost == 'undefined' || !parametrosPost) {

parametrosPost = null;

}

 

objAjax.open('POST', url, true);

objAjax.setRequestHeader('Content-type', 

		'application/x-www-form-urlencoded');

objAjax.send(parametrosPost);

}

//Si no la realizamos por GET.

else {

 

//Internet Explorer cachea las peticiones por GET, 

//por lo que agregamos un parametro random si se 

//quiere evitar

if (!cacheDatos) {

var separadorUrl = 

	(url.indexOf('?') > -1) ? '&' : '?';

url += separadorUrl + 'rndCache=' + Math.random();

}

 

objAjax.open('GET', url, true);

objAjax.send(null);

}

}

catch (e) {

//Si hay un error mostramos su mensaje

alert(e.message);

}

}

 
 


 //Realiza una petición asíncrona al servidor para obtener la hora
function sendSugerencia() {

var sugerencia=document.getElementById('message');
var codigo=document.getElementById('resultado');

	
    
ObtenerDatosASinc('procesar-ajax.php?cod='+codigo.value+'&sug='+sugerencia.value+'&pagina=sugerencia', 'TEXT', 'GET', null, false, mostrarMensaje);
}    
 
 
 
//Función para pintar los datos recibidos del servidor
function mostrarMensaje(datos) {


 if (datos.length==0)
 {
    document.getElementById('envioExitoso').innerHTML = "Enviado exitosamente!";
	document.getElementById('envioError').innerHTML = "";
	document.getElementById('message').value="";
	document.getElementById('resultado').value="";
    var obj=document.getElementById('captcha');
	if (!obj) obj=window.document.all.cap;
    obj.src='captcha.php?' + Math.random();


 }
 else
 {
    document.getElementById('envioExitoso').innerHTML = '';
	document.getElementById('envioError').innerHTML = datos;
	 
}
 
  
}


function refrescarCodigo()
{

     document.getElementById('resultado').value='';
	 var obj=document.getElementById('captcha');
	if (!obj) obj=window.document.all.cap;
    obj.src='captcha.php?' + Math.random();
	
	return false;
}

function refrescarCodigoAux()
{

    if (document.getElementById('resultado').value=='')
	{
	 var obj=document.getElementById('captcha');
	   if (!obj) obj=window.document.all.cap;
       obj.src='captcha.php?' + Math.random();
	}
	return false;
}

function startUpload(){
//	alert('sisi');
      document.getElementById('f1_upload_process').style.visibility = 'visible';
      document.getElementById('f1_upload_form').style.visibility = 'hidden';
      return true;
}

function stopUpload(success){
//	alert(success);
      var result = '';
	  cantFotosSubidas=0;
      if (success != ''){
		 cantFotosSubidas =parseInt(document.getElementById('cantFotosSubidas').value);
		 cantFotosSubidas=cantFotosSubidas+1;
		 document.getElementById('cantFotosSubidas').value=cantFotosSubidas;
		// alert(cantFotosSubidas);
		 if (cantFotosSubidas > 3)
		 {
		  document.getElementById('f1_upload_process').style.display = 'none';
		   document.getElementById('f1_upload_form').style.display = 'none';
		  //document.getElementById('f1_upload_form').innerHTML = result + '<label>File: <input name="myfile" type="file" size="30" onchange="upload();"/><\/label>';
		  //<label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
		  //document.getElementById('f1_upload_form').style.visibility = 'visible';      
			 
		 }
		 else
		 {
		  if (success=='1')
		  {
			   alert('El archivo no pueder superior a 300k');
			   document.getElementById('f1_upload_process').style.visibility = 'hidden';
 			   document.getElementById('f1_upload_form').style.visibility = 'visible';
			   document.getElementById('cantFotosSubidas').value=cantFotosSubidas-1;
			   return true;
		  }
		  else	{} 
		  document.getElementById('f1_upload_process').style.visibility = 'hidden';
		  document.getElementById('f1_upload_form').innerHTML = result + '<label> <input name="myfile" type="file" size="30" onchange="upload();"/><br><span class="lblpaHelp"> (M&aacute;ximo 4 fotos) JPG, PNG, GIF</span><\/label>';
		  //<label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
		  document.getElementById('f1_upload_form').style.visibility = 'visible';      
			
		}
		var br='';
		var files='';
		if (document.getElementById('filess').innerHTML.length>4)
		{
			br='';
		}
		var linkk="<a href='#' onclick='borrarFoto(\""+success+"\","+cantFotosSubidas+");return false;' >borrar</a>";
		files="<p id='"+cantFotosSubidas+"'>"+br+cantFotosSubidas+'-'+success + '&nbsp;&nbsp;'+linkk+"</p>";
		
		  document.getElementById('filess').innerHTML=document.getElementById('filess').innerHTML +files ;
         //result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
		// alert(linkk);
      }
      else
	  
	  {
         result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
      }
      return true;   
}


function borrarFoto(nameFoto,idfoto)
{

	ObtenerDatosASinc('procesar-ajax.php?nameFoto='+nameFoto+'&idFoto='+idfoto+'&pagina=altafotos', 'TEXT', 'GET', null, false, setearDatos);
	
}

function setearDatos(datos)
{
	document.getElementById(datos).style.display='none';
	//var cantFotosSubidas =parseInt(document.getElementById('cantFotosSubidas').value);
	//cantFotosSubidas=cantFotosSubidas-1;
	//document.getElementById('cantFotosSubidas').value=cantFotosSubidas;
	//window.scrollTo(0,800);
}

function upload()
{
	startUpload();
	//validamos tipo de archivo que intentan subir
  document.formanuncio.action='upload.php';
  document.formanuncio.submit();
  
}

function enviarAnuncio()
{
  document.getElementById('divError').innerHTML='';	
  document.formanuncio.action='procesar-ajax.php';
  document.formanuncio.submit();
}

function respuestaServidor(result)
{

	if (result.length==0)
	{
		anuncioPublicado();
	}
	else
	{
		mostrarErrores(result);
	}
	window.scrollTo(0,0);
}

function anuncioPublicado()
{
	document.getElementById('divFelicidades').innerHTML= "<span class='textoVerde'>Felicidades!. Los cambios fueron guardados satisfactoriamente!</span><br><br>" +	
	 "<span class='gracias'><p>Nuestros editores estan analizando su anuncio. Si realiz&oacute; una carga respetando los <span class='operacion'> <a href='#' onclick='mostrarTerminos();'>t&eacute;rminos y condiciones</a> </span> en menos de 24 horas su anuncio ser&aacute; publicado. Gracias! por aunciarse en ClasiSalta.</p></span>" +
	 "<span class='operacion'> <a href='poner-anuncio.php'>Publicar otro anuncio</a>&nbsp;&nbsp;&nbsp;<a href='index.php'>Volver a inicio</a> </span><br>";
	 
	document.getElementById('divAnuncio').innerHTML='';
	
}

function mostrarErrores(result)
{
	//alert(result);
	document.getElementById('divError').innerHTML=result;
	//formBusqueda.document.getElementById('busqueda').focus();
	//document.getElementById('linkarriba').focus();

	
//	document.getElementById('f1_upload_form').innerHTML =result;
}

function desabilitarBoton(id,valor)
{
	document.getElementById(id).disabled=valor;
	//obj.disabled=valor;
	if (valor!='')
	{

	}
}

function valisualizar(valor)
{
	var boton='<span class=inpBtn><br /><input name=btnCerrar type=submit id=btnCerrar value="Cerrar Vista Previa"   onclick=\'valisualizar(false);\' /></span>';

	if (valor)
	{
		document.getElementById('divAnuncio').style.display='none';
		document.getElementById('divVisualizador').style.display='';
		document.getElementById('divVisualizador').innerHTML=document.getElementById('descripcionAnun').value + boton;
		window.scrollTo(0,0);
	}
	else
	{
		document.getElementById('divAnuncio').style.display='';
		document.getElementById('divVisualizador').style.display='none';
		window.scrollTo(800,400);

	}
}

function ocultarDescripcion(valor)
{

	if (valor==1)
	{
     
	  document.getElementById('descripcion').style.visibility = 'hidden';
	  document.getElementById('contraer').style.display = 'none';
	  document.getElementById('expandir').style.display = '';
	//  document.getElementById('adesense').style.display = 'none';
	
	  
	}
	else
	{
		
	  document.getElementById('descripcion').style.visibility = 'visible';
	  document.getElementById('contraer').style.display = '';
  	  document.getElementById('expandir').style.display = 'none';

//    	document.getElementById('adesense').style.display = '';
		
	}
}

function enviarMail()
{

if (document.formContact[0].value.length>4 && document.formContact[1].value.length>4 && document.formContact[3].value.length>0 && document.formContact[4].value.length>4)
{


	ObtenerDatosASinc('procesar-ajax.php?mensaje='+document.formContact[4].value+'&nombre='+document.formContact[0].value+'&mail='+document.formContact[1].value+'&idpublicidad='+document.formContact[3].value+'&pagina=mail', 'TEXT', 'GET', null, false, respuestaMail);
}

}

function respuestaMail(datos)
{

	if (datos=="1")
	{
		document.getElementById('cancelar').click();
//		alert('El mail se envio exitosamente!');
	}
	else
	{
//		alert('Lo sentimos hubo un error en el envio de mail');
		document.getElementById('cancelar').click();
	}
			alert('El mail se envio exitosamente!');
	
}

function ToUpperCase(obj)
{
	 obj.value=obj.value.toUpperCase();
}



function mostrarSubrubros(valor)
{
	//alert(valor);
	if (valor.length>1)
	{
		document.getElementById('subrubrosTodos').style.display='none';
		document.getElementById('subrubroParticular').style.display='';
		var linkBorrar='<a href=\"#\" onclick=\"document.getElementById(\'provincia\').value=0;document.getElementById(\'subrubro\').value=0;mostrarSubrubros(\'\');loadPage(1,document.getElementById(\'provincia\').value,document.getElementById(\'rubro\').value,0);cargarProvincias(document.getElementById(\'rubro\').value,0,5);return false;\" alt=\'quitar filtro\' > X</a>';
		//alert(valor+"<a href='#' onclick='mostrarSubrubros(\'\');'> x </a>");
		//alert(linkBorrar);
		document.getElementById('subrubroParticular').innerHTML='<h4>Subcategorias</h4>'+ valor + linkBorrar;
	}
	else
	{
		document.getElementById('subrubrosTodos').style.display='';
		document.getElementById('subrubroParticular').style.display='none';
	}
}

function cargarProvincias(idRubro,idSubrubro,cantidad)
{
ObtenerDatosASinc('procesar-ajax.php?idRubro='+idRubro+'&idSubrubro='+idSubrubro+'&cantidad='+cantidad+'&pagina=subrubros', 'TEXT', 'GET', null, false, loadProvincias);
}

function loadProvincias(datos)
{
	
	document.getElementById('divProvincias').innerHTML=datos;
}

function mostrarProvincias(valor)
{
	//alert(valor);
	if (valor.length>1)
	{
		document.getElementById('divProvincias').style.display='none';
		document.getElementById('divProvinciasparticular').style.display='';
		var linkBorrar='<a href=\"#\" onclick=\"document.getElementById(\'provincia\').value=0;loadPage(1,document.getElementById(\'provincia\').value,document.getElementById(\'rubro\').value,document.getElementById(\'subrubro\').value);mostrarProvincias(\'\');return false;\" alt=\'quitar filtro\' > X</a>';
		//alert(valor+"<a href='#' onclick='mostrarSubrubros(\'\');'> x </a>");
		//alert(linkBorrar);
		document.getElementById('divProvinciasparticular').innerHTML='<h4>Provincias</h4>'+valor + linkBorrar;
	}
	else
	{
		document.getElementById('divProvincias').style.display='';
		document.getElementById('divProvinciasparticular').style.display='none';
	}
}



 //Realiza una petición asíncrona al servidor para obtener la hora
function sendMail() {
				
var idpublicidad=document.getElementById('idpublicidad');				
var nombre=document.getElementById('nombre');
var mail=document.getElementById('mail');
var mensaje=document.getElementById('mensaje');
var resultado=document.getElementById('resultado');

	
    
ObtenerDatosASinc('procesar-ajax.php?mensaje='+mensaje.value+'&mail='+mail.value+'&nombre='+nombre.value+'&idpublicidad='+idpublicidad.value+'&resultado='+resultado.value+'&pagina=detalle', 'TEXT', 'GET', null, false, mostrarMensajeMail);
}    
 
 
 
//Función para pintar los datos recibidos del servidor
function mostrarMensajeMail(datos) {


 if (datos.length==0)
 {
    alert("El email se envio exitosamente !");
	document.getElementById('cancelar').click();
    var obj=document.getElementById('captcha');
	if (!obj) obj=window.document.all.cap;
    obj.src='captcha.php?' + Math.random();


 }
 else
 {
    //document.getElementById('envioExitoso').innerHTML = '';
	//document.getElementById('envioError').innerHTML = datos;
	 alert(datos);
}
 
  
}


function mostrarAdsenseSuperior(valor)
{

	if (valor==0)
	{
     
	  document.getElementById('anuncioGoogleSuperior').style.display = 'none';
	}
	else
	{
	 pausecomp(500);	
	  document.getElementById('anuncioGoogleSuperior').style.display = '';
	}
}


function pausecomp(millis) 
{
var date = new Date();
var curDate = null;

do { curDate = new Date(); } 
while(curDate-date < millis);
} 
