﻿var esNetscape = /a/ [-1] == 'a';
var esExplorer = '\v' == 'v';
var esChrome = /source/ .test(( /a/ .toString + ''));
var esSafari = /a/ .__proto__ == '//';
var esOpera = /^function \(/ .test([].sort);
var versionNavegador = parseInt(navigator.appVersion);
var esExplorer6 = /MSIE 6.0/i .test(navigator.userAgent);
var ieVer =/*@cc_on function(){switch(@_jscript_version){case 1.0:return 3;case 3.0:return 4;case 5.0:return 5;case 5.1:return 5;case 5.5:return 5.5;case 5.6:return 6;case 5.7:return 7}}()||@*/ 0;
var esExplorer7 = (ieVer == 7);

var PORTAL_SEGUNDAMANO = 1;
var PORTAL_LOQUO = 2;
var PORTAL_MUNDOANUNCIO = 3;
var PORTAL_MILANUNCIOS = 4;
var PORTAL_CAMPUSANUNCIOS = 5;
var PORTAL_EBAY = 6;
var PORTAL_HABITAMOS = 7;
var PORTAL_OLX = 8;
var PORTAL_FOTOCASA = 9;
var PORTAL_COCHESNET = 10;
var PORTAL_TABLONDEANUNCIOS = 11;
var PORTAL_CASINUEVO = 12;
var PORTAL_MANUNCIOS = 13;
var PORTAL_TUSANUNCIOS = 14;
//var PORTAL_ANUNCIOS			= 15;
var PORTAL_ANUNCIOTOTAL = 16;
var PORTAL_BLIDOO = 17;
var PORTAL_ANUNCIOSDIARIOS = 18;
var PORTAL_ANUNCIO = 19;
var PORTAL_ECLASI = 20;
var PORTAL_ADOOS = 21;
var PORTAL_CITTYS = 22;
var PORTAL_PLANETANUNCIOS = 23;
var PORTAL_MERKATIA = 24;
var PORTAL_VENDERYA = 25;
var PORTAL_TABLONIA = 26;
var PORTAL_NEON = 27;
var PORTAL_ANUNCIOTECA = 28;
var PORTAL_GLOBALANUNCIO = 29;
var PORTAL_TUCASA = 30;
var PORTAL_TELOANUNCIO = 31;
var PORTAL_COMISION = 32;
var PORTAL_HOGARIA = 33;
var PORTAL_TWITTER = 34;
var PORTAL_TROVIT = 35;
var PORTAL_SUMAVISOS = 36;
var PORTAL_DONKIZ = 37;
var PORTAL_AUTOMOBILE247 = 38;
var PORTAL_MOTORES = 39;
var PORTAL_CANALANUNCIO = 40;
var PORTAL_MITULA = 41;
var PORTAL_MELOCOMPRAS = 42;
var PORTAL_CLASF = 43;
var PORTAL_VENDOO = 44;

var numeroDePortales = 43;

var CATEGORIA_INMOBILIARIA = 1;
var CATEGORIA_MOTOR = 2;
var CATEGORIA_EMPLEO = 3;
var CATEGORIA_COMPRAVENTA = 4;
var CATEGORIA_SERVICIOS = 5;
var CATEGORIA_FORMACION = 6;
var CATEGORIA_COMUNIDAD = 7;
var CATEGORIA_CONTACTOS = 8;

var idUsuarioMCorreo;
var cambiarTituloPago = false;
var formAux;
var numeroAnunciosUsuario = 0;
var idAnunciosUsuario = "";
var repetidos = false;
var mostrarBotonBorrar = false;
var numMaxAnuncios = 0;
var apiBitLyCargada = false;

var arraySubcategorias = [
    [],
    ["Piso", "Apartamento", "Ático", "Dúplex", "Estudio", "Loft", "Habitación", "Obra nueva", "Casa", "Chalet", "Adosado", "Vacacional", "Oficina", "Local", "Plaza de garaje", "Trastero", "Parcela", "Terreno", "Solar", "Nave industrial"],
    ["Coches", "Motos", "Otros vehículos"],
    ["Administrativos", "RRHH", "Informática", "Ingeniería", "Comerciales / Ventas", "Marketing / Publicidad", "Contabilidad / Finanzas", "Medicina / Sanidad", "Educación / Formación", "Hostelería", "Turismo", "Peluquería / Estética", "Logística / Distribución", "Construcción / Mantenimiento", "Atención al cliente / Telemarketing", "Otros", "Busco empleo / CV"],
    ["Muebles", "Electrodomésticos", "Ordenadores / Informática", "Electrónica / Móviles", "Fotografía", "Imagen / Sonido", "Videojuegos / Consolas", "Pelis / Dvds", "Ropa / Accesorios", "Instrumentos musicales", "Artículos deportivos", "Joyas / Relojes", "Colección / Antigüedades", "Libros / Revistas", "Niños / Bebes", "Bricolaje / Jardín", "Intercambio / Regalo", "Otras ventas"],
    ["Informática / Internet", "Editorial / Traducciones", "Gestoría / Legal", "Reformas / Mantenimiento", "Transporte / Mudanzas", "Terapias / Masajes", "Limpieza / Doméstico", "Otros servicios"],
    ["Idiomas", "Música / Teatro / Danza", "Informática", "Talleres literarios", "Repaso / Recuperación", "Masters", "Otros cursos"],
    ["Compartir aficción", "Artistas / Músicos", "Voluntariado", "Compartir coche", "Intercambio de idiomas", "Canguros / Cuidado de personas", "Mascotas / Animales", "Comunidad varios"],
    ["Chica busca chico", "Chica busca chica", "Chico busca chico", "Chico busca chica", "Relacciones ocasionales", "Eroticos profesionales"]
];

var marcasDeMotos = [["Aprilia", "2"], ["Beta", "3"], ["Bmw", "4"], ["Buell", "5"], ["Bultaco", "6"], ["Cagiva", "8"], ["Daelim", "11"], ["Derbi", "13"], ["Ducati", "15"], ["Gas Gas", "19"], ["Gilera", "20"], ["Harley Davidson", "21"], ["Honda", "22"], ["Husqvarna", "24"], ["Hyosung", "25"], ["Kawasaki", "29"], ["Ktm", "31"], ["Kymco", "32"], ["Montesa", "40"], ["Moto Guzzi", "41"], ["Peugeot", "43"], ["Piaggio", "44"], ["Polaris", "45"], ["Rieju", "47"], ["Suzuki", "54"], ["Triumph", "56"], ["Vespa", "57"], ["Yamaha", "59"]];
var marcasDeCoches = [["Alfa Romeo", "1"], ["Audi", "60"], ["Bmw", "4"], ["Cadillac", "7"], ["Chevrolet", "9"], ["Chrysler", "10"], ["Citroen", "61"], ["Daewoo", "12"], ["Dodge", "14"], ["Ferrari", "16"], ["Fiat", "17"], ["Ford", "62"], ["Galloper", "18"], ["Honda", "22"], ["Hummer", "23"], ["Hyundai", "26"], ["Jaguar", "27"], ["Jeep", "28"], ["Kia", "30"], ["Lancia", "33"], ["Land-rover", "34"], ["Lexus", "35"], ["MG", "37"], ["Mazda", "36"], ["Mercedes", "63"], ["Mini", "38"], ["Mitsubishi", "39"], ["Nissan", "64"], ["Opel", "65"], ["Peugeot", "43"], ["Porsche", "46"], ["Renault", "66"], ["Rover", "48"], ["Saab", "49"], ["Seat", "67"], ["Skoda", "50"], ["Smart", "51"], ["Ssangyong", "52"], ["Subaru", "53"], ["Suzuki", "54"], ["Tata", "55"], ["Toyota", "68"], ["Volkswagen", "69"], ["Volvo", "58"]];
var arrayProvincias = new Array("A CORU" + decodeURI('%C3%91') + "A", "ÁLAVA", "ALACANT", "ALBACETE", "ALMERIA", "ASTURIAS", "AVILA", "BADAJOZ", "BARCELONA", "BURGOS", "CACERES", "CADIZ", "CANTABRIA", "CASTELLO", "CEUTA", "CIUDAD REAL", "CORDOBA", "CUENCA", "GIRONA", "GRANADA", "GUADALAJARA", "GUIPÚZCOA", "HUELVA", "HUESCA", "ILLES BALEARS", "JAEN", "LA RIOJA", "LAS PALMAS", "LEON", "LLEIDA", "LUGO", "MADRID", "MALAGA", "MELILLA", "MURCIA", "NAVARRA", "OURENSE", "PALENCIA", "PONTEVEDRA", "S. C. TENERIFE", "SALAMANCA", "SEGOVIA", "SEVILLA", "SORIA", "TARRAGONA", "TERUEL", "TOLEDO", "VALENCIA", "VALLADOLID", "VIZCAYA", "ZAMORA", "ZARAGOZA");
var arrayCodProv = new Array("15", "1", "3", "2", "4", "33", "5", "6", "8", "9", "10", "11", "39", "12", "51", "13", "14", "16", "17", "18", "19", "20", "21", "22", "7", "23", "26", "35", "24", "25", "27", "28", "29", "52", "30", "31", "32", "34", "36", "38", "37", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50");
var antiguedadPiso = [["Menos de un año", "1"], ["Entre 1 y 5 años", "2"], ["Entre 5 y 10 años", "3"], ["Entre 10 y 20 años", "4"], ["Entre 20 y 50 años", "5"], ["Mas de 50 años", "6"]];
var conservacionPiso = [["Casi Nuevo", "1"], ["Muy bien", "2"], ["Bien", "3"], ["A Reformar", "4"]];
//array de portales gratuitos
var arraygratuitos = new Array(2, 24, 34, 35, 32, 13, 20, 25, 27, 36, 37, 38, 39, 40, 41, 42,43,44);

function ObtenerMarcaDeCochePorCodigo(codigo) {
    for (var i = 0; i < marcasDeCoches.length; i++) {
        if (marcasDeCoches[i][1] == codigo)
            return marcasDeCoches[i][0];
    }
}

function ObtenerMarcaDeMotoPorCodigo(codigo) {
    for (var i = 0; i < marcasDeMotos.length; i++) {
        if (marcasDeMotos[i][1] == codigo)
            return marcasDeMotos[i][0];
    }
}

/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
var anunciosInsertados = [];
var botonInsertaranuncio = false;

function InsertarAnuncio(anuncio) {
    if (!EmailVerificado) {
/*He puesto esto para que no salga na hacia verificacionemail.aspx con email en blanco ya sea error nuestro o por el usuario*/
        if (anuncio.email != '') {
            Sexy.confirm('Antes de comenzar a publicar tu anuncio necesitamos que confirmes la dirección de correo ' + anuncio.email + '. Entra en tu buzón de correo y pincha en el link que te hemos enviado. ¿Quieres que te volvamos a enviar el link?', {
                textBoxBtnOk: 'Si',
                textBoxBtnCancel: 'No',
                onComplete: function(returnvalue) {
                    if (returnvalue) {
                        Sexy.alert('Hemos enviado un email a la dirección de correo: ' + anuncio.email);
                        var myRequest = new Request({
                                url: 'verificacionemail.aspx',
                                data: 'idUsuario=' + idUsuario + '&emailNuevoAnuncio=' + anuncio.email + '&Enviar=ok&Paso=2',
                                evalResponse: true
                            });
                        myRequest.get();
                    } else {
                    }
                }
            });
        }
    } else {
        var check = document.getElementsByTagName("input");
        var lista = "";
        var totalACobrar = 12; /*PRECIO DEL PAQUETE DE PORTALES ES 12€*/
        for (var i = 0; i < check.length; i++) {
            if (check[i].checked == true) {
                lista += check[i].id + "|";
            }
        }
        /*este es el que se usa*/
        var menContactos = "";
        totalACobrar = (totalACobrar * 100) / 100;
        totalACobrar = totalACobrar.toFixed(2); //Redondear a 2 digitos decimales.        
        saldo = parseFloat(saldo);
        if (lista != "") {
            botonInsertaranuncio = true;
            ComprobarSaldoBBDD(repetidos, numeroAnunciosUsuario, lista, anuncio.idAnuncio);
        } else {
            Sexy.alert('Selecciona primero en el listado superior los portales donde quieres insertar.');
        }
    }
}

function callbackinsertaranuncio(json) {
//var myRequest2 = new Request({
//                url: '../usuarios/ObtenerDatosAnuncio.aspx',
//		        data:'idAnuncio='+ anuncio.idAnuncio +'&callback=CallbackObtenerDatosDeAnuncio',
//		        evalResponse:true
//	        });  
//	    myRequest2.get();
//var url = rutaDeLaAplicacion+'usuarios/ObtenerDatosAnuncio.aspx?idAnuncio='+idAnuncio+'&callback=CallbackObtenerDatosDeAnuncio';
//cs(url);


//		$("seleccionar").innerHTML = "";
//		mensajeYainsertadoEnPortal(json);
//location.reload(true);

}

function SeHaTerminado(portal, respuesta) {
    var iconoOk = '<img src="../images/icons/check.ico">';
    var iconoFallo = '<img src="../images/icons/delete.ico">';
    var iconoPosibleFallo = '<img src="../images/icons/block.ico">';
    var textoOk = (portal == PORTAL_MILANUNCIOS || portal == PORTAL_MUNDOANUNCIO || portal == PORTAL_TABLONDEANUNCIOS || portal == PORTAL_MANUNCIOS || portal == PORTAL_BLIDOO || portal == PORTAL_ANUNCIOSDIARIOS || portal == PORTAL_ECLASI || portal == PORTAL_CITTYS || portal == PORTAL_VENDERYA) ? iconoOk + 'Insertado' : iconoOk + '<b>Confirmar email.</b>';
    var insertado = document.getElementById("insertado" + portal);

    if (respuesta == '') insertado.innerHTML = textoOk;
    else if (respuesta == 'FALLO') insertado.innerHTML = insertado.innerHTML = iconoPosibleFallo + 'Fallo';
    else insertado.innerHTML = iconoPosibleFallo + 'Posible fallo. <b>Verificar email.</b> o <a onclick="javascript:InsertarAnuncio(' + portal + ');" href="javascript:void(0);">reenviar</a>';
    /*switch(resultado){
		case '0':{
			insertado.innerHTML = textoOk;
			if(respuesta!='' && respuesta!='#EANF#')
				document.getElementById("insertado"+portal).innerHTML += '&nbsp;<a target="_blank" href='+respuesta+'>Ver</a>';
			}break;
		case '1': insertado.innerHTML = iconoFallo+"Fallo";break;
		case '2': insertado.innerHTML = iconoFallo+"Fallo";break;
		case '3': insertado.innerHTML = iconoFallo+"Fallo";break;
		case '4': insertado.innerHTML = iconoFallo+"Fallo";break;
		case '5': insertado.innerHTML = iconoFallo+"Fallo";break;
		case '6': insertado.innerHTML = iconoFallo+"Fallo";break;
		default: insertado.innerHTML = iconoPosibleFallo + 'Posible fallo. <b>Verificar email.</b> o <a onclick="javascript:InsertarAnuncio('+portal+');" href="javascript:void(0);">reenviar</a>'; break;
	}
	*/

    document.getElementById("loading" + portal).style.display = "none";
    insertado.style.display = "inline";
    for (var i = 0; i <= numeroDePortales; i++) {
        if (document.getElementById("link" + i)) {
            if (!anunciosInsertados[i]) {
                document.getElementById("link" + i).style.display = "inline";
                document.getElementById("insertardisabled" + i).style.display = "none";
            }
        }
    }

    if ($("divInsertarEnTodos")) {
        InsercionAutomatica();
    }
}

//Funcion no usada del antoguo mootools y version anterior del portal
function IntroducirCaptcha(catpcha, id, portal, paso) {

    var titulo = (paso == '0') ? 'El portal te pide que escribas el texto que ves en la imágen:' : 'El código no es correcto. Vuelve a intentarlo:';
    //QUITADO || portal==PORTAL_LOQUO portal == PORTAL_NEON ||
    var textoSexyPromp = (portal == PORTAL_EBAY || portal == PORTAL_ECLASI) ? '<h1>' + titulo + '</h1><br><p>' + catpcha + '</p>' : '<h1>' + titulo + '</h1><br><p><img src="' + catpcha + '"/></p>';

    Sexy.prompt(textoSexyPromp, '',
        {
            onComplete:
                function(returnvalue) {
                    if (returnvalue) {
                        var url = "../anunciar/publicaranuncios.aspx?id=" + id + "&portal=" + portal + "&paso=1&callback=callbackinsertaranuncio&texto=" + returnvalue;
                        cs(url);
                    }
                        //else IntroducirCaptcha(catpcha, id, portal,paso);
                    else SeHaTerminado(portal, "FALLO");
                }
        }
		 );
}


/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
var nombreUsuarioAux;
var SexyLightbox;

function Load() {

    switch (tipo) {
    case 1:
        numMaxAnuncios = 2;
        break;
    case 2:
        numMaxAnuncios = 10;
        break;
    case 3:
        numMaxAnuncios = 30;
        break;
    }

    if (tipo == 2 && diasRestantesSuscripcion == '0' || tipo == 3 && diasRestantesSuscripcion == '0') {
        Sexy.confirm("Tu cuenta de usuario premium ha sido desactivada temporalmente. Si deseas volver a hacerse usuario premium, pincha en Aceptar.", {
            textBoxBtnOk: 'Aceptar',
            textBoxBtnCancel: 'Cancelar',
            onComplete: function(returnvalue) {
                if (returnvalue) {
                    SexyLightbox.display('pagoPremiun.html?&height=400&width=670');
                } else {
                }
            }
        });
    }

    fillthescreen();
    if (esExplorer6) {
        alert("ATENCIÓN. Estas usando el navegador Internet Explorer 6. Ésta web no soporta éste navegador debido a que no cumple los estándares y además dificulta el desarrollo de Internet. Por favor, actualiza tu navegador o instalara Firefox o Google Chrome.");
    }


    if (primerAcceso) NuevoAnuncio();
    else ObtenerAnunciosDeUsuario();
}

function MostrarAsistente() {
    SexyLightbox.display('bienvenida.html?&usuario=' + nombreUsuario + '&height=300&width=500');
}

var ProgramarActivado = 'false';
var anuncioAuxProgramacion;

function ProgramarAnuncios(anuncio) {
    anuncioAuxProgramacion = anuncio;
    var labelMen;
    if (ProgramarActivado == 'true') {
        var l4 = document.createElement("a");
        l4.setAttribute("href", "javascript:ProgramarActivarValor('no'," + anuncio.idAnuncio + ")");
        l4.setAttribute("id", "l4");
        l4.innerHTML = 'Desactivar';
        l4.style.fontSize = "12px";
        l4.style.textAlign = "left";
        l4.style.fontWeight = "bold";
        labelMen = document.createElement("label");
        labelMen.innerHTML = "Tu anuncio será insertado automaticamente cada " + anuncio.strProgramacion + " días.<br><br>";
        labelMen.style.fontSize = "12px";
        labelMen.style.textAlign = "left";
        labelMen.style.fontWeight = "bold";
        //$("repetirActivado").innerHTML ='';
        $("repetirMen").innerHTML = '';
        //$("repetirActivado").appendChild(label);
        $("repetirMen").setAttribute("style", "");
        $("repetirMen").appendChild(labelMen);
        $("repetirLink").innerHTML = '';
        $("repetirLink").appendChild(l4);
    } else {
        //label.style.float="left";
//        label.style.fontWeight="bold";
//        label.style.color="red";
//        label.style.fontSize="12px";
        var l1 = document.createElement("a");
        l1.setAttribute("href", "javascript:InsertarAnuncioProgramado('3','" + anuncio.email + "','" + anuncio.idAnuncio + "')");
        l1.setAttribute("id", "l1");
        l1.setAttribute("style", "font-weight:bold; margin-right: 15px;");
        l1.innerHTML = '3 días  ';
        var l2 = document.createElement("a");
        l2.setAttribute("href", "javascript:InsertarAnuncioProgramado('7','" + anuncio.email + "','" + anuncio.idAnuncio + "')");
        l2.setAttribute("id", "l2");
        l2.setAttribute("style", "font-weight:bold; margin-right: 15px;");
        l2.innerHTML = '7 días  ';
        var l3 = document.createElement("a");
        l3.setAttribute("href", "javascript:InsertarAnuncioProgramado('30','" + anuncio.email + "','" + anuncio.idAnuncio + "')");
        l3.setAttribute("id", "l3");
        l3.setAttribute("style", "font-weight:bold;");
        l3.innerHTML = '30 días';
        //$("repetirActivado").innerHTML ='';
        //$("repetirActivado").appendChild(label);
        $("repetirLink").innerHTML = '';
        $("repetirLink").appendChild(l1);
        $("repetirLink").appendChild(l2);
        $("repetirLink").appendChild(l3);
        labelMen = document.createElement("label");
        labelMen.innerHTML = "Hacer que Posteator, vuelva a insertar este anuncio en los portales seleccionados cada:";
        labelMen.style.textAlign = "left";
        labelMen.style.fontSize = "12px";
        labelMen.style.fontWeight = "bold";
        $("repetirMen").innerHTML = '';
        $("repetirMen").appendChild(labelMen);
        $("repetirMen").setAttribute("style", "margin-bottom: 10px;margin-top: 10px; margin-left: 10px; margin-right: 5px;line-height:10pt;");
    }
}

var valorActivacion = '0';

function ProgramarActivarValor(tValorActivacion, idAnuncio) {
    if (tipo != 1) {
        valorActivacion = tValorActivacion;
        if (tValorActivacion == 'no') {
            var myRequest = new Request({
                    url: 'Operaciones.aspx',
                    data: 'IdAnuncio=' + idAnuncio + '&EliminarAnuncioProgramado=si',
                    evalResponse: true
                });
            myRequest.get();
            ProgramarActivado = 'false';
            //InsertarAnuncio(anuncio);
            ProgramarAnuncios(anuncioAuxProgramacion);
            ObtenerDatosDeAnuncio(idAnuncio);
        }
    } else {
        AbrirRecargarSaldo();
//        Sexy.confirm("Esta utilidad es para usuarios Premium, para poder disfrutar de ello pulsa en aceptar.", {
//		                textBoxBtnOk: 'Aceptar',
//		                textBoxBtnCancel: 'Cancelar',
//		                onComplete: function(returnvalue) {
//			            if (returnvalue) {
//				         AbrirRecargarSaldo();
//			            } else {}
//		                }
//	                    });    
    }
}

function InsertarAnuncioProgramado(tValorActivacion, email, idAnuncio) {

    if (tipo != 1) {

        if (!EmailVerificado) {
/*He puesto esto para que no salga na hacia verificacionemail.aspx con email en blanco ya sea error nuestro o por el usuario*/
            if (email != '') {
                Sexy.confirm('Para mejorar la calidad de los anuncios, a partir de ahora Posteator.com va a necesitar confirmar la direccion de correo electrónico: ' + email + '. Una vez que confirmes el correo, podras insertar todos tus anuncios con ese email. ¿Quieres confirmar ahora la direccion de correo?', {
                    textBoxBtnOk: 'Si',
                    textBoxBtnCancel: 'No',
                    onComplete: function(returnvalue) {
                        if (returnvalue) {
                            Sexy.alert('Hemos enviado un email a la dirección de correo: ' + anuncio.email);
                            var myRequest = new Request({
                                    url: 'verificacionemail.aspx',
                                    data: 'idUsuario=' + idUsuario + '&emailNuevoAnuncio=' + anuncio.email + '&Enviar=ok&Paso=2',
                                    evalResponse: true
                                });
                            myRequest.get();
                        } else {
                        }
                    }
                });
            }
        } else {

            var check = document.getElementsByTagName("input");
            var lista = "";
            var totalACobrar = 12; /*PRECIO DEL PAQUETE DE PORTALES ES 12€*/
            for (var i = 0; i < check.length; i++) {
                if (check[i].checked == true) {
                    lista += check[i].id + "|";
                }
            }
            /*este es el que se usa*/
            var menContactos = "";
            totalACobrar = (totalACobrar * 100) / 100;
            totalACobrar = totalACobrar.toFixed(2); //Redondear a 2 digitos decimales.        
            saldo = parseFloat(saldo);
            if (lista != "") {
                valorActivacion = tValorActivacion;
                botonInsertaranuncio = true;
                ProgramarActivado = 'true';
                ProgramarAnuncios(anuncioAuxProgramacion);
                ComprobarSaldoBBDD(repetidos, numeroAnunciosUsuario, lista, idAnuncio);
            } else {
                Sexy.alert('Antes de realizar la programación, necesitamos saber en qué portales deseas que se inserte tu anuncio. Selecciona primero en el listado superior los portales donde quieres insertar.');
            }
        }
    } else {
        AbrirRecargarSaldo();
    }
}

function ObtenerAnunciosDeUsuario() {
    var url = rutaDeLaAplicacion + 'usuarios/ObtenerAnuncios.aspx?idUsuario=' + idUsuario + '&callback=CallbackObtenerAnunciosDeUsuario';
    cs(url);
}

function CallbackObtenerAnunciosDeUsuario(json) {

    if (json.length > 0) {
        var ultimoAnuncio;
        var mostrarMensajeCobro = 0;
        repetidos = false;
        numeroAnunciosUsuario = 0;
        for (var i = 0; i < json.length; i++) {
            ultimoAnuncio = AnadirAnuncioAlListado(json[i]);
            idAnunciosUsuario = json[i].idAnuncio + "|" + idAnunciosUsuario;
            numeroAnunciosUsuario += 1;
            if (json[i].categoria == CATEGORIA_CONTACTOS || json[i].categoria == CATEGORIA_SERVICIOS) {
                mostrarMensajeCobro += 1;
            }
            if (json[i].repetido) {
                repetidos = true;
            }
        }
        if (mostrarMensajeCobro > 0) {
            mostrarMensajeCobro = 0;
        }

        if (repetidos) {
            Sexy.alert("<B>Aviso</B>: Tienes anuncios repetidos, por favor elimina los anuncios repetidos");
        }
        if (numeroAnunciosUsuario > numMaxAnuncios) {
            Sexy.alert("<B>Aviso</B>: El número de anuncios maximo permitido para poder publicar es de " + numMaxAnuncios + ", debe de borrar anuncios para poder realizarlo.");
        }
        ClickEnAnuncioDelListado(ultimoAnuncio);
    } else {
        NuevoAnuncio();
    }
}


function CerrarSesion() {
    Sexy.confirm('¿Estas seguro de que deseas salir?', {
        textBoxBtnOk: 'Si',
        textBoxBtnCancel: 'No',
        onComplete: function(returnvalue) {
            if (returnvalue) {
                var myRequest = new Request({
                        url: 'CerrarSesion.aspx',
                        data: '&callback=CallBackCerrarSesion',
                        evalResponse: true
                    });
                myRequest.get();
            } else {
            }
        }
    });
}

function CallBackCerrarSesion() {
    window.location = rutaDeLaAplicacion;
}

/////////////////////////////////////////////////////////////////////////////////////////

var portalesAInsertarEnTodos;
var anuncioAInsertarEnTodos;

function InsertarEnTodos(anuncio) {
    anuncioAInsertarEnTodos = anuncio;
    portalesAInsertarEnTodos = ObtenetPortalesDondeInsertarAnuncio(anuncioAInsertarEnTodos);
    SexyLightbox.display('insertarentodos.html?&height=200&width=500&modal=1');
}

function InsercionAutomatica() {
    if (portalesAInsertarEnTodos.length == 0) {
        $("infoInsertando").style.display = "none";
        $("insertarEnTodosTitulo").style.color = "black";
        $("insertarEnTodosTitulo").innerHTML = "La inserción de anuncios ha finalizado. Algunos de los portales requieren que actives tu anuncio mediante el email que te han enviado.<br><br>Ya puedes cerrar ésta ventana.";
    } else {
        ActualizarContadorDePortalesInsertados();
        var portal = parseInt(portalesAInsertarEnTodos.splice(0, 1), 10);
        ActualizarInsertandoEn(portal);
        InsertarAnuncio(anuncioAInsertarEnTodos.idAnuncio, portal);
    }
}

function ActualizarContadorDePortalesInsertados() {
    $("contadorAnunciosRestantes").innerHTML = "<b>" + portalesAInsertarEnTodos.length + "</b> portales";
}

function ActualizarInsertandoEn(portal) {
    var nombreEIcono = NombrePortalEIconoPorCodigoPortal(portal);
    $("insertandoEn").innerHTML = '<img src="' + nombreEIcono[1] + '" />&nbsp;&nbsp;' + nombreEIcono[0] + '&nbsp;&nbsp;<img src="../images/loading.gif"/>';
}

/////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var categoriaNuevoAnuncio;
var subcategoriaNuevoAnuncio;
var provinciaNombreNuevoAnuncio;
var provinciaCodigoNuevoAnuncio;
var poblacionNombreNuevoAnuncio;
var poblacionCodigoNuevoAnuncio;
var codigoPostalNuevoAnuncio;
var particularOEmpresaNuevoAnuncio;
var ofertaDemandaNuevoAnuncio;
var titulo1NuevoAnuncio;
var titulo2NuevoAnuncio;
var descripcion1NuevoAnuncio;
var descripcion2NuevoAnuncio;
var precioNuevoAnuncio;
var nombreNuevoAnuncio;
var emailNuevoAnuncio;
var URLNuevoAnuncio;
var repetiremailNuevoAnuncio;
var telefonoNuevoAnuncio;
var ocultarTelefonoNuevoAnuncio;
var imagen1NuevoAnuncio;
var imagen2NuevoAnuncio;
var imagen3NuevoAnuncio;
var imagen4NuevoAnuncio;
var imagen5NuevoAnuncio;
var aux1;
var aux2;
var aux3;
var aux4;
var aux5;
var aux6;
var aux7;
var aux8;
var nuevoAnuncioOpcionesUl;
var nuevoAnuncioOpcionesDiv;
var pasosAnteriores;
var primerAcceso;


function NuevoAnuncio() {

    if (numeroAnunciosUsuario < numMaxAnuncios && repetidos == false || primerAcceso) {

        categoriaNuevoAnuncio = "";
        subcategoriaNuevoAnuncio = "";
        provinciaNombreNuevoAnuncio = "";
        provinciaCodigoNuevoAnuncio = "";
        poblacionNombreNuevoAnuncio = "";
        poblacionCodigoNuevoAnuncio = "";
        codigoPostalNuevoAnuncio = "";
        particularOEmpresaNuevoAnuncio = 0;
        ofertaDemandaNuevoAnuncio = 0;
        titulo1NuevoAnuncio = "";
        titulo2NuevoAnuncio = "";
        descripcion1NuevoAnuncio = "";
        descripcion2NuevoAnuncio = "";
        precioNuevoAnuncio = "";
        nombreNuevoAnuncio = "";
        emailNuevoAnuncio = "";
        URLNuevoAnuncio = "";
        repetiremailNuevoAnuncio = "";
        telefonoNuevoAnuncio = "";
        ocultarTelefonoNuevoAnuncio = "";
        imagen1NuevoAnuncio = "";
        imagen2NuevoAnuncio = "";
        imagen3NuevoAnuncio = "";
        imagen4NuevoAnuncio = "";
        imagen5NuevoAnuncio = "";
        aux1 = "";
        aux2 = "";
        aux3 = "";
        aux4 = "";
        aux5 = "";
        aux6 = "";
        aux7 = "";
        aux8 = "";
        pasosAnteriores = new Array();

        var myRequest = new Request({
                url: '../usuarios/Operaciones.aspx',
                data: 'ComprobarEstadoSession=estado&&callback=CallbackEstadoSession',
                evalResponse: true
            });

        myRequest.get();

    } else {

        if (numeroAnunciosUsuario >= numMaxAnuncios) {
            if (tipo == 1 || tipo == 2 && diasRestantesSuscripcion == '0' || tipo == 3 && diasRestantesSuscripcion == '0') {
                SexyLightbox.display('pagoPremiun.html?&height=400&width=670');
            } else {
                Sexy.alert("Posteator.com únicamente permite tener " + numMaxAnuncios + " anuncios como máximo. Si quieres añadir uno nuevo, tendrás que borrar algunos de los que ya tienes hasta que te queden menos de " + numMaxAnuncios + ". También puedes modificar alguno de los que ya tienes insertado.");
            }
        }
        if (repetidos == true) Sexy.alert("<B>Aviso</B>: Tienes anuncios repetidos, por favor elimina los anuncios repetidos");

    }
}

function CallbackEstadoSession(sessionEstado) {
    if (sessionEstado == '') {
        window.location = '~/index.aspx';
    } else {
        SexyLightbox.display('nuevoanuncio.html?&height=400&width=700&modal=1');
    }
}

function SalirModoEdicion() {
    modoEdicion = false;
}

var idAnuncio;
var modoEdicion = false;
var anuncioModoEdicion;

function EditarAnuncio() {

    idAnuncio = anuncioModoEdicion.idAnuncio;
    categoriaNuevoAnuncio = anuncioModoEdicion.categoria;
    subcategoriaNuevoAnuncio = anuncioModoEdicion.subcategoria;
    provinciaNombreNuevoAnuncio = anuncioModoEdicion.provinciaNombre;
    provinciaCodigoNuevoAnuncio = anuncioModoEdicion.provinciaCodigo;
    poblacionNombreNuevoAnuncio = anuncioModoEdicion.poblacionNombre;
    poblacionCodigoNuevoAnuncio = anuncioModoEdicion.poblacionCodigo;
    codigoPostalNuevoAnuncio = anuncioModoEdicion.codigoPostal;
    particularOEmpresaNuevoAnuncio = anuncioModoEdicion.particularOEmpresa;
    ofertaDemandaNuevoAnuncio = anuncioModoEdicion.ofertaDemanda;
    titulo1NuevoAnuncio = anuncioModoEdicion.titulo1;
    titulo2NuevoAnuncio = anuncioModoEdicion.titulo2;
    descripcion1NuevoAnuncio = anuncioModoEdicion.descripcion1;
    descripcion2NuevoAnuncio = anuncioModoEdicion.descripcion2;
    precioNuevoAnuncio = anuncioModoEdicion.precio;
    nombreNuevoAnuncio = anuncioModoEdicion.nombre;
    emailNuevoAnuncio = anuncioModoEdicion.email;
    URLNuevoAnuncio = anuncioModoEdicion.URL;
    repetiremailNuevoAnuncio = anuncioModoEdicion.email;
    telefonoNuevoAnuncio = anuncioModoEdicion.telefono;
    ocultarTelefonoNuevoAnuncio = anuncioModoEdicion.ocultartelefono;
    imagen1NuevoAnuncio = anuncioModoEdicion.imagen1;
    imagen2NuevoAnuncio = anuncioModoEdicion.imagen2;
    imagen3NuevoAnuncio = anuncioModoEdicion.imagen3;
    imagen4NuevoAnuncio = anuncioModoEdicion.imagen4;
    imagen5NuevoAnuncio = anuncioModoEdicion.imagen5;
    aux1 = anuncioModoEdicion.aux1;
    aux2 = anuncioModoEdicion.aux2;
    aux3 = anuncioModoEdicion.aux3;
    aux4 = anuncioModoEdicion.aux4;
    aux5 = anuncioModoEdicion.aux5;
    aux6 = anuncioModoEdicion.aux6;
    aux7 = anuncioModoEdicion.aux7;
    aux8 = anuncioModoEdicion.aux8;
    modoEdicion = true;
    pasosAnteriores = new Array();
    SexyLightbox.display('nuevoanuncio.html?&height=400&width=700&modal=1');

}

function NuevoAnuncioIntroduccion() {
    nuevoAnuncioOpcionesUl = $("nuevoAnuncioOpcionesUl");
    nuevoAnuncioOpcionesDiv = $("nuevoAnuncioOpcionesDiv");

    if (modoEdicion) {
        InicializarPasoNuevoAnuncio(0, arguments.callee, "Edite su anuncio.", "");

    } else {
        InicializarPasoNuevoAnuncio(0, arguments.callee, "Insertar un nuevo anuncio.", "");
    }
    nuevoAnuncioOpcionesDiv.innerHTML = '<p>';
    nuevoAnuncioOpcionesDiv.innerHTML += 'Éste formulario te ayudará a introducir los datos de tu anuncio, sigue las instrucciones que se te vayan indicando. En la barra superior podrás ver el progreso, puedes volver atrás pinchando en el botón \"&lt; Retroceder\".';
    nuevoAnuncioOpcionesDiv.innerHTML += '</p>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<p>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<b>Recomendaciones:</b>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<ol>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<li style="margin-left:20px;">Introduce tu número de teléfono y dirección de email solamente cuando se te pida.</li>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<li style="margin-left:20px;">Inserta al menos una fotografía de tu anuncio, conseguirás mayor visibilidad.</li>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<li style="margin-left:20px;">No escribas texto en mayúsculas, muchos portales lo ignorarán.</li>';
    nuevoAnuncioOpcionesDiv.innerHTML += '</ol>';
    nuevoAnuncioOpcionesDiv.innerHTML += '</p>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br/>';
    if (modoEdicion) {
        var cerrar = document.getElementById("SLB-Top").childNodes[0];
        cerrar.setAttribute('onclick', 'SalirModoEdicion();'); // for FF 
        cerrar.onclick = function() { SalirModoEdicion(); }; // for IE
        NuevoAnuncioSeleccionarProvincia();
    } else {
        var botonContinuar = AnadirBotonContinuar(function() { NuevoAnuncioSeleccionarCategoria(); });
        botonContinuar.style.marginLeft = "270px";
        botonContinuar.innerHTML = "<span>Comenzar  ></span>";
    }


    DesactivarBotonRetroceder();

}

function NuevoAnuncioSeleccionarCategoria() {
    InicializarPasoNuevoAnuncio(0, arguments.callee, "Selecciona en primer lugar la categoría de tu anuncio:", "");
    ActivarBotonRetroceder();

    AnadirOpcionAlListadoDeOpciones("Inmobiliaria", function() {
        categoriaNuevoAnuncio = CATEGORIA_INMOBILIARIA;
        NuevoAnuncioSeleccionarSubCategoria();
    });
    AnadirOpcionAlListadoDeOpciones("Motor", function() {
        categoriaNuevoAnuncio = CATEGORIA_MOTOR;
        NuevoAnuncioSeleccionarSubCategoria();
    });
    AnadirOpcionAlListadoDeOpciones("Empleo", function() {
        categoriaNuevoAnuncio = CATEGORIA_EMPLEO;
        NuevoAnuncioSeleccionarSubCategoria();
    });
    AnadirOpcionAlListadoDeOpciones("Compra venta", function() {
        categoriaNuevoAnuncio = CATEGORIA_COMPRAVENTA;
        NuevoAnuncioSeleccionarSubCategoria();
    });
    AnadirOpcionAlListadoDeOpciones("Servicios", function() {
        categoriaNuevoAnuncio = CATEGORIA_SERVICIOS;
        NuevoAnuncioSeleccionarSubCategoria();
    });
    AnadirOpcionAlListadoDeOpciones("Formación", function() {
        categoriaNuevoAnuncio = CATEGORIA_FORMACION;
        NuevoAnuncioSeleccionarSubCategoria();
    });
    AnadirOpcionAlListadoDeOpciones("Comunidad", function() {
        categoriaNuevoAnuncio = CATEGORIA_COMUNIDAD;
        NuevoAnuncioSeleccionarSubCategoria();
    });
    AnadirOpcionAlListadoDeOpciones("Contactos", function() {
        categoriaNuevoAnuncio = CATEGORIA_CONTACTOS;
        NuevoAnuncioSeleccionarSubCategoria();
    });

}

function NuevoAnuncioSeleccionarSubCategoria() {
    InicializarPasoNuevoAnuncio(5, arguments.callee, "Selecciona una subcategoría para tu anuncio:", "");

    var subcategorias = arraySubcategorias[categoriaNuevoAnuncio];

    for (i = 0; i < subcategorias.length; i++) {
        var li = AnadirOpcionAlListadoDeOpciones(subcategorias[i], function() {
            subcategoriaNuevoAnuncio = this.subcategoriaNuevoAnuncio;
            NuevoAnuncioSeleccionarProvincia();
        });
        li.subcategoriaNuevoAnuncio = i + 1;
    }

}

function NuevoAnuncioSeleccionarProvincia() {
    InicializarPasoNuevoAnuncio(10, arguments.callee, "Selecciona la provincia de tu anuncio:", "");
    for (var i = 0; i < arrayProvincias.length; i++) {
        var li = AnadirOpcionAlListadoDeOpciones(arrayProvincias[i], function() {
            provinciaNombreNuevoAnuncio = this.provinciaNombreNuevoAnuncio;
            provinciaCodigoNuevoAnuncio = this.provinciaCodigoNuevoAnuncio;
            InicializarPasoNuevoAnuncio(15, arguments.callee, "Selecciona la población:", "");
            //if(provinciaCodigoNuevoAnuncio=="1" || provinciaCodigoNuevoAnuncio=="20" || provinciaCodigoNuevoAnuncio=="31" || provinciaCodigoNuevoAnuncio=="48"){
            var json = new Request.JSON({
                    url: rutaDeLaAplicacion + 'usuarios/ObtenerPoblaciones.aspx',
                    securre: false,
                    onSuccess: function(json) {
                        NuevoAnuncioSeleccionarPoblacion(json);
                    }
                }).get({ 'codigoProvincia': provinciaCodigoNuevoAnuncio });

            nuevoAnuncioOpcionesDiv.innerHTML = 'Carcando poblaciones .. <img src="../images/loading.gif" />';
        });
        li.provinciaNombreNuevoAnuncio = arrayProvincias[i];
        li.provinciaCodigoNuevoAnuncio = arrayCodProv[i];
    }
}

function NuevoAnuncioSeleccionarPoblacion(json) {
    ActivarBotonRetroceder();
    if (json) {
        nuevoAnuncioOpcionesDiv.innerHTML = '';
        var poblaciones = (json.consulta_municipiero.muni) ? json.consulta_municipiero.muni : json.consulta_municipiero.municipiero.muni;
        var numeroDePoblaciones = poblaciones.length;
        for (var i = 0; i < numeroDePoblaciones; i++) {
            var unapoblacion = poblaciones[i];
            var nombrePoblacion = unapoblacion.nm;
            var codigoPoblacion = unapoblacion.locat.cmc;
            var li = AnadirOpcionAlListadoDeOpciones(nombrePoblacion, function() {
                poblacionNombreNuevoAnuncio = this.nombrePoblacion;
                poblacionCodigoNuevoAnuncio = this.codigoPoblacion;
                NuevoAnuncioCodigoPostal();
            });
            li.nombrePoblacion = nombrePoblacion;
            li.codigoPoblacion = codigoPoblacion;
        }
    } else {
        alert("No se han podido cargar las poblaciones. Las poblaciones se cargan desde los servidores de catastro, que a veces están caidos. Vuelve a intentarlo o espera un rato.");
        BotonRetrocederClick();
    }
}


function NuevoAnuncioCodigoPostal() {
    InicializarPasoNuevoAnuncio(15, arguments.callee, "¿Cual es el código postal?", "");

    nuevoAnuncioOpcionesDiv.innerHTML = '';
    nuevoAnuncioOpcionesDiv.innerHTML += '<span class="pequenonegrita">Si no lo conoces pudes buscarlo en la <a href="http://www.correos.es/contenido/13-MenuRec2/04-MenuRec24/1010_s-CodPostal.asp" target="_blank">web de correos</a>.</span><br> ';
    nuevoAnuncioOpcionesDiv.innerHTML += ' <input id="codigoPostalNuevoAnuncio" style="WIDTH: 80px;" type="text" maxLength="5" NAME="codigoPostalNuevoAnuncio" value="' + codigoPostalNuevoAnuncio + '"/>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br><br>';

    AnadirBotonContinuar(function() {
        codigoPostalNuevoAnuncio = trim(document.getElementById('codigoPostalNuevoAnuncio').value);
        if (codigoPostalNuevoAnuncio == "") alert("Debes introducir el código postal del inmueble");
        else if (!IsNumeric(codigoPostalNuevoAnuncio)) alert("El codigo postal no es un número valido");
        else if (codigoPostalNuevoAnuncio.length != 5) alert("El código postal debe tener 5 números");
        else if (codigoPostalNuevoAnuncio < 1 || codigoPostalNuevoAnuncio > 52999) alert("El código postal debe ser un número entre 1 y 52999");
        else {

            if (categoriaNuevoAnuncio == CATEGORIA_COMUNIDAD || categoriaNuevoAnuncio == CATEGORIA_CONTACTOS) {
                NuevoAnuncioOpcionesEspecificas();
            } else NuevoAnuncioSeleccionarTipoVendedor();
        }
    });
}

function NuevoAnuncioSeleccionarTipoVendedor() {
    InicializarPasoNuevoAnuncio(20, arguments.callee, "¿Eres un particular o una empresa?", "");

    AnadirOpcionAlListadoDeOpciones("Particular", function() {
        particularOEmpresaNuevoAnuncio = 0;
        if (categoriaNuevoAnuncio == CATEGORIA_EMPLEO) NuevoAnuncioOpcionesEspecificas();
        else NuevoAnuncioSeleccionarOfertaDemanta();
    });
    AnadirOpcionAlListadoDeOpciones("Empresa", function() {
        particularOEmpresaNuevoAnuncio = 1;
        if (categoriaNuevoAnuncio == CATEGORIA_EMPLEO) NuevoAnuncioOpcionesEspecificas();
        else NuevoAnuncioSeleccionarOfertaDemanta();
    });
}

function NuevoAnuncioSeleccionarOfertaDemanta() {
    InicializarPasoNuevoAnuncio(25, arguments.callee, "¿Vendes un producto o estás buscando?", "");
    if (categoriaNuevoAnuncio == CATEGORIA_INMOBILIARIA) {
        if (subcategoriaNuevoAnuncio == 7) {
            ofertaDemandaNuevoAnuncio = 2;
            NuevoAnuncioOpcionesEspecificas();
        } else {
            AnadirOpcionAlListadoDeOpciones("Vendo", function() {
                ofertaDemandaNuevoAnuncio = 0;
                NuevoAnuncioOpcionesEspecificas();
            });
            AnadirOpcionAlListadoDeOpciones("Compro", function() {
                ofertaDemandaNuevoAnuncio = 1;
                NuevoAnuncioOpcionesEspecificas();
            });
            AnadirOpcionAlListadoDeOpciones("Alquilo", function() {
                ofertaDemandaNuevoAnuncio = 2;
                NuevoAnuncioOpcionesEspecificas();
            });
            AnadirOpcionAlListadoDeOpciones("Intercambio", function() {
                ofertaDemandaNuevoAnuncio = 3;
                NuevoAnuncioOpcionesEspecificas();
            });
        }
    } else {
        AnadirOpcionAlListadoDeOpciones("Vendo / Ofrezco", function() {
            ofertaDemandaNuevoAnuncio = 0;
            NuevoAnuncioOpcionesEspecificas();
        });
        AnadirOpcionAlListadoDeOpciones("Compro / Busco", function() {
            ofertaDemandaNuevoAnuncio = 1;
            NuevoAnuncioOpcionesEspecificas();
        });
    }
}

function NuevoAnuncioOpcionesEspecificas() {

    switch (categoriaNuevoAnuncio) {
    case CATEGORIA_INMOBILIARIA:
        {
            NuevoAnuncioOpcionesEspecificasInmuebleSuperficie();

        }
        break;
    case CATEGORIA_MOTOR:
        {
            switch (subcategoriaNuevoAnuncio) {
            case 1:
                NuevoAnuncioOpcionesEspecificasMotorMarcaVehiculo();
                break;
            case 2:
                NuevoAnuncioOpcionesEspecificasMotorMarcaVehiculo();
                break;
            default:
                NuevoAnuncioInsertarTitulo();
                break;
            }
            break;
        }
    case CATEGORIA_CONTACTOS:
        {
            ofertaDemandaNuevoAnuncio = 0;
            NuevoAnuncioOpcionesEspecificasContactosEdad();
            break;
        }
    default:
        {
            ofertaDemandaNuevoAnuncio = 0;
            NuevoAnuncioInsertarTitulo();
            break;
        }
    }
}

function NuevoAnuncioOpcionesEspecificasInmuebleAlquilerOVenta() {
    InicializarPasoNuevoAnuncio(30, arguments.callee, "¿Es alquiler o venta?", "");

    AnadirOpcionAlListadoDeOpciones("Alquiler", function() {
        aux4 = 0;
        NuevoAnuncioInsertarTitulo();
    });
    AnadirOpcionAlListadoDeOpciones("Venta", function() {
        aux4 = 1;
        NuevoAnuncioInsertarTitulo();
    });
}

function NuevoAnuncioOpcionesEspecificasInmuebleDormitorios() {
    if (subcategoriaNuevoAnuncio == 7) {

        aux2 = "1";
        NuevoAnuncioOpcionesEspecificasInmuebleBanos();

    } else {
        InicializarPasoNuevoAnuncio(30, arguments.callee, "¿Cuantos dormitorios tiene?", "");

        for (i = 1; i < 10; i++) {
            var li = AnadirOpcionAlListadoDeOpciones(i, function() {
                aux2 = this.dormitorios;
                NuevoAnuncioOpcionesEspecificasInmuebleBanos();
            });
            li.dormitorios = i;
        }
    }
}

function NuevoAnuncioOpcionesEspecificasInmuebleBanos() {
    if (subcategoriaNuevoAnuncio == 7) {

        aux3 = "1";
        NuevoAnuncioOpcionesEspecificasInmueblePlanta();

    } else {
        InicializarPasoNuevoAnuncio(30, arguments.callee, "¿Cuantos baños tiene?", "");
        for (i = 1; i < 5; i++) {
            var li = AnadirOpcionAlListadoDeOpciones(i, function() {
                aux3 = this.banos;
                NuevoAnuncioOpcionesEspecificasInmueblePlanta();
            });
            li.banos = i;
        }
    }
}

function NuevoAnuncioOpcionesEspecificasSituacionParcela() {
    InicializarPasoNuevoAnuncio(40, arguments.callee, "Describe la localización del inmueble", "");
    nuevoAnuncioOpcionesDiv.innerHTML = '';
    nuevoAnuncioOpcionesDiv.innerHTML += '<span class="pequenonegrita">No es necesário la ubicación exacta.</span><br> ';
    nuevoAnuncioOpcionesDiv.innerHTML += ' <input id="situacionNuevoAnuncio" style="WIDTH: 400px;" type="text" maxLength="70" NAME="situacionNuevoAnuncio" value="' + aux7 + '"/>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br><br>';

    AnadirBotonContinuar(function() {
        aux7 = trim(document.getElementById('situacionNuevoAnuncio').value);
        if (aux7 == "") {
            aux7 = "N/A";
        }
        NuevoAnuncioInsertarTitulo();
    });

}

function NuevoAnuncioOpcionesEspecificasInmuebleSuperficie() {
    InicializarPasoNuevoAnuncio(30, arguments.callee, "¿Cual es la superficie del inmueble?", "");
    nuevoAnuncioOpcionesDiv.innerHTML = '';
    nuevoAnuncioOpcionesDiv.innerHTML += '<span class="pequenonegrita">Escribe sólo números.</span><br> ';
    nuevoAnuncioOpcionesDiv.innerHTML += ' <input id="superficieNuevoAnuncio" style="WIDTH: 100px;" type="text" maxLength="12" NAME="superficieNuevoAnuncio" value="' + aux1 + '"/>&nbsp;&nbsp;m<sup>2</sup>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br><br>';

    AnadirBotonContinuar(function() {
        aux1 = trim(document.getElementById('superficieNuevoAnuncio').value);
        if (aux1 == "") alert("Debes intruducir la superficie del inmueble");
        else if (!IsNumeric(aux1)) alert("La superficie del inmueble no es un número correcto. Inserta solo números, sin puntos ni comas.");
        else if (aux1 <= 0) alert("La superficie del inmueble no puede ser menor o igual que cero.");
        else {
            if (subcategoriaNuevoAnuncio > 0 && subcategoriaNuevoAnuncio < 13) {
                NuevoAnuncioOpcionesEspecificasInmuebleDormitorios();
            } else {
                if (subcategoriaNuevoAnuncio > 12) {
                    NuevoAnuncioOpcionesEspecificasSituacionParcela();
                }
            }
        }
    });
}

function NuevoAnuncioOpcionesEspecificasInmuebleAntiguedad() {
    InicializarPasoNuevoAnuncio(35, arguments.callee, "¿Cual es la antiguedad del inmueble?", "");
    var añosAux = antiguedadPiso;
    for (var i = 0; i < añosAux.length; i++) {
        var años = añosAux[i][0];
        var codigoaño = añosAux[i][1];
        var li = AnadirOpcionAlListadoDeOpciones(años, function() {
            aux5 = this.codigoaño;
            NuevoAnuncioOpcionesEspecificasInmuebleConservacion();
        });
        li.codigoaño = codigoaño;
    }
}


function NuevoAnuncioOpcionesEspecificasInmueblePlanta() {
    if (subcategoriaNuevoAnuncio >= 9 && subcategoriaNuevoAnuncio <= 11) {
        InicializarPasoNuevoAnuncio(35, arguments.callee, "¿Cuantas plantas tiene el inmueble?", "");
    } else {
        InicializarPasoNuevoAnuncio(35, arguments.callee, "¿Cual es el número de planta?", "");
    }
    nuevoAnuncioOpcionesDiv.innerHTML = '';
    nuevoAnuncioOpcionesDiv.innerHTML += '<span class="pequenonegrita">Escribe sólo números.</span><br> ';
    nuevoAnuncioOpcionesDiv.innerHTML += ' <input id="plantaNuevoAnuncio" style="WIDTH: 100px;" type="text" maxLength="2" NAME="plantaNuevoAnuncio" value="' + aux4 + '"/>&nbsp;&nbsp;';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br><br>';

    AnadirBotonContinuar(function() {


        aux4 = trim(document.getElementById('plantaNuevoAnuncio').value);
        if (aux4 == "") alert("Debes intruducir la planta del inmueble");
        else if (!IsNumeric(aux4)) alert("La planta del inmueble no es un número correcto. Inserta solo números, sin puntos ni comas.");
        else if (aux4 <= 0) alert("La planta del inmueble no puede ser menor o igual que cero.");
        else if (aux4 > 30) alert("La planta del inmueble no puede ser mayor que 30.");
        else NuevoAnuncioOpcionesEspecificasInmuebleAntiguedad();

    });
}


function NuevoAnuncioOpcionesEspecificasInmuebleConservacion() {
    InicializarPasoNuevoAnuncio(40, arguments.callee, "¿Cual es el estado del inmueble?", "");
    var estadoAux = conservacionPiso;
    for (var i = 0; i < estadoAux.length; i++) {
        var estado = estadoAux[i][0];
        var codigoestado = estadoAux[i][1];
        var li = AnadirOpcionAlListadoDeOpciones(estado, function() {
            aux6 = this.codigoestado;
            NuevoAnuncioOpcionesEspecificasSituacionParcela();
        });
        li.codigoestado = codigoestado;
    }
}

function NuevoAnuncioOpcionesEspecificasMotorMarcaVehiculo() {
    InicializarPasoNuevoAnuncio(30, arguments.callee, "¿Cual es la marca del vehículo?", "");
    var marcasAux = (subcategoriaNuevoAnuncio == 1) ? marcasDeCoches : marcasDeMotos;
    for (var i = 0; i < marcasAux.length; i++) {
        var nombreMarca = marcasAux[i][0];
        var codigoMarca = marcasAux[i][1];
        var li = AnadirOpcionAlListadoDeOpciones(nombreMarca, function() {
            aux1 = this.codigoMarca;
            NuevoAnuncioOpcionesEspecificasMotorModeloVehiculo();
        });
        li.codigoMarca = codigoMarca;
    }
}

function NuevoAnuncioOpcionesEspecificasMotorModeloVehiculo() {
    InicializarPasoNuevoAnuncio(35, arguments.callee, "¿Cual es modelo?", "");
    nuevoAnuncioOpcionesDiv.innerHTML = '';
    nuevoAnuncioOpcionesDiv.innerHTML += ' <input id="modeloNuevoAnuncio" style="WIDTH: 300px;" type="text" maxLength="50" NAME="modeloNuevoAnuncio" value="' + aux2 + '"/>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br><br>';

    AnadirBotonContinuar(function() {
        aux2 = trim(document.getElementById('modeloNuevoAnuncio').value);
        if (aux2 == "") alert("Debes intruducir el modelo del vehiculo.");
        else NuevoAnuncioOpcionesEspecificasMotorAnoVehiculo();
    });
}

function NuevoAnuncioOpcionesEspecificasMotorAnoVehiculo() {
    InicializarPasoNuevoAnuncio(40, arguments.callee, "¿De qué año es el vehículo?", "");
    for (var i = 2010; i >= 1970; i--) {
        var li = AnadirOpcionAlListadoDeOpciones(i, function() {
            aux3 = this.ano;
            NuevoAnuncioOpcionesEspecificasMotorKm();
        });
        li.ano = i;
    }
}

function NuevoAnuncioOpcionesEspecificasMotorKm() {
    InicializarPasoNuevoAnuncio(40, arguments.callee, "¿Cuantos kilómetros tiene el vehículo?", "");
    nuevoAnuncioOpcionesDiv.innerHTML = '';
    nuevoAnuncioOpcionesDiv.innerHTML += '<span class="pequenonegrita">Escribe sólo números.</span><br> ';
    nuevoAnuncioOpcionesDiv.innerHTML += ' <input id="kmNuevoAnuncio" style="WIDTH: 100px;" type="text" maxLength="10" NAME="kmNuevoAnuncio" value="' + aux4 + '"/>&nbsp; Km';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br><br>';

    AnadirBotonContinuar(function() {
        aux4 = trim(document.getElementById('kmNuevoAnuncio').value);
        if (aux4 == "") alert("Escribe el número de kilometros");
        else if (!IsNumeric(aux4)) alert("No es un número válido. Escribe solo números, sin puntos ni comas.");
        else if (aux4 <= 0) alert("No puede ser menor o igual que cero.");
        else NuevoAnuncioOpcionesEspecificasMotorCombustible();
    });
}

function NuevoAnuncioOpcionesEspecificasMotorCombustible() {
    InicializarPasoNuevoAnuncio(40, arguments.callee, "¿Qué combustible usa?", "");

    AnadirOpcionAlListadoDeOpciones("Gasolina", function() {
        aux5 = 0;
        NuevoAnuncioOpcionesEspecificasMotorCambio();
    });
    AnadirOpcionAlListadoDeOpciones("Diesel", function() {
        aux5 = 1;
        NuevoAnuncioOpcionesEspecificasMotorCambio();
    });
    AnadirOpcionAlListadoDeOpciones("Otro", function() {
        aux5 = 2;
        NuevoAnuncioOpcionesEspecificasMotorCambio();
    });
}

function NuevoAnuncioOpcionesEspecificasMotorCambio() {
    InicializarPasoNuevoAnuncio(40, arguments.callee, "¿Qué cambio de marchas tiene?", "");
    AnadirOpcionAlListadoDeOpciones("Manual", function() {
        aux6 = 0;
        NuevoAnuncioInsertarTitulo();
    });
    AnadirOpcionAlListadoDeOpciones("Secuencial", function() {
        aux6 = 1;
        NuevoAnuncioInsertarTitulo();
    });
    AnadirOpcionAlListadoDeOpciones("Semiautomatico", function() {
        aux6 = 2;
        NuevoAnuncioInsertarTitulo();
    });
    AnadirOpcionAlListadoDeOpciones("Automatico", function() {
        aux6 = 3;
        NuevoAnuncioInsertarTitulo();
    });
}

function NuevoAnuncioOpcionesEspecificasContactosEdad() {
    InicializarPasoNuevoAnuncio(35, arguments.callee, "¿Qué edad tienes?", "");
    for (var i = 18; i < 100; i++) {
        var li = AnadirOpcionAlListadoDeOpciones(i, function() {
            aux1 = this.edad;
            NuevoAnuncioOpcionesEspecificasContactosQueBuscas();
        });
        li.edad = i;
    }
}

function NuevoAnuncioOpcionesEspecificasContactosQueBuscas() {
    InicializarPasoNuevoAnuncio(40, arguments.callee, "¿Qué tipo de relacción buscas?", "");
    AnadirOpcionAlListadoDeOpciones("Relacción estable", function() {
        aux2 = 0;
        NuevoAnuncioOpcionesEspecificasContactosChicoChica();
    });
    AnadirOpcionAlListadoDeOpciones("Encuentro casual", function() {
        aux2 = 1;
        NuevoAnuncioOpcionesEspecificasContactosChicoChica();
    });
}

function NuevoAnuncioOpcionesEspecificasContactosChicoChica() {
    InicializarPasoNuevoAnuncio(40, arguments.callee, "¿Eres un..?", "");
    AnadirOpcionAlListadoDeOpciones("Hombre", function() {
        aux3 = 0;
        NuevoAnuncioInsertarTitulo();
    });
    AnadirOpcionAlListadoDeOpciones("Mujer", function() {
        aux3 = 1;
        NuevoAnuncioInsertarTitulo();
    });
}

function NuevoAnuncioInsertarTitulo() {
    InicializarPasoNuevoAnuncio(45, arguments.callee, "Escribe ahora el título de tu anuncio:", "Asegurate de que describe tu anuncio lo mejor posible.");

    nuevoAnuncioOpcionesDiv.innerHTML = '';
    nuevoAnuncioOpcionesDiv.innerHTML += '	<label for="titulo1NuevoAnuncio">Título:</label><span class="pequenonegrita">&nbsp;(Al menos cinco palabras diferentes).</span><br>';
    nuevoAnuncioOpcionesDiv.innerHTML += '	<input id="titulo1NuevoAnuncio" style="width:450px;" type="text" maxLength="500" NAME="titulo1NuevoAnuncio" value="' + titulo1NuevoAnuncio + '"/>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<p>';
    nuevoAnuncioOpcionesDiv.innerHTML += '	<label for="titulo2NuevoAnuncio">Título abreviado:</label><span class="pequenonegrita">&nbsp;(Máximo 40 caracteres).</span> <A onclick=\'javascript:if(document.getElementById("titulo1NuevoAnuncio").value.length>parseInt(document.getElementById("titulo2NuevoAnuncio").getAttribute("maxlength")))document.getElementById("titulo2NuevoAnuncio").value=document.getElementById("titulo1NuevoAnuncio").value.substring(0,parseInt(document.getElementById("titulo2NuevoAnuncio").getAttribute("maxlength"))); else document.getElementById("titulo2NuevoAnuncio").value=document.getElementById("titulo1NuevoAnuncio").value;\' href="javascript:void(0);" >Copiar el texto anterior</A>.<br>';
    nuevoAnuncioOpcionesDiv.innerHTML += '	<input id="titulo2NuevoAnuncio" style="width:450px;" type="text" maxLength="40" NAME="titulo2NuevoAnuncio" value="' + titulo2NuevoAnuncio + '"/>';
    nuevoAnuncioOpcionesDiv.innerHTML += '</p>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br><br>';

    AnadirBotonContinuar(function() {
        titulo1NuevoAnuncio = trim(document.getElementById('titulo1NuevoAnuncio').value);
        var titulo1NuevoAnuncioLower = titulo1NuevoAnuncio.toLowerCase();
        titulo2NuevoAnuncio = trim(document.getElementById('titulo2NuevoAnuncio').value);
        //Quitamos el punto final para que se puedan visualizar correctamente los anuncios.
        while (titulo2NuevoAnuncio.lastIndexOf('.') == titulo2NuevoAnuncio.length - 1) {

            if (titulo2NuevoAnuncio.lastIndexOf('.', titulo2NuevoAnuncio.length) == titulo2NuevoAnuncio.length - 1) {
                titulo2NuevoAnuncio = titulo2NuevoAnuncio.substring(0, titulo2NuevoAnuncio.length - 1);
            }
        }

        if (titulo1NuevoAnuncio == "") alert("Debes introducir el título del anuncio.");
        else if (titulo1NuevoAnuncio.indexOf("\"") >= 0 || titulo1NuevoAnuncio.indexOf("'") >= 0 || titulo1NuevoAnuncio.indexOf("<") >= 0 || titulo1NuevoAnuncio.indexOf(">") >= 0 || titulo1NuevoAnuncio.indexOf("!") >= 0 || titulo1NuevoAnuncio.indexOf("*") >= 0 || titulo1NuevoAnuncio.indexOf("&") >= 0 || titulo1NuevoAnuncio.indexOf("'") >= 0) alert("No están permitidos en el título los caracteres: \", ', <, >, !, *, &");
        else if (titulo1NuevoAnuncio.indexOf("....") > 0) alert("Demasiados signos de puntuación en el título del anuncio.");
        else if (titulo1NuevoAnuncio.split(' ').length < 5) alert("El título debe contener al menos cinco palabras.");
        else if (titulo1NuevoAnuncioLower.indexOf("vende") > 0 || titulo1NuevoAnuncioLower.indexOf("compra") > 0 || titulo1NuevoAnuncioLower.indexOf("vendo") > 0 || titulo1NuevoAnuncioLower.indexOf("compro") > 0) alert("No están permitidas en el título las palabras 'vendo' o 'compro'");
        else if (titulo2NuevoAnuncio == "") alert("Debes introducir el título abreviado.");
        else if (titulo2NuevoAnuncio.length > 40) alert("El título abreviado debe de contener menos 40 caracteres.");
        else if (titulo1NuevoAnuncio.length < 20) alert("El título debe de contener al menos 20 caracteres.");
        else if (titulo2NuevoAnuncio.indexOf("\"") > 0 || titulo2NuevoAnuncio.indexOf("'") > 0 || titulo2NuevoAnuncio.indexOf(";") > 0 || titulo2NuevoAnuncio.indexOf("?") > 0 || titulo2NuevoAnuncio.indexOf("/") > 0 || titulo2NuevoAnuncio.indexOf(":") > 0 || titulo2NuevoAnuncio.indexOf("#") > 0 || titulo2NuevoAnuncio.indexOf("&") > 0 || titulo2NuevoAnuncio.indexOf("=") > 0 || titulo2NuevoAnuncio.indexOf("$") > 0 || titulo2NuevoAnuncio.indexOf("%") > 0 || titulo2NuevoAnuncio.indexOf("<") > 0 || titulo2NuevoAnuncio.indexOf(">") > 0 || titulo2NuevoAnuncio.indexOf("~") > 0) alert("No están permitidos en el título abreviado los caracteres: \" ' ; / : # & = $ % < > ~ _");
        else {

            verificarTitulo();

        }
    });

}

function verificarTitulo() {

    if (primerAcceso) {
        NuevoAnuncioInsertarDescripcion();
    }
    ;

    var myRequest = new Request({
            url: '../usuarios/verificartitulodescripcion.aspx',
            data: 'titulo=' + titulo1NuevoAnuncio + '&idAnuncios=' + idAnunciosUsuario + '&callback=CallbackVerificarTitulo',
            evalResponse: true
        });
    myRequest.get();
}

function CallbackVerificarTitulo(continuar) {
    if (modoEdicion) {
        NuevoAnuncioInsertarDescripcion();
    } else {
        if (!continuar) alert("Ya tiene un anuncio con este titulo, no repita anuncios");

        else NuevoAnuncioInsertarDescripcion();
    }
}


function NuevoAnuncioInsertarDescripcion() {
    InicializarPasoNuevoAnuncio(50, arguments.callee, "Escribe la descripción de tu anuncio:", "Cuanto mejor describas tu anuncio, mejores serán los contactos que recibas.");
    nuevoAnuncioOpcionesDiv.innerHTML = '';
    nuevoAnuncioOpcionesDiv.innerHTML += '	<span class="pequenonegrita">Escribe al menos 15 palabras diferentes.</span> ';
    nuevoAnuncioOpcionesDiv.innerHTML += '	<textarea  id="descripcion1NuevoAnuncio" name="descripcion1NuevoAnuncio" rows="10" cols="20"  style="width:590px;height:140px;" onKeyUp="var maxLength = 1800;if(this.value.length>maxLength)this.value=this.value.substring(0,maxLength);">' + descripcion1NuevoAnuncio + '</textarea>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br><br>';

    AnadirBotonContinuar(function() {
        descripcion1NuevoAnuncio = trim(document.getElementById('descripcion1NuevoAnuncio').value);

        if (descripcion1NuevoAnuncio == "") alert("Debes introducir una descripción del anuncio.");
        else if (descripcion1NuevoAnuncio.split(' ').length < 15) alert("Tu anuncio debe de contener al menos 15 palabras en la descripción.");
        else if (descripcion1NuevoAnuncio.indexOf("loquo") > 0) alert("No está permitida la palabra loquo en la descripción del anuncio.");
        else if (descripcion1NuevoAnuncio.indexOf(" msn") > 0) alert("No está permitida la palabra msn en la descripción del anuncio.");
        else if (descripcion1NuevoAnuncio.length < 30) alert("Tu anuncio debe de tener al menos 30 caracteres en la descripción.");
        else if (descripcion1NuevoAnuncio.indexOf("\"") > 0 || descripcion1NuevoAnuncio.indexOf("'") > 0 || descripcion1NuevoAnuncio.indexOf("<") > 0 || descripcion1NuevoAnuncio.indexOf(">") > 0 || descripcion1NuevoAnuncio.indexOf("!") > 0 || descripcion1NuevoAnuncio.indexOf("*") > 0 || descripcion1NuevoAnuncio.indexOf("&") > 0 || descripcion1NuevoAnuncio.indexOf("'") > 0) alert("No están permitidos en la descripción los caracteres: \", ', <, >, !, *, &");
        else if (ContieneURL(descripcion1NuevoAnuncio)) alert("No puedes introducir una URL en la descripción, tu anuncio puede que no se inserte correctamente.");
        else verificarDescripcion();
    });
}

function verificarDescripcion() {
    if (primerAcceso) NuevoAnuncioInsertarDescripcionAbreviada();

    var myRequest = new Request({
            url: '../usuarios/verificartitulodescripcion.aspx',
            data: 'descripcion=' + descripcion1NuevoAnuncio + '&idAnuncios=' + idAnunciosUsuario + '&callback=CallbackVerificarDescripcion',
            evalResponse: true
        });
    myRequest.get();
}

function CallbackVerificarDescripcion(continuar) {
    if (!modoEdicion) {
        if (!continuar) alert("Ya tiene un anuncio con esta descripcion, no repita anuncios");

        else NuevoAnuncioInsertarDescripcionAbreviada();
    } else {
        NuevoAnuncioInsertarDescripcionAbreviada();
    }
}


function NuevoAnuncioInsertarDescripcionAbreviada() {
    InicializarPasoNuevoAnuncio(55, arguments.callee, "Escribe ahora una descripción abreviada:", "Algunos portales sólamente permiten descripciones abreviadas de los anuncios.");

    nuevoAnuncioOpcionesDiv.innerHTML = '	<span class="pequenonegrita">Como máximo 255 caracteres.</span> Puedes <A onclick=\'javascript:if(descripcion1NuevoAnuncio.length>255)document.getElementById("descripcion2NuevoAnuncio").value=descripcion1NuevoAnuncio.substring(0,255); else document.getElementById("descripcion2NuevoAnuncio").value=descripcion1NuevoAnuncio;\' href="javascript:void(0);" >copiar el texto anterior</A>';
    nuevoAnuncioOpcionesDiv.innerHTML += '	<textarea id="descripcion2NuevoAnuncio"  onkeyup="javascript:var maxLength = 255; if(this.value.length>maxLength)this.value=this.value.substring(0,maxLength);" name="descripcion2NuevoAnuncio" rows=10 cols=10 style="width:590px;height:80px;">' + descripcion2NuevoAnuncio + '</textarea>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br><br>';

    AnadirBotonContinuar(function() {
        descripcion2NuevoAnuncio = trim(document.getElementById('descripcion2NuevoAnuncio').value);

        if (descripcion2NuevoAnuncio == "") alert("Debes introducir una descripción abreviada del anuncio.");
        else if (descripcion2NuevoAnuncio.length < 30) alert("La descripción detallada debe de contener al menos 30 caracteres.");
        else if (descripcion2NuevoAnuncio.length > 255) alert("No puedes introducir más de 255 caracteres en la descripción abreviada.");
        else if (descripcion2NuevoAnuncio.split(' ').length < 5) alert("Tu anuncio debe de contener al menos 5 palabras en la descripción.");
        else if (ContieneURL(descripcion2NuevoAnuncio)) alert("No puedes introducir una URL en la descripción, tu anuncio puede que no se inserte correctamente.");
        else NuevoAnuncioInsertarPrecio();
    });
}

function NuevoAnuncioInsertarPrecio() {
    InicializarPasoNuevoAnuncio(60, arguments.callee, "Inserta el precio de tu anuncio:", "La mayoría de los portales de anuncios, requieren que introduzcas el precio.");
    nuevoAnuncioOpcionesDiv.innerHTML = '';
    nuevoAnuncioOpcionesDiv.innerHTML += '	<span class="pequenonegrita">Sin puntos ni comas, sólo números.</span><br> ';
    nuevoAnuncioOpcionesDiv.innerHTML += ' <input id="precioNuevoAnuncio" style="WIDTH: 100px;" type="text" maxLength="10" NAME="precioNuevoAnuncio" value="' + precioNuevoAnuncio + '"/>&nbsp;&nbsp;€';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br><br>';

    AnadirBotonContinuar(function() {
        precioNuevoAnuncio = trim(document.getElementById('precioNuevoAnuncio').value);

        if (precioNuevoAnuncio == "") alert("Debes insertar el precio.");
        else if (!IsNumeric(precioNuevoAnuncio)) alert("El precio no es un número correcto. Introduce sólamente numeros, sin puntos ni comas.");
        else NuevoAnuncioInsertarDatosDeContactoNombreYTelefono();
    });
}

var URLApoyo = "";

function NuevoAnuncioInsertarDatosDeContactoNombreYTelefono() {
    InicializarPasoNuevoAnuncio(70, arguments.callee, "Introduce tus datos de contacto:", "Estos datos serán usados para que la gente pueda contactar contigo.");

    if (modoEdicion) {
        URLApoyo = URLNuevoAnuncio;
    }

    if (ocultarTelefonoNuevoAnuncio == null) {
        ocultarTelefonoNuevoAnuncio = false;
    }
    var strOcultarTelefonoNuevoAnuncio = "";
    if (ocultarTelefonoNuevoAnuncio == 0)
        strOcultarTelefonoNuevoAnuncio = '&nbsp;&nbsp;<input type="checkbox" id="ocultartelefonoNuevoAnuncio"  NAME="ocultartelefonoNuevoAnuncio"/><label for="ocultartelefonoNuevoAnuncio">&nbsp;Ocultar mi número de teléfono en los anuncios.</label>';
    else
        strOcultarTelefonoNuevoAnuncio = '&nbsp;&nbsp;<input type="checkbox" id="ocultartelefonoNuevoAnuncio" checked="checked" NAME="ocultartelefonoNuevoAnuncio"/><label for="ocultartelefonoNuevoAnuncio">&nbsp;Ocultar mi número de teléfono en los anuncios.</label>';
    nuevoAnuncioOpcionesDiv.innerHTML = '';
    nuevoAnuncioOpcionesDiv.innerHTML += '	<label for="nombreNuevoAnuncio">Tu nombre:</label><br><input id="nombreNuevoAnuncio" style="WIDTH: 200px" type="text" maxLength=50 NAME="nombreNuevoAnuncio" value="' + nombreUsuario + '"/>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<p>';
    nuevoAnuncioOpcionesDiv.innerHTML += '	<label for="telefonoNuevoAnuncio">Tu teléfono:</label><span class="pequenonegrita">&nbsp;(nueve dígitos).</span><br><input maxLength=9 id="telefonoNuevoAnuncio" style="WIDTH: 200px" type="text" NAME="telefonoNuevoAnuncio" value="' + telefonoUsuario + '"/>' + strOcultarTelefonoNuevoAnuncio;
    nuevoAnuncioOpcionesDiv.innerHTML += '</p>';

    nuevoAnuncioOpcionesDiv.innerHTML += '<p>';
    nuevoAnuncioOpcionesDiv.innerHTML += '	<label for="URLNuevoAnuncio">¿Tienes páginas web?</label><br><input id="URLNuevoAnuncio" style="WIDTH: 200px" type="text" maxLength=100 NAME="URLNuevoAnuncio" value="' + URLApoyo + '"/><span class="pequenonegrita">&nbsp;(ej. http://www.miempresa.com).</span>';
    nuevoAnuncioOpcionesDiv.innerHTML += '</p>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br>';
    nuevoAnuncioOpcionesDiv.innerHTML += '<br>';

    AnadirBotonContinuar(function() {
        URLNuevoAnuncio = trim($('URLNuevoAnuncio').value);
        URLApoyo = URLNuevoAnuncio;
        nombreUsuarioAux = trim($('nombreNuevoAnuncio').value);
        nombreNuevoAnuncio = trim($('nombreNuevoAnuncio').value);
        telefonoNuevoAnuncio = trim($('telefonoNuevoAnuncio').value);
        var primerDigitoTelefonoNuevoAnuncio = telefonoNuevoAnuncio.substring(0, 1);
        ocultarTelefonoNuevoAnuncio = ($('ocultartelefonoNuevoAnuncio').checked) ? "1" : "";
        nombreUsuario = nombreNuevoAnuncio;
        telefonoUsuario = telefonoNuevoAnuncio;

        if (nombreNuevoAnuncio == "") alert("Debes introducir tu nombre.");
        else if (nombreNuevoAnuncio.indexOf("'") > -1) alert("En el nombre solo se permiten caracteres alfanumericos y espacios");
        else if (!ValidaURL2(URLNuevoAnuncio) && URLNuevoAnuncio != '') alert("Debes introducir URL correcta");
        else if (telefonoNuevoAnuncio == "") alert("Debes introducir tu teléfono.");
        else if (!IsNumeric(telefonoNuevoAnuncio)) alert("El numero de teléfono solo puede contener números.");
        else if (telefonoNuevoAnuncio.length != 9) alert("El teléfono debe de ser un número de nueve dígitos.");
        else if (primerDigitoTelefonoNuevoAnuncio != 6 && primerDigitoTelefonoNuevoAnuncio != 9 && primerDigitoTelefonoNuevoAnuncio != 8) alert("El número de teléfono debe de comenzar por 6 o 9 o 8.");
        else NuevoAnuncioInsertarDatosDeContactoEmail();
    });
}

function NuevoAnuncioInsertarDatosDeContactoEmail() {

    if (primerAcceso || emailUsuario == "") {
        InicializarPasoNuevoAnuncio(75, arguments.callee, "Introduce tu dirección de email:", "Los usuarios contactarán mediante ésta dirección de email.");
        nuevoAnuncioOpcionesDiv.innerHTML += '	<label for="emailNuevoAnuncio">Tu email de contacto:</label><br><input id="emailNuevoAnuncio" style="WIDTH: 200px" type="text" maxLength=50 NAME="emailNuevoAnuncio" value="' + emailUsuario + '"/>';
        nuevoAnuncioOpcionesDiv.innerHTML += '<p>';
        nuevoAnuncioOpcionesDiv.innerHTML += '	<label for="repetiremailNuevoAnuncio">Repetir email:</label><br><input id="repetiremailNuevoAnuncio" style="WIDTH: 200px" type="text" maxLength=50 NAME="repetiremailNuevoAnuncio" value="' + emailUsuario + '"/>';
        nuevoAnuncioOpcionesDiv.innerHTML += '</p>';
        nuevoAnuncioOpcionesDiv.innerHTML += '<br><br>';

        AnadirBotonContinuar(function() {
            emailNuevoAnuncio = trim($('emailNuevoAnuncio').value);
            repetiremailNuevoAnuncio = trim($('repetiremailNuevoAnuncio').value);
            var myRequest = new Request({
                    url: '../registro/LoginUsuario.aspx',
                    data: 'email=' + trim($('emailNuevoAnuncio').value) + '&callback=CallbackEmaIlExistente',
                    evalResponse: true
                });
            myRequest.get();
        });
    } else {
        emailNuevoAnuncio = emailUsuario;
        repetiremailNuevoAnuncio = emailUsuario;
        NuevoAnuncioPreguntarInsertarImagenes();
    }

}

function CallbackEmaIlExistente(bEmailExiste) {
    if (nombreNuevoAnuncio == "") alert("Debes introducir tu nombre.");
    else if (emailNuevoAnuncio == "") alert("Debes introducir tu dirección de email.");
    else if (repetiremailNuevoAnuncio == "") alert("Debes repetir tu dirección de email en el campo Repetir Email.");
    else if (!isValidEmail(emailNuevoAnuncio)) alert("La dirección de email no es correcta. Verifícala.");
    else if (emailNuevoAnuncio != repetiremailNuevoAnuncio) alert("Las direcciones de email no coinciden. Verifícalas.");
    else if (bEmailExiste) alert("La dirección de email esta siendo utilizada.");
    else NuevoAnuncioPreguntarInsertarImagenes();
}

function NuevoAnuncioPreguntarInsertarImagenes() {

    if (modoEdicion) {
        NuevoAnuncioInsertarImagenes();
    } else {
        InicializarPasoNuevoAnuncio(80, arguments.callee, "¿Tienes fotografías de tu anuncio?", "Los anuncios con fotografías reciben más visitas que los que no las tienen.");
        AnadirOpcionAlListadoDeOpciones("Si", function() { NuevoAnuncioInsertarImagenes(); });
        AnadirOpcionAlListadoDeOpciones("No", function() {
            if (usuarioSinRegistrar) {
                GuardarUsuario();
            } else {
                NuevoAnuncioInsertando();
            }
        });
    }

}

function NuevoAnuncioInsertarImagenes() {
    if (modoEdicion) {
        InicializarPasoNuevoAnuncio(90, arguments.callee, "Selecciona las fotografías que quieres editar.", "Al menos una fotografía y como máximo cinco. La primera imagen, será la imagen principal de tu anuncio.");
    } else {
        InicializarPasoNuevoAnuncio(90, arguments.callee, "Selecciona las fotografías que quieres insertar.", "Al menos una fotografía y como máximo tres. La primera imagen, será la imagen principal de tu anuncio.");
    }
    var form = new Element('form');
    form.setAttribute("id", "formularioNuevoAnuncio");
    form.setAttribute("name", "formularioNuevoAnuncio");
    form.setAttribute("style", "height:220px; overflow: auto;");
    nuevoAnuncioOpcionesDiv.appendChild(form);

    if (modoEdicion && imagen1NuevoAnuncio != "") {
        var img1 = document.createElement("img");
        img1.setAttribute("style", "padding:0; width:60px; height:40px; border:0;");
        img1.setAttribute("src", imagen1NuevoAnuncio);
        var borrar1 = document.createElement("a");
        borrar1.setAttribute("href", "javascript:BorrarImagen('1')");
        borrar1.setAttribute("id", "borrar1");
        borrar1.innerHTML = '  Borrar Imagen';
    }
    var input1 = document.createElement("input");
    input1.setAttribute("type", "file");
    input1.setAttribute("id", "imagen1NuevoAnuncio");
    input1.setAttribute("name", "imagen1NuevoAnuncio");
    input1.setAttribute("onchange", "VerificarImagen(this.value);");
    var label1 = document.createElement("label");
    label1.innerHTML = "Imagen principal";
    label1.setAttribute("for", "imagen1NuevoAnuncio");

    form.appendChild(label1);
    form.appendChild(document.createElement("BR"));
    if (modoEdicion && imagen1NuevoAnuncio != "") {
        form.appendChild(img1);
        //form.appendChild(borrar1);
        form.appendChild(document.createElement("BR"));
    }
    form.appendChild(input1);
    form.appendChild(document.createElement("BR"));

    if (modoEdicion && imagen2NuevoAnuncio != "") {
        var img2 = document.createElement("img");
        img2.setAttribute("style", "padding:0; width:60px; height:40px; border:0;");
        img2.setAttribute("src", imagen2NuevoAnuncio);
        var borrar2 = document.createElement("a");
        borrar2.setAttribute("href", "javascript:BorrarImagen('2')");
        borrar2.setAttribute("id", "borrar2");
        borrar2.innerHTML = '  Borrar Imagen';
    }
    var input2 = document.createElement("input");
    input2.setAttribute("type", "file");
    input2.setAttribute("id", "imagen2NuevoAnuncio");
    input2.setAttribute("name", "imagen2NuevoAnuncio");
    input2.setAttribute("onchange", "VerificarImagen(this.value);");
    var label2 = document.createElement("label");
    label2.innerHTML = "Imagen 2";
    label2.setAttribute("for", "imagen2NuevoAnuncio");
    form.appendChild(label2);
    form.appendChild(document.createElement("BR"));
    if (modoEdicion && imagen2NuevoAnuncio != "") {
        form.appendChild(img2);
        form.appendChild(borrar2);
        form.appendChild(document.createElement("BR"));
    }
    form.appendChild(input2);
    form.appendChild(document.createElement("BR"));

    if (modoEdicion && imagen3NuevoAnuncio != "") {
        var img3 = document.createElement("img");
        img3.setAttribute("style", "padding:0; width:60px; height:40px; border:0;");
        img3.setAttribute("src", imagen3NuevoAnuncio);
        var borrar3 = document.createElement("a");
        borrar3.setAttribute("href", "javascript:BorrarImagen('3')");
        borrar3.setAttribute("id", "borrar3");
        borrar3.innerHTML = '  Borrar Imagen';
    }
    var input3 = document.createElement("input");
    input3.setAttribute("type", "file");
    input3.setAttribute("id", "imagen3NuevoAnuncio");
    input3.setAttribute("name", "imagen3NuevoAnuncio");
    input3.setAttribute("onchange", "VerificarImagen(this.value);");
    var label3 = document.createElement("label");
    label3.innerHTML = "Imagen 3";
    label3.setAttribute("for", "imagen3NuevoAnuncio");
    form.appendChild(label3);
    form.appendChild(document.createElement("BR"));
    if (modoEdicion && imagen3NuevoAnuncio != "") {
        form.appendChild(img3);
        form.appendChild(borrar3);
        form.appendChild(document.createElement("BR"));
    }
    form.appendChild(input3);
    form.appendChild(document.createElement("BR"));

    if (modoEdicion && imagen4NuevoAnuncio != "") {
        var img4 = document.createElement("img");
        img4.setAttribute("style", "padding:0; width:60px; height:40px; border:0;");
        img4.setAttribute("src", imagen4NuevoAnuncio);
        var borrar4 = document.createElement("a");
        borrar4.setAttribute("href", "javascript:BorrarImagen('4')");
        borrar4.setAttribute("id", "borrar4");
        borrar4.innerHTML = '  Borrar Imagen';
    }
    var input4 = document.createElement("input");
    input4.setAttribute("type", "file");
    input4.setAttribute("id", "imagen4NuevoAnuncio");
    input4.setAttribute("name", "imagen4NuevoAnuncio");
    input4.setAttribute("onchange", "VerificarImagen(this.value);");
    var label4 = document.createElement("label");
    label4.innerHTML = "Imagen 4";
    label4.setAttribute("for", "imagen4NuevoAnuncio");
    form.appendChild(label4);
    form.appendChild(document.createElement("BR"));
    if (modoEdicion && imagen4NuevoAnuncio != "") {
        form.appendChild(img4);
        form.appendChild(borrar4);
        form.appendChild(document.createElement("BR"));
    }
    form.appendChild(input4);
    form.appendChild(document.createElement("BR"));

    if (modoEdicion && imagen5NuevoAnuncio != "") {
        var img5 = document.createElement("img");
        img5.setAttribute("style", "padding:0; width:60px; height:40px; border:0;");
        img5.setAttribute("src", imagen5NuevoAnuncio);
        var borrar5 = document.createElement("a");
        borrar5.setAttribute("href", "javascript:BorrarImagen('5')");
        borrar5.setAttribute("id", "borrar5");
        borrar5.innerHTML = '  Borrar Imagen';
    }
    var input5 = document.createElement("input");
    input5.setAttribute("type", "file");
    input5.setAttribute("id", "imagen5NuevoAnuncio");
    input5.setAttribute("name", "imagen5NuevoAnuncio");
    input5.setAttribute("onchange", "VerificarImagen(this.value);");
    var label5 = document.createElement("label");
    label5.innerHTML = "Imagen 5";
    label5.setAttribute("for", "imagen5NuevoAnuncio");
    form.appendChild(label5);
    form.appendChild(document.createElement("BR"));
    if (modoEdicion && imagen5NuevoAnuncio != "") {
        form.appendChild(img5);
        form.appendChild(borrar5);
        form.appendChild(document.createElement("BR"));
    }
    form.appendChild(input5);
    form.appendChild(document.createElement("BR"));

    form.appendChild(document.createElement("BR"));

    AnadirBotonContinuar(function() {
        if (modoEdicion) {
            imagen1NuevoAnuncio = $('imagen1NuevoAnuncio');
            imagen2NuevoAnuncio = $('imagen2NuevoAnuncio');
            imagen3NuevoAnuncio = $('imagen3NuevoAnuncio');
            imagen4NuevoAnuncio = $('imagen4NuevoAnuncio');
            imagen5NuevoAnuncio = $('imagen5NuevoAnuncio');
            if (usuarioSinRegistrar) {
                GuardarUsuario(form);
            } else {
                NuevoAnuncioInsertando(form);
            }
        } else {
            imagen1NuevoAnuncio = $('imagen1NuevoAnuncio');
            imagen2NuevoAnuncio = $('imagen2NuevoAnuncio');
            imagen3NuevoAnuncio = $('imagen3NuevoAnuncio');
            imagen4NuevoAnuncio = $('imagen4NuevoAnuncio');
            imagen5NuevoAnuncio = $('imagen5NuevoAnuncio');

            if (imagen1NuevoAnuncio.value == "") alert("No has seleccionado ninguna imágen como principal. Si no deseas insetar imágenes pincha en Retroceder");
            else if (imagen1NuevoAnuncio.value != "" && !VerificarImagen(imagen1NuevoAnuncio.value)) alert("La imagen principal no es correcta.");
            else if (imagen2NuevoAnuncio.value != "" && !VerificarImagen(imagen2NuevoAnuncio.value)) alert("La imagen 2 no es correcta.");
            else if (imagen3NuevoAnuncio.value != "" && !VerificarImagen(imagen3NuevoAnuncio.value)) alert("La imagen 3 no es correcta.");
            else if (imagen4NuevoAnuncio.value != "" && !VerificarImagen(imagen4NuevoAnuncio.value)) alert("La imagen 4 no es correcta.");
            else if (imagen5NuevoAnuncio.value != "" && !VerificarImagen(imagen5NuevoAnuncio.value)) alert("La imagen 5 no es correcta.");
            else {
                if (usuarioSinRegistrar) {
                    GuardarUsuario(form);
                } else {
                    NuevoAnuncioInsertando(form);
                }
            }
        }
    });
}

var imagen1NuevoAnuncioBorrar = false;
var imagen2NuevoAnuncioBorrar = false;
var imagen3NuevoAnuncioBorrar = false;
var imagen4NuevoAnuncioBorrar = false;
var imagen5NuevoAnuncioBorrar = false;

function BorrarImagen(imagenBorrar) {


    switch (imagenBorrar) {
    case '1':
        imagen1NuevoAnuncioBorrar = true;
        $('borrar1').innerHTML = "  Imagen 1 sera Borrada.";
        break;
    case '2':
        imagen2NuevoAnuncioBorrar = true;
        $('borrar2').innerHTML = "  Imagen 2 sera Borrada.";
        break;
    case '3':
        imagen3NuevoAnuncioBorrar = true;
        $('borrar3').innerHTML = "  Imagen 3 sera Borrada.";
        break;
    case '4':
        imagen4NuevoAnuncioBorrar = true;
        $('borrar4').innerHTML = "  Imagen 4 sera Borrada.";
        break;
    case '5':
        imagen5NuevoAnuncioBorrar = true;
        $('borrar5').innerHTML = "  Imagen 5 sera Borrada.";
        break;
    }
}

function NuevoAnuncioInsertando(formulario) {
    // Esto hay que hacer estas cosas raras porque si no no funciona correctamente.	
    DesactivarBotonRetroceder();
    EstablecerBarraProgreso(90);
    //pasosAnteriores.push(funcionAnterior);
    EstablecerTituloNuevoAnuncio("Terminado. Insertando anuncio ...");
    EstablecerSubtituloNuevoAnuncio((formulario) ? "Dependiendo del tamaño de las imágenes que has seleccionado y de la velocidad de tu conexión, es posíble que se pueda demorar." : "");

    var form = (formulario) ? formulario : new Element('form');
    if (!formulario) {
        nuevoAnuncioOpcionesDiv.innerHTML = "";
        nuevoAnuncioOpcionesUl.innerHTML = "";
        nuevoAnuncioOpcionesDiv.appendChild(form);
    } else {
        nuevoAnuncioOpcionesDiv.removeChild($("botoncontinuar"));
        if (!esExplorer) form.style.display = "none";
    }

    var img = document.createElement("img");
    img.setAttribute("style", "margin-top:90px;position:absolute;left:40%;");
    img.setAttribute("src", "../images/loading.gif");
    nuevoAnuncioOpcionesDiv.appendChild(img);

    var iframe = new IFrame({
            id: 'iframeupload',
            name: 'iframeupload',
            src: '#',
            styles: { 'display': 'none', 'height': '0', 'width': '0', 'border': '0' }
        });

    nuevoAnuncioOpcionesDiv.appendChild(iframe);
    form.setAttribute("target", "iframeupload");
    form.setAttribute("accept-charset", "UTF-8");
    form.setAttribute("method", "post");
    form.setAttribute("action", "guardaranuncio.aspx");
    form.setAttribute("enctype", "multipart/form-data");
    form.setAttribute("encoding", "multipart/form-data");
    form.setAttribute("id", "formularioNuevoAnuncio");
    form.setAttribute("name", "formularioNuevoAnuncio");
    if (modoEdicion) AnadirInputAlFormulario(form, "hidden", "idAnuncio", idAnuncio);
    AnadirInputAlFormulario(form, "hidden", "idUsuario", idUsuario);
    AnadirInputAlFormulario(form, "hidden", "categoriaNuevoAnuncio", categoriaNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "subcategoriaNuevoAnuncio", subcategoriaNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "provinciaNombreNuevoAnuncio", provinciaNombreNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "provinciaCodigoNuevoAnuncio", provinciaCodigoNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "poblacionNombreNuevoAnuncio", poblacionNombreNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "poblacionCodigoNuevoAnuncio", poblacionCodigoNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "codigoPostalNuevoAnuncio", codigoPostalNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "particularOEmpresaNuevoAnuncio", particularOEmpresaNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "ofertaDemandaNuevoAnuncio", ofertaDemandaNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "titulo1NuevoAnuncio", titulo1NuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "titulo2NuevoAnuncio", titulo2NuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "descripcion1NuevoAnuncio", descripcion1NuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "descripcion2NuevoAnuncio", descripcion2NuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "precioNuevoAnuncio", precioNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "nombreNuevoAnuncio", nombreNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "emailNuevoAnuncio", emailNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "URLNuevoAnuncio", URLNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "telefonoNuevoAnuncio", telefonoNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "ocultarTelefonoNuevoAnuncio", ocultarTelefonoNuevoAnuncio);
    AnadirInputAlFormulario(form, "hidden", "aux1", aux1);
    AnadirInputAlFormulario(form, "hidden", "aux2", aux2);
    AnadirInputAlFormulario(form, "hidden", "aux3", aux3);
    AnadirInputAlFormulario(form, "hidden", "aux4", aux4);
    AnadirInputAlFormulario(form, "hidden", "aux5", aux5);
    AnadirInputAlFormulario(form, "hidden", "aux6", aux6);
    AnadirInputAlFormulario(form, "hidden", "aux7", aux7);
    AnadirInputAlFormulario(form, "hidden", "aux8", aux8);
    AnadirInputAlFormulario(form, "hidden", "usuarioSinRegistrar", usuarioSinRegistrar);
    if (imagen2NuevoAnuncioBorrar) AnadirInputAlFormulario(form, "hidden", "imagen2NuevoAnuncioBorrar", imagen2NuevoAnuncioBorrar);
    if (imagen3NuevoAnuncioBorrar) AnadirInputAlFormulario(form, "hidden", "imagen3NuevoAnuncioBorrar", imagen3NuevoAnuncioBorrar);
    if (imagen4NuevoAnuncioBorrar) AnadirInputAlFormulario(form, "hidden", "imagen4NuevoAnuncioBorrar", imagen4NuevoAnuncioBorrar);
    if (imagen5NuevoAnuncioBorrar) AnadirInputAlFormulario(form, "hidden", "imagen5NuevoAnuncioBorrar", imagen5NuevoAnuncioBorrar);

    function AnadirInputAlFormulario(form, inputType, inputId, value) {
        var input = document.createElement("input");
        input.setAttribute("type", inputType);
        input.setAttribute("id", inputId);
        input.setAttribute("name", inputId);
        input.setAttribute("value", value);
        form.appendChild(input);
        return input;
    }

    idUsuarioMCorreo = idUsuario;

    if (emailUsuario == "") {
        emailUsuario = emailNuevoAnuncio;
        telefonoUsuario = telefonoNuevoAnuncio;
        nombreUsuario = nombreNuevoAnuncio;
        ocultarTelefonoUsuario = (ocultarTelefonoNuevoAnuncio == "1");
    }

    if (categoriaNuevoAnuncio != CATEGORIA_INMOBILIARIA && ofertaDemandaNuevoAnuncio == 3 || emailNuevoAnuncio == "") {
        SexyLightbox.close();
        Sexy.alert("Lo sentimos, ha habido un error en la aplicación, inténtelo de nuevo en unos minutos.");
    } else {
        form.submit();
    }
}

function NuevoAnuncioAnuncioInsertado(anuncio) {

    ControlVentanaNuevoAnuncio(false);

    ObtenerAnuncioAnadirYMostrar(anuncio);
    if (modoEdicion) {
        InicializarPasoNuevoAnuncio(100, arguments.callee, "Enhorabuena, tu anuncio se ha actualizado correctamente.", "");
        modoEdicion = false;
    } else {
        InicializarPasoNuevoAnuncio(100, arguments.callee, "Enhorabuena, tu anuncio se ha insertado correctamente.", "");
    }

    if (primerAcceso) {
        nuevoAnuncioOpcionesDiv.innerHTML = '<p>';
        nuevoAnuncioOpcionesDiv.innerHTML += '<font color="red">Se le ha enviado un email, para confirmar su dirección de correo electrónico. Una vez lo haya confirmado, podrá comenzar a publicar en los portales.</font>';
        nuevoAnuncioOpcionesDiv.innerHTML += '</p>';
        if (!usuarioSinRegistrar) ReenvioEmailConfirmacion();
    } else {
        nuevoAnuncioOpcionesDiv.innerHTML = '<p>';
        nuevoAnuncioOpcionesDiv.innerHTML += 'A continuación puedes comenzar a insertar tu anuncio en los distintos portales. Puedes elegir los portales donde insertar tu anuncio, o insertar automáticamente en todos los portales disponibles.';
        nuevoAnuncioOpcionesDiv.innerHTML += '</p>';
    }
    nuevoAnuncioOpcionesDiv.innerHTML += '<br><br><br>';
    var botonContinuar = AnadirBotonContinuar(function() {
        if (primerAcceso) {
            primerAcceso = false;
            MostrarAsistente();
        }
        SexyLightbox.close();
        parent.location.reload();
    });

    botonContinuar.style.marginLeft = "270px";
    botonContinuar.innerHTML = "<span>Finalizar</span>";
}

function ReenvioEmailConfirmacion() {
//correo
    var myRequest = new Request({
            url: 'verificacionemail.aspx',
            data: 'idUsuario=' + idUsuarioMCorreo + '&emailNuevoAnuncio=' + emailUsuario + '&Enviar=ok&Paso=1',
            evalResponse: true
        });
    myRequest.get();
}

function AnadirOpcionAlListadoDeOpciones(texto, funcion) {
    var li = new Element('li', {
        'html': texto,
        'class': 'opcion',
        'events': { 'click': funcion ? funcion : void(0) }
    });
    nuevoAnuncioOpcionesUl.appendChild(li);
    return li;
}

function AnadirBotonContinuar(funcion) {
    var div = new Element('button', {
        'id': 'botoncontinuar',
        'html': '<span>Continuar ></span>',
        'class': 'rounded',
        'events': { 'click': funcion }
    });
    disableSelection(div);
    nuevoAnuncioOpcionesDiv.appendChild(div);
    return div;
}


function InicializarPasoNuevoAnuncio(porcentaje, funcionAnterior, titulo, subtitulo) {
    LimpiarNuevoAnuncio();
    EstablecerBarraProgreso(porcentaje);
    pasosAnteriores.push(funcionAnterior);
    if (titulo) EstablecerTituloNuevoAnuncio(titulo);
    if (subtitulo) EstablecerSubtituloNuevoAnuncio(subtitulo);
}

function LimpiarNuevoAnuncio() {
    $("nuevoAnuncioTitulo").innerHTML = "";
    $("nuevoAnuncioSubTitulo").innerHTML = "";
    nuevoAnuncioOpcionesDiv.innerHTML = "";
    nuevoAnuncioOpcionesUl.innerHTML = "";
}

function EstablecerBarraProgreso(porcentaje) {
    $("barraProgreso").innerHTML = "&nbsp;&nbsp;&nbsp;" + ((porcentaje == 100) ? "COMPLETO" : ("Completado: " + porcentaje + " %"));
    $("barraProgreso").style.width = porcentaje + "%";
}

function BotonRetrocederClick() {
    if (pasosAnteriores.length > 1) {
        pasosAnteriores.pop();
        var funcionAnterior = pasosAnteriores.pop();
        return funcionAnterior();
    }
}

function EstablecerTituloNuevoAnuncio(titulo) {
    $("nuevoAnuncioTitulo").innerHTML = titulo;
}

function EstablecerSubtituloNuevoAnuncio(subtitulo) {

    $("nuevoAnuncioSubTitulo").innerHTML = subtitulo;

}

function ActivarBotonRetroceder() {
    //$("divNuevoAnuncioBotones").style.display="block";
    $("linkNuevoAnuncioRetroceder").style.color = "#FF7700";
    //$("linkNuevoAnuncioRetroceder").enabled = true;
    //$("linkNuevoAnuncioRetroceder").style.visibility ="visible";
    $("linkNuevoAnuncioRetroceder").setAttribute("href", "javascript:BotonRetrocederClick();");
    $("linkNuevoAnuncioRetroceder").setAttribute("class", "");
}

function DesactivarBotonRetroceder() {
    //$("divNuevoAnuncioBotones").style.display="none";
    $("linkNuevoAnuncioRetroceder").style.color = "gray";
    //$("linkNuevoAnuncioRetroceder").enabled = false;
    //EstablecerBotonRetroceder(function(){});
    //$("linkNuevoAnuncioRetroceder").style.visibility ="hidden";
    $("linkNuevoAnuncioRetroceder").setAttribute("href", "javascript:void(0);");

    $("linkNuevoAnuncioRetroceder").setAttribute("class", "botonRetrocederDesactivado");

}


function Opciones() {
    ComprobarSaldoBBDDOpciones();
}

function DatosUsuarioModificar() {
    if (tipo == 1 || tipo == 2 && diasRestantesSuscripcion == '0' || tipo == 3 && diasRestantesSuscripcion == '0') {
        $("divTipoUsuario").innerHTML = "<img src='../images/btnGratuito.png' alt='' />";
        $("divConvertirUsuario").innerHTML = "<a href='javascript:AbrirRecargarSaldo();'><img src='../images/btnConvertirPremium.png' alt='' /></a>";
    } else if (tipo == 2) {
        $("divTipoUsuario").innerHTML = "<img src='../images/btnPremium.png' alt='' />";
        $("divConvertirUsuario").innerHTML = "<a href='javascript:AbrirRecargarSaldoPlus();'><img src='../images/btnConvertirPlus.png' alt='' /></a>";
    } else if (tipo == 3) {
        $("divTipoUsuario").innerHTML = "<img src='../images/btnPlus.png' alt='' />";
        $("divConvertirUsuario").style.display = "none";
    }


    var label1 = document.createElement("label");
    label1.innerHTML = nombreUsuario;
    label1.setAttribute("id", "nombreMostrar");

    var label2 = document.createElement("label");
    label2.innerHTML = telefonoUsuario;
    label2.setAttribute("id", "telefonoMostrar");

    var label3 = document.createElement("label");
    label3.innerHTML = emailUsuario;
    label3.setAttribute("id", "emailMostrar");

    var label4 = document.createElement("label");
    label4.innerHTML = (EmailVerificado) ? "  (Confirmado)" : "  (Sin Confirmar)";
    label4.setAttribute("id", "confirmadoMostrar");
    if (EmailVerificado) {
        //label4.style.float="left";//label4.setAttribute('style', 'float:left; font-weight:bold; color:green;');
        label4.style.fontWeight = "bold";
        label4.style.color = "green";
        label4.style.fontSize = "9px";
    } else {
        //label4.setAttribute('style', 'float:left; font-weight:bold; color:red;');
        //label4.style.float="left";
        label4.style.fontWeight = "bold";
        label4.style.color = "red";
        label4.style.fontSize = "9px";
    }
    $('tdOpcionesNombre').appendChild(label1);
    $('tdOpcionesTelefono').appendChild(label2);
    $('tdOpcionesEmail').appendChild(label3);
    $('tdOpcionesEmail').appendChild(label4); //$('tdOpcionesConfirmado').appendChild(label4);
    if (diasRestantesSuscripcion == '0') {
        $('saldo').style.fontWeight = "bold";
        $('saldo').style.color = "red";
        $('saldo').innerHTML = "Desactivado";
    } else {
        $('saldo').style.fontWeight = "bold";
        $('saldo').style.color = "green";
        $('saldo').innerHTML = "Activado";
    }
}

function ModificarDatos() {

    $("tdOpcionesNombre").removeChild($("nombreMostrar"));
    $('tdOpcionesTelefono').removeChild($("telefonoMostrar"));
    $('tdOpcionesEmail').removeChild($("emailMostrar"));
    $('tdOpcionesEmail').removeChild($("confirmadoMostrar"));

    var input1 = document.createElement("input");
    input1.setAttribute("type", "text");
    input1.setAttribute("id", "nombreMostrar");
    input1.setAttribute("name", "nombreMostrar");
    input1.setAttribute("maxLength", "30");
    input1.setAttribute("size", "30");
    input1.setAttribute("value", nombreUsuario);
    input1.setAttribute("class", "modDatosUsuario");
    var input2 = document.createElement("input");
    input2.setAttribute("type", "text");
    input2.setAttribute("id", "telefonoMostrar");
    input2.setAttribute("name", "telefonoMostrar");
    input2.setAttribute("maxLength", "9");
    input2.setAttribute("size", "30");
    input2.setAttribute("value", telefonoUsuario);
    input2.setAttribute("class", "modDatosUsuario");
    var input3 = document.createElement("input");
    input3.setAttribute("type", "text");
    input3.setAttribute("id", "emailMostrar");
    input3.setAttribute("name", "emailMostrar");
    input3.setAttribute("maxLength", "100");
    input3.setAttribute("size", "30");
    input3.setAttribute("value", emailUsuario);
    input3.setAttribute("class", "modDatosUsuario");
    $("aOpcionesModificar").setAttribute("href", "javascript:AceptarDatos();");
    $("aOpcionesModificar").innerHTML = "&nbsp;Aceptar";
    var a = document.createElement("a");
    a.innerHTML = "&nbsp;Cancelar";
    a.setAttribute('style', 'padding-left:5px;');
    a.setAttribute('id', 'cancelarModificar');
    a.setAttribute("href", "javascript:CancelarModificar();");

    $('tdOpcionesNombre').appendChild(input1);
    $('tdOpcionesTelefono').appendChild(input2);
    $('tdOpcionesEmail').appendChild(input3);
    $('tdOpcionesModificar').appendChild(a);
    $('hAbrirDatos').innerHTML = anuncioModoEdicion.nombre;
}

function AceptarDatos() {
    var evalEmail = $('emailMostrar').value;
    var primerDigitoTelefonoNuevoAnuncio = $('telefonoMostrar').value.substring(0, 1);
    if (!isValidEmail(evalEmail)) alert("La dirección de email no es correcta. Verifícala.");
    else if ($('telefonoMostrar').value == "") alert("Debes introducir tu teléfono.");
    else if (!IsNumeric($('telefonoMostrar').value)) alert("El numero de teléfono solo puede contener números.");
    else if ($('telefonoMostrar').value.length != 9) alert("El teléfono debe de ser un número de nueve dígitos.");
    else if (primerDigitoTelefonoNuevoAnuncio != 6 && primerDigitoTelefonoNuevoAnuncio != 9 && primerDigitoTelefonoNuevoAnuncio != 8) alert("El número de teléfono debe de comenzar por 6 o 9 o 8.");
    else {
        $('tdOpcionesMensajeConfirmacion').setAttribute('style', 'font-weight:bold; color: red;');
        if ($('emailMostrar').value != emailUsuario) {
            EmailVerificado = false;
            //$('confirmadoMostrar').innerHTML="Sin Confirmar";
            $('tdOpcionesMensajeConfirmacion').innerHTML = "Se le ha enviado un email, para confirmar su dirección de correo electrónico.";
            $('tdOpcionesMensajeConfirmacion').style.fontSize = "10px";
            var myRequest = new Request({
                    url: 'verificacionemail.aspx',
                    data: 'ModificarDatos=aceptado&idUsuario=' + idUsuario + '&emailNuevoAnuncio=' + $('emailMostrar').value + '&nombreUsuario=' + $('nombreMostrar').value + '&telefonoUsuario=' + $('telefonoMostrar').value + '&ocultarTelefonoUsuario=' + anuncioModoEdicion.ocultartelefono + '&Paso=3',
                    evalResponse: true
                });
            myRequest.get();
        } else {
            //EmailVerificado = true;
            $('tdOpcionesMensajeConfirmacion').innerHTML = "Datos modificados.";
            var myRequest = new Request({
                    url: 'verificacionemail.aspx',
                    data: 'ModificarDatos=noModificado&idUsuario=' + idUsuario + '&emailNuevoAnuncio=' + emailUsuario + '&nombreUsuario=' + $('nombreMostrar').value + '&telefonoUsuario=' + $('telefonoMostrar').value + '&ocultarTelefonoUsuario=' + anuncioModoEdicion.ocultartelefono,
                    evalResponse: true
                });
            myRequest.get();
        }
        anuncioModoEdicion.nombre = $("nombreMostrar").value;
        nombreUsuario = anuncioModoEdicion.nombre;
        anuncioModoEdicion.telefono = $("telefonoMostrar").value;
        telefonoUsuario = anuncioModoEdicion.telefono;
        emailUsuario = $("emailMostrar").value;
        $("tdOpcionesNombre").removeChild($("nombreMostrar"));
        $('tdOpcionesTelefono').removeChild($("telefonoMostrar"));
        $('tdOpcionesEmail').removeChild($("emailMostrar"));
//$('tdOpcionesConfirmado').innerHTML ='';//removeChild($("confirmadoMostrar"));
        $('tdOpcionesModificar').removeChild($('cancelarModificar'));
        $("aOpcionesModificar").setAttribute("href", "javascript:ModificarDatos();");
        $("aOpcionesModificar").innerHTML = "Modificar";
        DatosUsuarioModificar();
    }
}

function CancelarModificar() {
    $("tdOpcionesNombre").removeChild($("nombreMostrar"));
    $('tdOpcionesTelefono').removeChild($("telefonoMostrar"));
    $('tdOpcionesEmail').removeChild($("emailMostrar"));
    $('tdOpcionesModificar').removeChild($("cancelarModificar"));
//$('tdOpcionesConfirmado').innerHTML ='';//removeChild($("confirmadoMostrar"));
    $("aOpcionesModificar").setAttribute("href", "javascript:ModificarDatos();");
    $("aOpcionesModificar").innerHTML = "&nbsp;Modificar";
    DatosUsuarioModificar();
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function ObtenerAnuncioAnadirYMostrar(anuncio) {
    var itemListado = AnadirAnuncioAlListado(anuncio);
    ClickEnAnuncioDelListado(itemListado);
}

function ObtenerDatosDeAnuncio(idAnuncio) {
    $("contentcontent").innerHTML = "Cargando ...";
    $("rightcontent").innerHTML = "";
    $("seleccionar").innerHTML = "";
    $("insertarportales").innerHTML = "";

    var url = rutaDeLaAplicacion + 'usuarios/ObtenerDatosAnuncio.aspx?idAnuncio=' + idAnuncio + '&callback=CallbackObtenerDatosDeAnuncio';
    cs(url);
}


function CallbackObtenerDatosDeAnuncio(anuncio) {
    //ProgramarActivado = 'false';
    if (anuncio.mostrarBotonBorrar != null) {
        if (anuncio.mostrarBotonBorrar != '0' || numeroAnunciosUsuario > numMaxAnuncios) {
//            if (tipo == 1 && numeroAnunciosUsuario <= numMaxAnuncios) {
//                mostrarBotonBorrar = false;
//            } else {
                mostrarBotonBorrar = true;
//            }
        } else {
            mostrarBotonBorrar = false;
        }
    }
    if (anuncio.existeAnuncioProgramar != null) {
        ProgramarActivado = anuncio.existeAnuncioProgramar;
        ProgramarAnuncios(anuncio);
    }
    MostrarPortalesParaInsertar(anuncio);
    MostrarDatosDeAnuncio(anuncio);
    anuncioModoEdicion = anuncio;
}

function AnadirAnuncioAlListado(anuncio) {
    //var box_anuncio = document.createElement("div");
    if (modoEdicion) {
        var leftcontent = $("leftcontent");
        $("contentcontent").innerHTML = "";
        $("rightcontent").innerHTML = "";
        $("seleccionar").innerHTML = "";
        $("insertarportales").innerHTML = "";
        leftcontent.removeChild(anuncioSeleccionado);
        anuncioSeleccionado = "";
    }
    var box_anuncio = new Element('div', {
        'id': anuncio.idAnuncio,
        'class': 'roundedcornr_box_anuncio'/*,		
		
		,
		'events':{
			'click':function(){
				ClickEnAnuncioDelListado(this);
				
			},
			'mouseover':function(){
				//if(box_anuncio!=anuncioSeleccionado){
				//	box_anuncio.className="roundedcornr_box_anuncio_hover";
				//	roundedcornr_top_anuncio.className= "roundedcornr_top_anuncio_hover";
				//	roundedcornr_bottom_anuncio.className= "roundedcornr_bottom_anuncio_hover";
				//}
				
			}
		}*/
    });

    var roundedcornrTopAnuncio = document.createElement("div");
    var roundedcornrContentAnuncio = document.createElement("div");
    var roundedcornrBottomAnuncio = document.createElement("div");

    box_anuncio.className = "roundedcornr_box_anuncio";
    roundedcornrTopAnuncio.className = "roundedcornr_top_anuncio";
    roundedcornrContentAnuncio.className = "roundedcornr_content_anuncio";
    roundedcornrBottomAnuncio.className = "roundedcornr_bottom_anuncio";

    var div = document.createElement("div");

    div.innerHTML = anuncio.titulo2;
    roundedcornrContentAnuncio.appendChild(div);
    //roundedcornr_content_anuncio.innerHTML = anuncio.titulo1;		
    disableSelection(roundedcornrContentAnuncio);

    roundedcornrTopAnuncio.appendChild(document.createElement("div"));
    box_anuncio.appendChild(roundedcornrTopAnuncio);
    box_anuncio.appendChild(roundedcornrContentAnuncio);
    roundedcornrBottomAnuncio.appendChild(document.createElement("div"));
    box_anuncio.appendChild(roundedcornrBottomAnuncio);

    //box_anuncio.setAttribute("id",anuncio.idAnuncio);

    /*var img = document.createElement("img");
	img.setAttribut("src",((anuncio.thumbnail!='')?anuncio.thumbnail:""));
	*/
    box_anuncio.anuncio = anuncio;
    $("leftcontent").insertBefore(box_anuncio, $("leftcontent").firstChild);

    box_anuncio.addEvent('click', function() {
        ClickEnAnuncioDelListado(box_anuncio);
    });

    box_anuncio.addEvent('mouseover', function() {
        if (box_anuncio != anuncioSeleccionado) {
            //box_anuncio.className="roundedcornr_box_anuncio_hover";
            //roundedcornr_top_anuncio.className= "roundedcornr_top_anuncio_hover";
            //roundedcornr_bottom_anuncio.className= "roundedcornr_bottom_anuncio_hover";
        }
    });
    box_anuncio.addEvent('mouseout', function() {
        if (box_anuncio != anuncioSeleccionado) {
            box_anuncio.className = "roundedcornr_box_anuncio";
            roundedcornrTopAnuncio.className = "roundedcornr_top_anuncio";
            roundedcornrBottomAnuncio.className = "roundedcornr_bottom_anuncio";
        }
    });

    return box_anuncio;
}

var anuncioSeleccionado = "";

function ClickEnAnuncioDelListado(div) {
    if (anuncioSeleccionado != div) {
        if (anuncioSeleccionado != "") {
            DeselecttionarItemDeListado(anuncioSeleccionado);
        }
        div.className = "roundedcornr_box_anuncio_selected";
        div.childNodes[0].className = "roundedcornr_top_anuncio_selected";
        div.childNodes[1].className = "roundedcornr_content_anuncio_selected";
        div.childNodes[2].className = "roundedcornr_bottom_anuncio_selected";

        ObtenerDatosDeAnuncio(div.anuncio.idAnuncio);
        anuncioSeleccionado = div;
    }

}

function DeselecttionarItemDeListado(div) {
    div.className = "roundedcornr_box_anuncio";
    div.childNodes[0].className = "roundedcornr_top_anuncio";
    div.childNodes[1].className = "roundedcornr_content_anuncio";
    div.childNodes[2].className = "roundedcornr_bottom_anuncio";
}

var enlaceAnuncioCompartir;
var tituloAnuncioCompartir;

function MostrarDatosDeAnuncio(anuncio) {

    function CrearImagen(container, urlimagen) {
        var link = document.createElement("a");
        link.setAttribute("href", urlimagen);
        link.setAttribute("rel", "sexylightbox[group1]");
        var imagen = document.createElement("img");
        imagen.setAttribute("src", urlimagen);
        link.appendChild(imagen);
        container.appendChild(link);
    }

    function CrearYAdjuntarDiv(container, divId, innerHTML) {
        var div = document.createElement("div");
        div.setAttribute("id", divId);
        div.innerHTML = innerHTML;
        container.appendChild(div);
        return div;
    }

    var contentcontent = $("contentcontent");
    contentcontent.innerHTML = "";

    CrearYAdjuntarDiv(contentcontent, "titulo1", anuncio.titulo1);
    /*CrearYAdjuntarDiv(contentcontent,"mostrartituloabreviado", '<a href="javascript:void(0);" onclick=$("titulo2").style.display="block";this.style.display="none";>Título abreviado</a>');
	CrearYAdjuntarDiv(contentcontent,"titulo2", anuncio.titulo2).style.display="none";
	*/
    CrearYAdjuntarDiv(contentcontent, "poblacionProvincia", anuncio.poblacionNombre + " (" + anuncio.provinciaNombre + ")");
    if (anuncio.precio != '0') {
        CrearYAdjuntarDiv(contentcontent, "precio", "Precio: " + anuncio.precio + " &euro;");
    }

    switch (anuncio.categoria) {
    case CATEGORIA_INMOBILIARIA:
        {
            if (anuncio.subcategoria == 1 || anuncio.subcategoria == 2 || anuncio.subcategoria == 3) {
                CrearYAdjuntarDiv(contentcontent, "opcionesespeciales", anuncio.aux1 + "m<sup>2</sup> " + anuncio.aux2 + " dormitorios " + anuncio.aux3 + " baños " + anuncio.aux4 + "planta.");
            } else if (anuncio.subcategoria == 4 || anuncio.subcategoria == 5 || anuncio.subcategoria == 7) {
                CrearYAdjuntarDiv(contentcontent, "opcionesespeciales", anuncio.aux1 + "m<sup>2</sup> Situación:" + anuncio.aux7);
            } else if (anuncio.subcategoria == 6) {
                // alquiler o venta de plaza de garaje
            }
            break;
        }
    case CATEGORIA_MOTOR:
        {
            if (anuncio.subcategoria == 1 || anuncio.subcategoria == 2) {
                CrearYAdjuntarDiv(contentcontent, "opcionesespeciales", ((anuncio.subcategoria == 1) ? ObtenerMarcaDeCochePorCodigo(anuncio.aux1) : ObtenerMarcaDeMotoPorCodigo(anuncio.aux1)) + " " + anuncio.aux2 + ". Año: " + anuncio.aux3 + ". " + anuncio.aux4 + " Km. " + ((anuncio.aux5 == 0) ? "Gasolina." : (anuncio.aux5 == 1) ? "Diesel." : ""));
            }
            break;
        }
    case CATEGORIA_CONTACTOS:
        {
            CrearYAdjuntarDiv(contentcontent, "opcionesespeciales", "Edad: " + anuncio.aux1 + " años.");
            break;
        }
    }

    CrearYAdjuntarDiv(contentcontent, "descripcion1", anuncio.descripcion1 + '<br><a href="javascript:void(0);" onclick=javascript:$("descripcion2").style.display="block";this.style.display="none";>Ver abreviada</a>');
    CrearYAdjuntarDiv(contentcontent, "descripcion2", anuncio.descripcion2).style.display = "none";

    if (anuncio.imagen1 != '' || anuncio.imagen2 != '' || anuncio.imagen3 != '' || anuncio.imagen4 != '' || anuncio.imagen5 != '') {
        var containerImagenes = CrearYAdjuntarDiv(contentcontent, "containerimagenes", "");
        if (anuncio.imagen1 != '') CrearImagen(containerImagenes, anuncio.imagen1);
        if (anuncio.imagen2 != '') CrearImagen(containerImagenes, anuncio.imagen2);
        if (anuncio.imagen3 != '') CrearImagen(containerImagenes, anuncio.imagen3);
        if (anuncio.imagen4 != '') CrearImagen(containerImagenes, anuncio.imagen4);
        if (anuncio.imagen5 != '') CrearImagen(containerImagenes, anuncio.imagen5);
    }

    var enlaceAux = anuncio.titulo2.replace( / /g , "_") + "_" + anuncio.idAnuncio;

    enlaceAnuncioCompartir = rutaDeLaAplicacion + "anuncio/" + enlaceAux;
    ComprimirUrl(rutaDeLaAplicacion + "anuncio/" + enlaceAux);
    tituloAnuncioCompartir = anuncio.titulo2;
    CrearYAdjuntarDiv(contentcontent, "contacto", anuncio.nombre + "<br>" + anuncio.email + "<br>" + anuncio.telefono + ((anuncio.ocultartelefono == "True") ? "&nbsp;(ocultar)" : "") + "<br>" + anuncio.URL + "<br>");

    var controlAnuncioDiv = CrearYAdjuntarDiv(contentcontent, "controlAnuncioDiv", "");
    controlAnuncioDiv.setAttribute("id", "controlanuncio");
    
    var editarAnuncioDiv = CrearYAdjuntarDiv(controlAnuncioDiv, "editarAnuncioDiv", "");
    var editarAnuncioA = document.createElement("a");
    editarAnuncioA.setAttribute("href", "javascript:EditarAnuncio()");
    editarAnuncioA.setAttribute("id", "aeditar");
    editarAnuncioA.setAttribute("style", "padding-left:3px;");
    editarAnuncioDiv.setAttribute("id", "editaranuncio");
    editarAnuncioA.innerHTML = '<img border=0 src="../images/images_nuevodiseno/editar.png"/>';
    editarAnuncioDiv.appendChild(editarAnuncioA);
    
    if (mostrarBotonBorrar) {
        var borrarAnuncioDiv = CrearYAdjuntarDiv(controlAnuncioDiv, "borrarAnuncioDiv", "");
        var borrarAnuncioA = document.createElement("a");
        borrarAnuncioA.setAttribute("href", "javascript:BorrarAnuncio(" + anuncio.idAnuncio + ")");
        borrarAnuncioA.setAttribute("id", "aborrar");
        borrarAnuncioDiv.setAttribute("id", "borraranuncio");
        borrarAnuncioA.innerHTML = '<img border=0 src="../images/images_nuevodiseno/borrar.png"/>';
        borrarAnuncioDiv.appendChild(borrarAnuncioA);
    }

    var verAnuncioDiv = CrearYAdjuntarDiv(controlAnuncioDiv, "ver_anuncio", "");
    var verAnuncio = document.createElement("a");
    verAnuncio.setAttribute("href", enlaceAnuncioCompartir);
    verAnuncio.setAttribute("id", "averAnuncio");
    verAnuncio.setAttribute("target", "_blank");
    verAnuncioDiv.setAttribute("id", "ver_anuncio");
    verAnuncio.innerHTML = '<img border=0 src="../images/images_nuevodiseno/ver.png"/>';
    verAnuncioDiv.appendChild(verAnuncio);

    var compartirAnuncioDiv = CrearYAdjuntarDiv(controlAnuncioDiv, "compartirAnuncioDiv", "");
    var compartirAnuncio = document.createElement("a");
    compartirAnuncio.setAttribute("href", "javascript:SexyLightbox.display('compartirAnuncio.htm?&height=360&width=580')");
    compartirAnuncio.setAttribute("id", "acompartirAnuncio");
    compartirAnuncio.setAttribute("style", "padding-right:3px; float:left;");
    compartirAnuncioDiv.setAttribute("id", "compartirAnuncio");
    compartirAnuncio.innerHTML = '<img border=0 src="../images/images_nuevodiseno/compartir.png"/>';
    compartirAnuncioDiv.appendChild(compartirAnuncio);

    
    	
	
	
    SexyLightboxImagenesAnuncio.refresh();
    if (MostrarVentanaConfirmacion) {
        MostrarVentanaConfirmacion = false;
        Sexy.alert("Tu dirección de email: '" + emailUsuario + "', se ha confirmado correctamente. Ahora podrás comenzar a insertar los anuncios en los distintos portales.");
    }

    if (pagoRealizado) {
        pagoRealizado = false;
        //Sexy.alert('Tu saldo se ha recargado correctamente en ' + saldoRecarga + ' €. Recuerda que tus anuncios tendrán prioridad sobre el resto.');
        Sexy.alert('Tu Suscripción se ha realizado correctamente. Puede tardar unos minutos en quedar reflejado en su cuenta, para ello salga y vuelva a entrar.<br>Gracias.');

    }
    if (nombreUsuario != "")
        $("hAbrirDatos").innerHTML = nombreUsuario;
    else
        $("hAbrirDatos").innerHTML = nombreUsuarioAux;
}


var urlAComprimir;

function ComprimirUrl(url) {
    urlAComprimir = url;
    BitlyClient.shorten(urlAComprimir, 'shortenResponse');
}

function callbackApiBitLyCargada() {
    apiBitLyCargada = true;
    BitlyClient.shorten(urlAComprimir, 'shortenResponse');
}

var urlACompartir;

shortenResponse = function(data) {
    var firstResult;
    for (var r in data.results) {
        firstResult = data.results[r];
        break;
    }
    var urlComprimida = firstResult["shortUrl"];
    urlACompartir = urlComprimida;
    //funcionEspera();
};


function BorrarAnuncio(idAnuncio) {
    Sexy.confirm('El anuncio se borrará de la web Posteator.com, pero no de las webs donde lo hayas insertado. ¿Estas seguro de que deseas borrar el anuncio?', {
        textBoxBtnOk: 'Si',
        textBoxBtnCancel: 'No',
        onComplete: function(returnvalue) {
            if (returnvalue) {
                var myRequest = new Request({
                        url: 'BorrarAnuncio.aspx',
                        data: 'idUsuario=' + idUsuario + '&idAnuncio=' + idAnuncio + '&callback=CallBackBorrarAnuncio',
                        evalResponse: true
                    });
                myRequest.get();
            } else {
            }
        }
    });
}

function CallBackBorrarAnuncio(json) {
    var leftcontent = $("leftcontent");
    $("contentcontent").innerHTML = "";
    $("rightcontent").innerHTML = "";
    $("seleccionar").innerHTML = "";
    $("insertarportales").innerHTML = "";
    leftcontent.removeChild(anuncioSeleccionado);
    anuncioSeleccionado = "";
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var insertarCheck = true;

function MostrarPortalesParaInsertar(anuncio) {

    $("rightcontent").innerHTML = "";
    $("seleccionar").innerHTML = "";
    $("insertarportales").innerHTML = "";
    var table = document.createElement("table");
    table.setAttribute("id", "tablaPortales");
    var tr = document.createElement("tr");
    var th1 = document.createElement("th");
    var th2 = document.createElement("th");
    var tbody = document.createElement("tbody");
    tbody.setAttribute("id", "tablaPortalesDeAnuncios");
    var thead = document.createElement("thead");

    th2.setAttribute("width", "135");
    tr.appendChild(th1);
    tr.appendChild(th2);
    thead.appendChild(tr);
    table.appendChild(thead);
    table.appendChild(tbody);

    $("rightcontent").appendChild(table);

    table = tbody;

    var portales = ObtenetPortalesDondeInsertarAnuncio(anuncio);

    if (tipo != 1) {
        for (var i = 0; i < portales.length; i++) {
            AnadirPortalAlListado(anuncio, portales[i]);
        }
    } else {

        for (var i = 0; i < arraygratuitos.length; i++) {
            if (portales.indexOf(arraygratuitos[i]) != -1) {
                AnadirPortalAlListado(anuncio, arraygratuitos[i]);
            }
        }

        for (var i = 0; i < portales.length; i++) {
            if (!(arraygratuitos.indexOf(portales[i].toInt()) != -1))//esto es para que en la lista no salgan los gratuitos que ya se han metido
            {
                AnadirPortalAlListado(anuncio, portales[i]);
            }
        }
    }

    function AnadirPortalAlListado(anuncio, portal) {

        var precioInsercion = 0;
        var insertarNormal = true;

        var Estado = "";

        if ($("tablaPortalesDeAnuncios") != null) {

            if (anuncio.EstadoInsercion != undefined) {
                for (var h = 0; h < anuncio.EstadoInsercion.length; h++) {
                    if (anuncio.EstadoInsercion[h].portal == portal) {
                        Estado = anuncio.EstadoInsercion[h].estadoInsercion;
                    }
                }

                if (Estado != "") {
                    insertarNormal = false;
                }
                if (Estado == 0) {
                    insertarNormal = true;
                }
                if (Estado == 3) {
                    if (Estado == "") {
                        Estado = "";
                    } else {
                        Estado = "Insertado";
                    }
                } else if (Estado == 10) {
                    //Estado="Fallo"; 
                    if (Estado == "") {
                        Estado = "";
                    } else {
                        Estado = "Insertado";
                    }
                } else {
                    if (Estado == "") {
                        Estado = "";
                    } else {
                        Estado = "Pendiente";
                    }
                }
                //(!insertarNormal)
                if (anuncio.bMostrarCheck == 'false') {

                    var tr = document.createElement("tr");
                    var td0 = document.createElement("td");
                    td0.setAttribute("width", "10px");
                    var td1 = document.createElement("td");
                    td1.setAttribute("width", "140px");
                    var td2 = document.createElement("td");
                    td2.setAttribute("width", "100px");
                    td2.innerHTML = Estado;
                    td2.style.fontWeight = "bold";
                    td2.style.color = "black";
                    td2.style.fontSize = "11px";

                    var nombrePortalEIcono = NombrePortalEIconoPorCodigoPortal(portal);
                    td1.innerHTML = '<img src="' + nombrePortalEIcono[1] + '" />' + nombrePortalEIcono[0];
                    td1.style.fontSize = "11px";
                    tr.appendChild(td0);
                    tr.appendChild(td1);
                    tr.appendChild(td2);

                    $("tablaPortalesDeAnuncios").appendChild(tr);
                } else {
                    AnadirPortalNormal(anuncio, portal);
                }
            } else {
                AnadirPortalNormal(anuncio, portal);
            }
        }

        function AnadirPortalNormal(anuncio, portal) {
            var tr = document.createElement("tr");
            var td1 = document.createElement("td");
            var td0 = document.createElement("td");
            td0.setAttribute("id", "tdPortal" + portal);
            td0.setAttribute("name", "tdPortal" + portal);
            td0.setAttribute("width", "10px");

            var cb = document.createElement("input");
            cb.type = "checkbox";
            cb.setAttribute("name", "portal");
            cb.setAttribute("value", precioInsercion);
            cb.setAttribute("id", portal);
            if (tipo == 1) {


                if (arraygratuitos.indexOf(portal) != -1) {
                    cb.checked = true;
                } else {
                    cb.setAttribute("onclick", "avisoUsuarioGratuito(" + portal + ")");
                    cb.checked = false;
                }
            } else {
                cb.checked = true;
            }
            //if(MostrarZonaPago)            			

            var imgLoading = document.createElement("img");
            imgLoading.setAttribute("src", "../images/loading.gif");
            imgLoading.style.display = "none";
            imgLoading.setAttribute("id", "loading" + portal);

            var spanInsertado = document.createElement("span");
            spanInsertado.style.display = "none";
            spanInsertado.setAttribute("id", "insertado" + portal);
            td0.appendChild(cb);
            var nombrePortalEIcono = NombrePortalEIconoPorCodigoPortal(portal);
            td1.innerHTML = '<img src="' + nombrePortalEIcono[1] + '" />' + nombrePortalEIcono[0];
            td1.style.fontSize = "11px";
            if (tipo == 1) {
                if (!(tipo == 1 && arraygratuitos.indexOf(portal) != -1)) {
                    td1.style.color = "gray";
                }
            }
            tr.appendChild(td0);
            tr.appendChild(td1);
            $("tablaPortalesDeAnuncios").appendChild(tr);
        }
    }

    var check = document.getElementsByTagName("input");
    var c = 0;
    if (check.length > 0) {
        for (var i = 0; i < check.length; i++) {
            if (check[i].type == 'checkbox') {
                c++;
            }
        }
    }

    if (c > 0) {

        var botoninsertar = new Element('div', {
            'id': 'botoninsertar',
            'html': '<img src="../images/images_nuevodiseno/insertar.png" />',
            'events': {
                'click': function() {
                    InsertarAnuncio(anuncio);
                }
            }
        });

        var botonselect = new Element('div', { 'id': 'SelectPortales', 'html': '' });

        var seleccionar = document.createElement("a");
        seleccionar.setAttribute("id", "deselect");
        seleccionar.innerHTML = 'Seleccionar: ';
        botonselect.appendChild(seleccionar);

        var selectTodo = document.createElement("a");
        selectTodo.setAttribute("href", "javascript:seleccionarPortales()");
        selectTodo.setAttribute("id", "select");
        selectTodo.innerHTML = 'Todos ';
        botonselect.appendChild(selectTodo);

        var guion = document.createElement("a");
        guion.setAttribute("id", "deselect");
        guion.innerHTML = '-';
        botonselect.appendChild(guion);

        var deselectTodo = document.createElement("a");
        deselectTodo.setAttribute("href", "javascript:deseleccionarPortales()");
        deselectTodo.setAttribute("id", "select");
        deselectTodo.innerHTML = ' Ninguno';
        botonselect.appendChild(deselectTodo);
        $("seleccionar").appendChild(botonselect);

    } else {
        var imagenBoton;
        if (ProgramarActivado == 'true') {
            imagenBoton = "<span style='color: Green; font-size:11px; font-family:Helvetica,Verdana,Arial,SunSans-Regular,Sans-Serif; font-weight: bold; title='Programación Activada.'>Programación Activada.</span>";
        } else {
            if (anuncio.dias == "0") {
                imagenBoton = "<span style='color: Black; text-align:center; font-family: Calibri; font-weight: bold; title='insertar en 3 días.'>Debe esperar " + anuncio.horas + " hora/s,<br> para volver a publicar.</span>";
            } else {
                imagenBoton = "<span style='color: Black; text-align:center; font-family: Calibri; font-weight: bold; title='insertar en 3 días.'>Debe esperar " + anuncio.dias + " dia/s,<br> para volver a publicar.</span>";
            }

        }
        var botoninsertar = new Element('div', {
            'id': 'botoninsertar',
            'html': imagenBoton,
            'events': {
                'click': function() {

                }
            }
        });
        botoninsertar.setAttribute("style", "padding-left: 37px;");
    }
    $("insertarportales").appendChild(botoninsertar);
}

function deseleccionarPortales() {
    var check = document.getElementsByTagName("input");
    for (var i = 0; i < check.length; i++) {
        if (check[i].checked == true) {
            check[i].checked = false;
        }
    }
}

function seleccionarPortales() {
    var check = document.getElementsByTagName("input");
    for (var i = 0; i < check.length; i++) {
        if (check[i].checked == false) {
            if (tipo == 1) {
                if (arraygratuitos.indexOf(check[i].id.toInt()) != -1) {
                    check[i].checked = true;
                } else {
                    check[i].checked = false;
                }
            } else {
                check[i].checked = true;
            }

        }
    }
}

function ObtenetPortalesDondeInsertarAnuncio(anuncio) {
    var arrayPortales = new Array();
    var categoria = anuncio.categoria;
    var subcategoria = anuncio.subcategoria;
    var codOperacion = anuncio.operacion;
    var loquoExiste = true;
    var provNOloquo = new Array(1, 2, 33, 5, 9, 10, 39, 12, 51, 13, 16, 19, 20, 21, 22, 23, 26, 24, 27, 52, 32, 34, 40, 42, 49, 51, 52);
    for (i = 0; i < provNOloquo.lenght; i++) {
        if (provNOloquo[i] == provinciaCodigoNuevoAnuncio) {
            loquoExiste = false;
        }
    }

    if (!(categoria == 1 && (subcategoria == 12 || subcategoria == 17 || subcategoria == 18 || subcategoria == 19 || subcategoria == 20))) {
        if (!(categoria == 2 || categoria == 3 && codOperacion == 1)) {
            arrayPortales.push(PORTAL_MUNDOANUNCIO);
        }
    }
    arrayPortales.push(PORTAL_CAMPUSANUNCIOS);

    if (!(categoria == 1 && (subcategoria == 12 || subcategoria == 16) && !(categoria == 1 && (codOperacion == 3)))) {
        if (categoria != 7) {
            arrayPortales.push(PORTAL_MILANUNCIOS);
        }
    }
    //categoria!=CATEGORIA_CONTACTOS && categoria!= CATEGORIA_SERVICIOS 
    if (categoria != CATEGORIA_EMPLEO && loquoExiste) {
        //if(MostrarZonaPago)
        if (categoria == 1) {
            if (subcategoria != 12 && subcategoria != 16 && subcategoria != 20) {
                arrayPortales.push(PORTAL_LOQUO);
            }
        } else {
            arrayPortales.push(PORTAL_LOQUO);
        }

    }

    if (categoria == CATEGORIA_COMPRAVENTA || categoria == CATEGORIA_FORMACION) {
        if (categoria == CATEGORIA_FORMACION || (categoria == CATEGORIA_COMPRAVENTA && subcategoria != '17' && subcategoria != '18'))
            arrayPortales.push(PORTAL_SEGUNDAMANO);
    }
    if (!(categoria == 1 && subcategoria == 20) && !(categoria == 1 && subcategoria >= 8 && codOperacion >= 2)) {
        arrayPortales.push(PORTAL_HABITAMOS);
    }
    if (!(categoria == 1 && (subcategoria == 20 || subcategoria == 16) && !(categoria == 1 && codOperacion == 1))) {
        arrayPortales.push(PORTAL_OLX);
    }
    if (!(categoria == 3 && (subcategoria == 7 || subcategoria == 6 || subcategoria == 4 || subcategoria == 2)) && !(categoria == 1 && (subcategoria == 7 || subcategoria == 8 || subcategoria == 12 || subcategoria == 16 || subcategoria == 13 || subcategoria == 18 || subcategoria == 20))) {
        arrayPortales.push(PORTAL_TABLONDEANUNCIOS);
    }
    if (!(categoria == 1 && (subcategoria == 8 || subcategoria == 16))) {
        arrayPortales.push(PORTAL_CASINUEVO);
    }
    arrayPortales.push(PORTAL_MANUNCIOS);
    if (!(categoria == 1 && codOperacion == 1)) {
        arrayPortales.push(PORTAL_TUSANUNCIOS);
    }
    if (categoria != CATEGORIA_CONTACTOS && subcategoria != 6)
        //arrayPortales.push(PORTAL_ANUNCIOS);
        if (!(categoria == 1 && subcategoria == 16) && codOperacion == 3) {
            arrayPortales.push(PORTAL_ANUNCIOTOTAL);
        }
    if (!(categoria == 1 && (subcategoria == 12 || subcategoria == 12) && !(categoria == 1 && (codOperacion == 1 || codOperacion == 3)))) {
        arrayPortales.push(PORTAL_BLIDOO);
    }
    //arrayPortales.push(PORTAL_ANUNCIOSDIARIOS);//ESTAMOS BANEADOS Y NO RESPONDEN A LOS EMAIL.
    //arrayPortales.push(PORTAL_ANUNCIO);
    if (codOperacion != 3) {
        if (categoria == 1 && codOperacion == 2) {
            if (subcategoria != 3 && subcategoria != 5 && subcategoria != 6 && subcategoria != 8 && subcategoria != 11 && subcategoria != 12 && subcategoria != 16 && subcategoria != 20) {
                arrayPortales.push(PORTAL_ECLASI);
            }
        } else {
            arrayPortales.push(PORTAL_ECLASI);
        }
    }
    if (categoria == 1) {
        if (!(subcategoria >= 8 && codOperacion == 3)) {
            if (!(codOperacion == 2 && (subcategoria == 8 || subcategoria == 11 || subcategoria == 17 || subcategoria == 18 || subcategoria == 19))) {
                if (subcategoria != 20) {
                    arrayPortales.push(PORTAL_ADOOS);
                }
            }
        }
    } else {
        arrayPortales.push(PORTAL_ADOOS);
    }
    if (!(codOperacion == 1 && categoria == 1)) {
        if (!(categoria == 3 && subcategoria == 17)) {
            if (!(categoria == 1 && (subcategoria == 16 || subcategoria == 18 || subcategoria == 20))) {
                arrayPortales.push(PORTAL_CITTYS);
            }
        }
    }
    if (categoria == 1) {
        if (subcategoria == 15 || subcategoria == 13 || (subcategoria == 7 && (codOperacion == 1 || codOperacion == 2)) || (subcategoria == 1 && codOperacion != 1) || (subcategoria == 9 && codOperacion != 1)) {
            arrayPortales.push(PORTAL_PLANETANUNCIOS);
        }
    }
    if (codOperacion != 1) {
        if (!(subcategoria == 7 && codOperacion == 0)) {
            if (!(subcategoria == 8 && codOperacion == 2)) {
                arrayPortales.push(PORTAL_MERKATIA);
            }
        }
    }

    if (codOperacion != 1) {
        arrayPortales.push(PORTAL_VENDERYA);
    }
    if (categoria != CATEGORIA_COMUNIDAD && categoria != CATEGORIA_COMPRAVENTA) {
        arrayPortales.push(PORTAL_TABLONIA);
    }
    if (categoria != CATEGORIA_CONTACTOS) {
        if (!(categoria == 1 && subcategoria == 16)) {
            arrayPortales.push(PORTAL_NEON);
        }
    }
    if (categoria != CATEGORIA_COMPRAVENTA && provinciaCodigoNuevoAnuncio != 15) {
        arrayPortales.push(PORTAL_ANUNCIOTECA);
    }
    if (categoria != CATEGORIA_SERVICIOS && categoria != CATEGORIA_FORMACION && categoria != CATEGORIA_COMUNIDAD) {
        arrayPortales.push(PORTAL_GLOBALANUNCIO);
    }
    if (categoria == CATEGORIA_INMOBILIARIA) {
        if (subcategoria != 12 && subcategoria != 7 && subcategoria != 8 && codOperacion != 2 && codOperacion != 3) {
            arrayPortales.push(PORTAL_TUCASA);
        }
    }
    if (categoria == CATEGORIA_INMOBILIARIA) {
        arrayPortales.push(PORTAL_COMISION);
    }
    if (categoria != CATEGORIA_COMUNIDAD && categoria != CATEGORIA_SERVICIOS) {
        if (codOperacion != 1 && codOperacion != 2) {
            //arrayPortales.push(PORTAL_TELOANUNCIO);
        }
    }
    if (categoria == CATEGORIA_INMOBILIARIA) {

        if (codOperacion == 0 || codOperacion == 2) {

            //arrayPortales.push(PORTAL_HOGARIA);
        }
    }
    
     arrayPortales.push(PORTAL_VENDOO);
    arrayPortales.push(PORTAL_TWITTER);
    if (categoria == CATEGORIA_COMPRAVENTA || categoria == CATEGORIA_EMPLEO || categoria == CATEGORIA_INMOBILIARIA || categoria == CATEGORIA_MOTOR) {

        if (codOperacion == 0 || codOperacion == 2) {
            arrayPortales.push(PORTAL_DONKIZ);
            if (!(categoria == CATEGORIA_COMPRAVENTA && subcategoria == 17) || !(categoria == CATEGORIA_COMPRAVENTA && subcategoria == 18)) {
                arrayPortales.push(PORTAL_TROVIT);
                arrayPortales.push(PORTAL_SUMAVISOS);
                arrayPortales.push(PORTAL_CLASF);
            }
        }
    }
    if (categoria == CATEGORIA_MOTOR && subcategoria == 1 && codOperacion == 0) {

        arrayPortales.push(PORTAL_MOTORES);
    }

    if (categoria == CATEGORIA_MOTOR && codOperacion == 0) {
        arrayPortales.push(PORTAL_AUTOMOBILE247);
    }

    if ((categoria == CATEGORIA_MOTOR || categoria == CATEGORIA_EMPLEO) && codOperacion == 0) {

        arrayPortales.push(PORTAL_MITULA);
    }
    if (codOperacion == 0) {

        arrayPortales.push(PORTAL_CANALANUNCIO);
        arrayPortales.push(PORTAL_MELOCOMPRAS);
    }

    return arrayPortales;
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ADMIN ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function PrepararAdmin() {
    for (var i = 0; i < anunciosPendientes.length; i++) {
        var idAnuncioPortal = anunciosPendientes[i][0];
        var portal = idAnuncioPortal + "&nbsp;&nbsp;&nbsp;" + NombrePortalEIconoPorCodigoPortal(anunciosPendientes[i][1])[0];
        var li = new Element('li', {
            'id': idAnuncioPortal,
            'html': portal,
            'class': 'opcion',
            'events': {
                'click': function() {
                    InsertarAnuncioAdmin(this.id);
                }
            }
        });
        listaAnunciosPendientes.appendChild(li);
    }
}

function InsertarAnuncioAdmin(idAnuncioPortal) {
    var myRequest = new Request({
            url: '../anunciar/publicaranuncios.aspx',
            data: 'idanuncioportal=' + idAnuncioPortal + '&paso=0&callback=callbackinsertaranuncio',
            evalResponse: true
        });
    myRequest.get();
}

function NombrePortalEIconoPorCodigoPortal(codigoPortal) {
    var nombrePortal = "";
    var iconoPortal = "";
    switch (codigoPortal) {
    case PORTAL_SEGUNDAMANO:
        nombrePortal = "Segundamano";
        iconoPortal = "../images/segundamano.ico";
        break;
    case PORTAL_LOQUO:
        nombrePortal = "Loquo+eBay";
        iconoPortal = "../images/loquo.ico";
        break;
    case PORTAL_MUNDOANUNCIO:
        nombrePortal = "Mundoanuncio";
        iconoPortal = "../images/mundoanuncio.ico";
        break;
    case PORTAL_MILANUNCIOS:
        nombrePortal = "Milanuncios";
        iconoPortal = "../images/milanuncios.ico";
        break;
    case PORTAL_CAMPUSANUNCIOS:
        nombrePortal = "CampusAnuncios";
        iconoPortal = "../images/campusanuncios.ico";
        break;
    case PORTAL_EBAY:
        nombrePortal = "Ebay";
        iconoPortal = "../images/ebay.ico";
        break;
    case PORTAL_HABITAMOS:
        nombrePortal = "Habitamos";
        iconoPortal = "../images/habitamos.ico";
        break;
    case PORTAL_OLX:
        nombrePortal = "Olx";
        iconoPortal = "../images/olx.ico";
        break;
    case PORTAL_FOTOCASA:
        nombrePortal = "Fotocasa";
        iconoPortal = "../images/fotocasa.ico";
        break;
    case PORTAL_COCHESNET:
        nombrePortal = "Coches.net";
        iconoPortal = "../images/cochesnet.ico";
        break;
    case PORTAL_TABLONDEANUNCIOS:
        nombrePortal = "TablonAnuncios";
        iconoPortal = "../images/tablondeanuncios.ico";
        break;
    case PORTAL_CASINUEVO:
        nombrePortal = "CasiNuevo";
        iconoPortal = "../images/casinuevo.ico";
        break;
    case PORTAL_MANUNCIOS:
        nombrePortal = "Manuncios";
        iconoPortal = "../images/manuncios.ico";
        break;
    case PORTAL_TUSANUNCIOS:
        nombrePortal = "TusAnuncios";
        iconoPortal = "../images/tusanuncios.ico";
        break;
    //case PORTAL_ANUNCIOS				: nombrePortal =  "Anuncios.es";		iconoPortal= "../images/anuncios.ico"; break;
    case PORTAL_ANUNCIOTOTAL:
        nombrePortal = "AnuncioTotal";
        iconoPortal = "../images/anunciototalicon.png";
        break;
    case PORTAL_BLIDOO:
        nombrePortal = "Blidoo";
        iconoPortal = "../images/blidoo.png";
        break;
    case PORTAL_ANUNCIOSDIARIOS:
        nombrePortal = "AnunciosDiarios";
        iconoPortal = "../images/anunciosdiariosicon.png";
        break;
    case PORTAL_ANUNCIO:
        nombrePortal = "Anuncio.es";
        iconoPortal = "../images/anuncio.ico";
        break;
    case PORTAL_ECLASI:
        nombrePortal = "Eclasi";
        iconoPortal = "../images/eclasiico.jpg";
        break;
    case PORTAL_ADOOS:
        nombrePortal = "Adoos";
        iconoPortal = "../images/adoosico.ico";
        break;
    case PORTAL_CITTYS:
        nombrePortal = "Cittys";
        iconoPortal = "../images/cittysicon.ico";
        break;
    case PORTAL_PLANETANUNCIOS:
        nombrePortal = "PlanetAnuncios";
        iconoPortal = "../images/planetanunciosicon.png";
        break;
    case PORTAL_MERKATIA:
        nombrePortal = "Merkatia";
        iconoPortal = "../images/mercatiaicon.png";
        break;
    case PORTAL_VENDERYA:
        nombrePortal = "VenderYa";
        iconoPortal = "../images/venderyaicon.png";
        break;
    case PORTAL_TABLONIA:
        nombrePortal = "Tablonia";
        iconoPortal = "../images/tablonia.ico";
        break;
    case PORTAL_NEON:
        nombrePortal = "AnunciosNeon";
        iconoPortal = "../images/neon.ico";
        break;
    case PORTAL_ANUNCIOTECA:
        nombrePortal = "Anuncioteca";
        iconoPortal = "../images/favicon_anuncioteca.ico";
        break;
    case PORTAL_GLOBALANUNCIO:
        nombrePortal = "GlobalAnuncio";
        iconoPortal = "../images/favicon_globalanuncio.ico";
        break;
    case PORTAL_TUCASA:
        nombrePortal = "TuCasa";
        iconoPortal = "../images/tucasa.ico";
        break;
    case PORTAL_TELOANUNCIO:
        nombrePortal = "TeLoAnuncio";
        iconoPortal = "../images/logoteloanuncio.png";
        break;
    case PORTAL_COMISION:
        nombrePortal = "0Comision";
        iconoPortal = "../images/comision.ico";
        break;
    case PORTAL_HOGARIA:
        nombrePortal = "Hogaria";
        iconoPortal = "../images/hogaria.ico";
        break;
    case PORTAL_TWITTER:
        nombrePortal = "Twitter";
        iconoPortal = "../images/twitter.ico";
        break;
    case PORTAL_TROVIT:
        nombrePortal = "Trovit";
        iconoPortal = "../images/trovit.ico";
        break;
    case PORTAL_SUMAVISOS:
        nombrePortal = "Sumavisos";
        iconoPortal = "../images/sumavisos.ico";
        break;
    case PORTAL_DONKIZ:
        nombrePortal = "Donkiz";
        iconoPortal = "../images/donkiz.ico";
        break;
    case PORTAL_AUTOMOBILE247:
        nombrePortal = "AutoMobile247";
        iconoPortal = "../images/automobile247.ico";
        break;
    case PORTAL_MOTORES:
        nombrePortal = "Motor.es";
        iconoPortal = "../images/motor_es.ico";
        break;
    case PORTAL_CANALANUNCIO:
        nombrePortal = "CanalAnuncio";
        iconoPortal = "../images/canal_anuncio.ico";
        break;
    case PORTAL_MITULA:
        nombrePortal = "Mitula";
        iconoPortal = "../images/mitula.ico";
        break;
    case PORTAL_MELOCOMPRAS:
        nombrePortal = "MeLoCompras";
        iconoPortal = "../images/melocompras.ico";
        break;	
    case PORTAL_CLASF:
        nombrePortal = "clasf";
        iconoPortal = "../images/clasf.png";
        break;
     case PORTAL_VENDOO:
        nombrePortal = "Vendoo";
        iconoPortal = "../images/vendoo.png";
        break;
    }
    return [nombrePortal, iconoPortal];
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// FUNCIONES UTILES

function disableSelection(target) {
    if (typeof target.onselectstart != "undefined") //IE route
        target.onselectstart = function() { return false; };
    else if (typeof target.style.MozUserSelect != "undefined") //Firefox route
        target.style.MozUserSelect = "none";
    else //All other route (ie: Opera)
        target.onmousedown = function() { return false; };
}

function XmlToJson(url, callback) {
    url = "http://www.goolzoom.com/XmlToJson.aspx?theurl=" + escape(url);
    if (callback) url += "&callback=" + callback;
    cs(url);
}

function cs(scriptUrl, callback) {

    e = document.createElement("script");
    /*e.setAttribute("lang","javascript");
	
	e.setAttribute("type","text/javascript");
	e.setAttribute("charset","ISO-8859-15");
	e.setAttribute("content","application/x-javascript; charset=ISO-8859-15");
	e.setAttribute("src",scriptUrl+"&d="+GetDateString());
	*/	
	
	
    e.lang = 'javascript';
    e.type = 'text/javascript';
    e.charset = 'ISO-8859-15';
    e.content = 'application/x-javascript; charset=ISO-8859-15';

    if (callback) {
        e.onreadystatechange = function() { if (this.readyState == 'loaded' || this.readyState == 'complete') callback(); };
        e.onload = function() { callback(); };
    }

    e.src = scriptUrl + "&d=" + GetDateString();
//	alert(e.src);
    document.getElementsByTagName("head")[0].appendChild(e);
}

function IsNumeric(sText) {
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) if (ValidChars.indexOf(sText.charAt(i)) == -1) IsNumber = false;
    return IsNumber;
}

function IsNumeric2(sText) {
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;
    if (ValidChars.indexOf(sText) == -1) IsNumber = false;
    return IsNumber;
}

function trim(cadena) {
    return (cadena == '') ? '' : cadena.replace( /^\s*|\s*$/g , "");
}

function isValidEmail(texto) {
    var mailres = true;
    var cadena = "abcdefghijklmnñopqrstuvwxyzABCDEFGHIJKLMNÑOPQRSTUVWXYZ1234567890@._-";

    var arroba = texto.indexOf("@", 0);
    if ((texto.lastIndexOf("@")) != arroba) arroba = -1;

    var punto = texto.lastIndexOf(".");

    for (var contador = 0; contador < texto.length; contador++) {
        if (cadena.indexOf(texto.substr(contador, 1), 0) == -1) {
            mailres = false;
            break;
        }
    }

    if ((arroba > 1) && (arroba + 1 < punto) && (punto + 1 < (texto.length)) && (mailres == true) && (texto.indexOf("..", 0) == -1))
        mailres = true;
    else
        mailres = false;

    return mailres;
//return (/^[a-zA-Z0-9_-]{2,}@[a-zA-Z0-9_-]{2,}\.[a-zA-Z]{2,4}(\.[a-zA-Z]{2,4})?$/.test(str));
}

function ValidaURL(url) {
    var regex = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/ ;
    return regex.test(url);
}

function ValidaURL2(url) {
    if (url != "") {
        if (url.indexOf("http://") == -1) {
            url = "http://" + url;
            URLNuevoAnuncio = "http://" + URLNuevoAnuncio;
        }
    }
    var regex = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/ ;

    return regex.test(url);
}

function GetDateString() {
    return new Date().getTime();
}

function ContieneEmail(texto) {
    var contiene = false;
    texto = texto.split(' ');
    for (var i = 0; i < texto.length; i++) {
        if (isValidEmail(texto[i])) {
            contiene = true;
            break;
        }
    }
    return contiene;
}

function ContieneURL(texto) {
    var contiene = false;
    texto = texto.split(' ');
    for (var i = 0; i < texto.length; i++) {
        if (ValidaURL(texto[i])) {
            contiene = true;
            break;
        }
    }
    return contiene;
}

function ContieneNumeroDeTelefono(texto) {
    var contiene = false;
    texto = texto.split(' ');
    for (var i = 0; i < texto.length; i++) {
        if (texto[i].length == 9 && IsNumeric(texto[i])) {
            contiene = true;
            break;
        }
    }
    return contiene;
}


function ContieneNumeroDeTelefono2(texto) {

    var contiene = false;
    var AuxContiene = "";
    var indice = 0;
    texto = trim(texto);
    for (var i = 0; i < texto.length; i++) {

        if (IsNumeric2(texto.charAt(i)) && i == 0) {

            AuxContiene += texto[i];
            indice = i;

        } else if (i > 0 && IsNumeric2(texto.charAt(i))) {
            if (AuxContiene == "") {
                if (IsNumeric2(texto.charAt(i))) {
                    AuxContiene += texto[i];
                    indice = i;
                }
            } else {
                if ((indice + 1) == i && AuxContiene != "") {
                    if (IsNumeric2(texto.charAt(i))) {
                        AuxContiene += texto[i];
                        indice = i;
                    }
                } else {
                    AuxContiene = "";
                    indice = 0;
                }
            }
        }
    }
    if (AuxContiene != "" && AuxContiene.length >= 9) {
        contiene = true;
    }
    return contiene;
}

/////////////////////////////////////
/////////////////////////////////////
//PARA REALIZAR PAGOS
/////////////////////////////////////
/////////////////////////////////////

function AbrirRecargarSaldo() {
    SexyLightbox.close();
    SexyLightbox.display('pagoPremiun.html?&height=400&width=670');
}

function AbrirRecargarSaldoPlus() {
    SexyLightbox.close();
    SexyLightbox.display('pagoPlus.html?&height=400&width=670');
}

function CambioTitulo() {
//    if(cambiarTituloPago)
//    {
//        cambiarTituloPago = false;
//        //$("divOpcionesTitulo").innerHTML = "Precio Anuncio.";
//    }
//    else
//    {
//        $("mensajeRecarga").style.display="none";
//    }    
}

function controlFactura() { //NO BORRAR
}

var eleccionTipo;

function eleccionTipoUsuario(tipoUsuSeleccionado) {
    eleccionTipo = tipoUsuSeleccionado;
}

var bPagoPaypal;

function FacturaRecargarSaldo() {
    var nombreEmpresa = $('nombreEmpresa').value;
    var domicilioEmpresa = $('domicilioEmpresa').value;
    var cifEmpresa = $('cifEmpresa').value;
    if ($("inputPagoPaypal").checked == true) {
        bPagoPaypal = true;
        //RecargarSaldoPaypal();
    } else {
        bPagoPaypal = false;
        //RecargarSaldoPaypalMensual();               
    }
    if (nombreEmpresa != '' && domicilioEmpresa != '' && cifEmpresa != '' && $("necesitasfacturasi").checked == true) {
        //alert("si");
        var myRequest = new Request({
                url: '../usuarios/Operaciones.aspx',
                data: 'idUsuario=' + idUsuario + '&nombreEmpresa=' + nombreEmpresa + '&domicilioEmpresa=' + domicilioEmpresa + '&cifEmpresa=' + cifEmpresa,
                evalResponse: true
            });
        myRequest.get();
        RecargarSaldo();
    } else if ($("necesitasfacturano").checked == true) {
        //alert("no");
        RecargarSaldo();
    } else {
        alert("Debe rellenar las 3 cajas de texto.");
    }
}

function RecargarSaldo() {
    if (bPagoPaypal == true) {
        RecargarSaldoPaypal();
    } else {
        RecargarSaldoPaypalMensual();
/*PAGO CON TARJETA*/
//            var myRequest = new Request({
//		    url: '../pagos/RegistrarNuevoUsuario.aspx',
//		    data:'idUsuario='+idUsuario+'&saldo=' + $("txtRecarga").value,		
//		    evalResponse:true
//	    });
//	    myRequest.get();        
    }
}

function ComprobarTextRecarga(txtRecarga) {

    var mostrarMensaje = false;
    for (i = 0; i < txtRecarga.length; i++) {
        if (!EsNumero(txtRecarga.charAt(i))) {

            if (txtRecarga.charAt(i) == ".") {
                mostrarMensaje = false;
            } else {
                mostrarMensaje = true;
                break;
            }
        }
    }
    return mostrarMensaje;
}

function EsNumero(Caracter) {
    var ValidChars = "0123456789";
    var IsNumber = true;
    if (ValidChars.indexOf(Caracter) == -1)
        IsNumber = false;
    return IsNumber;
}

function RecargarSaldoPaypal() {
    var linkPaypal = '';
    linkPaypal += 'https://www.paypal.com/cgi-bin/webscr?cmd=_xclick-subscriptions&business=consultas@goolzoom.com&item_name=';
    linkPaypal += 'Posteator.com subscripcion mensual - ' + emailUsuario;
    linkPaypal += '&page_style=Goolzoom';
    linkPaypal += '&amp;lc=ES';
    //linkPaypal+='&amount=' + $("txtRecarga").value;		
    linkPaypal += '&item_number=';
    linkPaypal += idUsuario;
    linkPaypal += '&no_shipping=1&no_note=1&currency_code=EUR&lc=ES&bn=PP%2dSubscriptionsBF&charset=UTF%2d8';
    if (eleccionTipo == 2) {
        linkPaypal += '&a3=30%2e00';
    } else if (eleccionTipo == 3) {
        linkPaypal += '&a3=60%2e00';
    }
    linkPaypal += '&p3=1&t3=M';
    linkPaypal += '&src=1&sra=1';
    linkPaypal += '&return=http://www.posteator.com/usuarios/index.aspx?pagoRealizado=10';
    linkPaypal += '&notify_url=http://www.posteator.com/pagos/payment_success.aspx';
    window.location = linkPaypal;
}

function RecargarSaldoPaypalMensual() {

    var linkPaypal = '';
    linkPaypal += 'https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business=consultas@goolzoom.com&item_name=';
    linkPaypal += 'Posteator.com pago mensual - ' + emailUsuario;
    linkPaypal += '&page_style=Goolzoom';
    linkPaypal += '&amp;lc=ES';
    if (eleccionTipo == 2) {
        linkPaypal += '&amount=30';
    } else if (eleccionTipo == 3) {
        linkPaypal += '&amount=60';
    }

    linkPaypal += '&item_number=';
    linkPaypal += idUsuario;
    linkPaypal += '&no_shipping=1&no_note=1&currency_code=EUR&lc=ES&charset=UTF%2d8';
    linkPaypal += '&return=http://www.posteator.com/usuarios/index.aspx?pagoRealizado=10';
    linkPaypal += '&notify_url=http://www.posteator.com/pagos/payment_success.aspx';
    window.location = linkPaypal;
}

function RecargarSaldoTarjeta(identificador, clave) {

    var myForm = document.createElement("form");
    myForm.method = "post";
    myForm.action = 'https://sis.sermepa.es/sis/realizarPago';
    var input1 = document.createElement("input");
    var input2 = document.createElement("input");
    var input3 = document.createElement("input");
    var input4 = document.createElement("input");
    var input5 = document.createElement("input");
    var input6 = document.createElement("input");
    var input7 = document.createElement("input");
    var input8 = document.createElement("input");
    var input9 = document.createElement("input");
    var input10 = document.createElement("input");
    input1.setAttribute("name", "Ds_Merchant_Amount");
    input1.setAttribute("value", ($("txtRecarga").value) * 100);
    input2.setAttribute("name", "Ds_Merchant_Currency");
    input2.setAttribute("value", "978");
    input3.setAttribute("name", "Ds_Merchant_Order");
    input3.setAttribute("value", identificador); // entre 4 y doce  posiones
    input4.setAttribute("name", "Ds_Merchant_MerchantCode");
    input4.setAttribute("value", "297333551");
    input5.setAttribute("name", "Ds_Merchant_TransactionType");
    input5.setAttribute("value", "0");
    input6.setAttribute("name", "Ds_Merchant_MerchantURL");
    input6.setAttribute("value", "http://www.poneranuncios.net/pagos/PasarelaPagado.aspx?pagoRealizado=" + ($("txtRecarga").value) * 100);
    input7.setAttribute("name", "Ds_Merchant_MerchantSignature");
    input7.setAttribute("value", clave);
    input8.setAttribute("name", "Ds_Merchant_Terminal");
    input8.setAttribute("value", "1");
    input9.setAttribute("name", "Ds_Merchant_ProductDescription");
    input9.setAttribute("value", "Recarga Saldo Posteator.com");
    input10.setAttribute("name", "Ds_Merchant_PayMethods");
    input10.setAttribute("value", "T");

    myForm.appendChild(input1);
    myForm.appendChild(input2);
    myForm.appendChild(input3);
    myForm.appendChild(input4);
    myForm.appendChild(input5);
    myForm.appendChild(input6);
    myForm.appendChild(input7);
    myForm.appendChild(input8);
    myForm.appendChild(input9);
    myForm.appendChild(input10);

    //alert("A continuación se va a proceder a realizar el pago mediante tarjeta a través de una pasarela segura. Siga los pasos que se le vallan indicando. Recibirá un mail de Goolzoom notificándole que el pago se ha realizado correctamente.");
    document.body.appendChild(myForm);
    myForm.submit();
    document.body.removeChild(myForm);

}

//function ayudaRecarga()
//{
//    var textoTodos = "<B>Información importante:</B> Posteator.com ha modificado las condiciones de uso del servicio: <br><ol>";
//    textoTodos += "<li>Solamente puedes tener activos un máximo de " + numMaxAnuncios + " anuncios. Posteriormente éste número se irá ampliando. Puedes modificar sin embargo los anuncios que ya tienes insertados.<br>";
//    textoTodos += "<li>Puedes borrar y volver a publicar anuncios cada 3 días.</li>";
//    textoTodos += "<li>Para los anuncios de contactos y servicios ya no es necesario el pago de 12 € por anuncio.</li>";
//    textoTodos += "<li>En cambio, es necesario que realices un pago de 30€ para poder insertar los anuncios que quieras durante un mes.</li>";
//    textoTodos += "<li>Tus anuncios ya no mostrarán la publicidad 'Anuncio insertado con la herramienta Posteator.com'.</li></ol>";
//    
//    if(!bFechaSuscripcion)Sexy.alert(textoTodos);
//	
//}

function VerificarImagen(imagen) {
    //imagen = imagen.toLowerCase();
    var imgRe = /^.+\.(jpg|jpeg|gif|png)$/i ;
    if (imagen.search(imgRe) != -1) return true;
    else {
        alert("Solo se permiten imagenes con extensiones .jpeg, .jpg, .png y .gif. Introduce otro archivo.");
        imagen = "";
        return false;
    }
}

function ComprobarSaldoBBDD(strRepetidos, strNumeroAnunciosUsuario, strLista, strIdAnuncio) {
    var myRequest = new Request({
            url: '../pagos/ConsultaSaldoUsuario.aspx',
            data: 'idUsuario=' + idUsuario + '&bFechaSuscripcion=true&repetidos=' + strRepetidos + '&numeroAnunciosUsuario=' + strNumeroAnunciosUsuario + '&lista=' + strLista + '&idAnuncio=' + strIdAnuncio + '&callback=CallbackComprobarSaldoBBDD',
            evalResponse: true
        });
    myRequest.get();
}

function CallbackComprobarSaldoBBDD(cFechaSuscripcion, cdiasRestantesSuscripcion, cRepetidos, cnumeroAnunciosUsuario, lista, cIdAnuncio, bPublicadoGratis) {

    bFechaSuscripcion = cFechaSuscripcion;
    diasRestantesSuscripcion = cdiasRestantesSuscripcion;
    repetidos = cRepetidos;
    numeroAnunciosUsuario = cnumeroAnunciosUsuario;
    if (MostrarZonaPago) {
        bFechaSuscripcion = true;
        numeroAnunciosUsuario = 1;
        repetidos = false;
        tipo = 2;
    }

    if (tipo == 1 && !bPublicadoGratis) {
        bFechaSuscripcion = true;
    }

    if (bFechaSuscripcion && numeroAnunciosUsuario <= numMaxAnuncios && !repetidos) {
        //Sexy.alert(' A continuación tu anuncio va a pasar a una cola de anuncios pendientes de inserción. Podrás comprobar el estado de los anuncios en el panel de la derecha. Una vez que hayamos insertado tu anuncio en los distintos portales, comenzarás a recibir los emails de confirmación.');
        SexyLightbox.display('compartirAnuncio.htm?&height=360&width=580'); //220&width=450
        var listaAux = lista.substring(0, lista.length - 1);
        var myRequest = new Request({
                url: '../usuarios/InsertarAnuncioPaso1.aspx',
                data: 'id=' + cIdAnuncio + '&portal=' + listaAux + '&paso=0&programar=' + valorActivacion + '&callback=CallbackObtenerDatosDeAnuncio',
                evalResponse: true
            });
        myRequest.get();
        //ObtenerDatosDeAnuncio(cIdAnuncio);
    } else {
        if (repetidos == true) Sexy.alert("<B>Aviso</B>: Tienes anuncios repetidos, por favor elimina los anuncios repetidos");

        if (numeroAnunciosUsuario > numMaxAnuncios) Sexy.alert("<B>Aviso</B>: El número de anuncios maximo permitido para poder publicar es de " + numMaxAnuncios + ", debe de borrar anuncios para poder realizarlo.");

        var usuarioNoSuscrito = "Posteator.com ha modificado recientemente las condiciones del uso del servicio. Para publicar anuncios es necesario que realices un pago de 30 €, y podrás publicar los anuncios durante un mes.<br>";

        if (!bFechaSuscripcion) {
            AbrirRecargarSaldo();                                   
        }

    }

}

function ComprobarSaldoBBDDOpciones() {
    var myRequest = new Request({
            url: '../pagos/DescontarSaldo.aspx',
            data: 'ComprobarSaldo=si&idUsuario=' + idUsuario + '&callback=CallbackComprobarSaldoBBDDOpciones',
            evalResponse: true
        });
    myRequest.get();
}

function CallbackComprobarSaldoBBDDOpciones(strSaldo) {
    if (strSaldo != 0) {
        strSaldo = (strSaldo * 100) / 100;
        strSaldo = strSaldo.toFixed(2);
        saldo = strSaldo;
    }
    SexyLightbox.display('opciones.html?&height=290&width=460');
}

function GuardarUsuario(sform) {

    var myRequest = new Request({
            url: '../usuarios/GuardarUsuario.aspx',
            data: 'emailNuevoAnuncio=' + emailNuevoAnuncio + '&callback=CallbackGuardarUsuario',
            evalResponse: true
        });
    myRequest.get();
}

function CallbackGuardarUsuario(strIdUsuario, strCola) {
    cola = strCola;
    idUsuario = strIdUsuario;
    NuevoAnuncioInsertando(formAux);
}

function CompartirAnuncio() {
//    if (botonInsertaranuncio)
//    {
//        $("divTextoPublicacion").style.color="#564B47";
//        $("divTextoPublicacion").style.fontFamily ="Helvetica,Verdana,Arial,SunSans-Regular,Sans-Serif";
//        $("divTextoPublicacion").style.fontWeight="bold";
//        $("divTextofecha").innerHTML= '<p> A continuación tu anuncio va a pasar a una cola de anuncios pendientes de inserción. Podrás comprobar el estado de los anuncios en el panel de la derecha. Una vez que hayamos insertado tu anuncio en los distintos portales, comenzarás a recibir los emails de confirmación.</p><br>';
//        botonInsertaranuncio = false;
//    }

    var lf = document.createElement("a");
    lf.setAttribute("href", "http://www.facebook.com/sharer.php?u=" + enlaceAnuncioCompartir + "&t=" + tituloAnuncioCompartir);
    lf.setAttribute("Title", "Compartir en Facebook");
    lf.setAttribute("id", "lf");
    lf.setAttribute("target", "_blank");
    lf.style.color = "white";
    lf.innerHTML = '<div class="cajaredondeada"><img src="../images/icons/facebook.png" alt="Compartir en Facebook" style ="padding-right:5px;" ><div class="textocaja">Enviar este anuncio a Facebook</div></div>';
//   var lt =  document.createElement("a");
//	   lt.setAttribute("href","http://www.tuenti.com/share?url=" + urlACompartir);
//	   lt.setAttribute("Title","Compartir en Tuenti");
//	   lt.setAttribute("id","lt");
//	   lt.setAttribute("target","_blank");
//	   lt.style.color= "white";
//	   lt.innerHTML ='<img src="../images/icons/Tuenti.ico" alt="Compartir en Tuenti" style ="padding-right:5px;" ><span style="color: #564B47; font-family:Helvetica,Verdana,Arial,SunSans-Regular,Sans-Serif; font-size:9px; font-weight: bold;">Compartir en Tuenti </span>'; 
    var ltw = document.createElement("a");
    ltw.setAttribute("href", " http://twitter.com/home?status=" + tituloAnuncioCompartir + " - " + urlACompartir);
    ltw.setAttribute("Title", "Compartir en Twitter");
    ltw.setAttribute("id", "ltw");
    ltw.setAttribute("target", "_blank");
    ltw.style.color = "white";
    ltw.innerHTML = '<div class="cajaredondeada"><img src="../images/icons/twitter.png" alt="Compartir en Twitter" style ="padding-right:5px;" ><div class="textocaja">Enviar este anuncio a Twitter</div></div>';
//   var labelred = document.createElement("label");
//	   labelred.innerHTML = "<span class='titulo'>Comparte este anuncio en tus <span class='cambio_color'>redes sociales</span></span>";
//	   labelred.style.color= "#564B47"; 
//	   labelred.style.fontFamily ="Helvetica,Verdana,Arial,SunSans-Regular,Sans-Serif"; 
//	   labelred.style.fontWeight="bold";
//	   $("divEnlaceCompartir").appendChild(labelred);
    $("divEnlaceCompartir").appendChild(lf);
//	   $("divEnlaceCompartir").appendChild(lt);
    $("divEnlaceCompartir").appendChild(ltw);

}

function EnviarAnuncioCorreo() {
    //emailUsuario    
    if ($("correoCompartir").value != "") {
        var myRequest = new Request({
                url: '../usuarios/Operaciones.aspx',
                data: 'nombreUsuario=' + nombreUsuario + '&emailUsuario=' + emailUsuario + '&listaCorreos=' + $("correoCompartir").value + '&enlaceAnuncioCompartir=' + enlaceAnuncioCompartir + '&tituloAnuncioCompartir=' + tituloAnuncioCompartir,
                evalResponse: true
            });
        myRequest.get();
        if ($("correoCompartir").value.split(',').length > 1) {
            Sexy.alert('Hemos enviado un email a las direcciónes de correo proporcionadas.');
        } else {
            Sexy.alert('Hemos enviado un email a la dirección de correo proporcionada.');
        }
    } else {
        Sexy.alert('Caja de texto vacia.');
    }
}

var bVentanaNuevoAnuncio = false;

function ControlVentanaNuevoAnuncio(cVentanaNuevoAnuncio) {
    bVentanaNuevoAnuncio = cVentanaNuevoAnuncio;
}

function avisoUsuarioGratuito(portal) {
    var check = document.getElementsByTagName("input");

    for (var i = 0; i < check.length; i++) {
        if (check[i].checked == true) {
            if (check[i].id == portal) {
                check[i].checked = false;
            }
        }
    }
    SexyLightbox.display('pagoPremiun.html?&height=400&width=670');
}

function windowHeight() {
    var alto = 0;
    if (typeof(window.innerWidth) == 'number') {
        alto = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        alto = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        alto = document.body.clientHeight;
    }
    return alto;
}

function fillthescreen() {
    winH = windowHeight(); //This returns the screen heigth
    heightNeeded = winH - ((esExplorer) ? 100 : 170); //We need to substract the footer height
    heightcontent = heightNeeded - ((esExplorer) ? 105 : 30);
    heightcontentLeft = heightcontent - 30;
    heightcontentRight = heightcontent - 231; //102
    //($('seleccionar').style.height + $('insertarportales').style.height);
    if (typeof(window.innerWidth) != 'number') { //Explorer doesn't recognize minHeight
        $('content').style.height = heightNeeded - 6 + 'px'; //So, we use height (and explroer bug)
        $('left').style.height = heightNeeded - 6 + 'px';
        $('right').style.height = heightNeeded - 6 + 'px';
        $('left').style.maxHeight = heightNeeded - 9 + 'px';

    } else {
        $('content').style.minHeight = heightNeeded + 'px'; //For every other browser, we use minHeight
        $('left').style.minHeight = heightNeeded + 'px';
        $('right').style.minHeight = heightNeeded + 'px';
    }

    $('contentcontent').style.height = heightcontent + 'px';
    $('leftcontent').style.height = heightcontentLeft + 'px';
    $('rightcontent').style.height = heightcontentRight + 40 + 'px';


}
