var nnn;
function slideSwitch(id) {
    var $active = $('#'+id+' div.active');
 
    if ( $active.length == 0 ) $active = $('#'+id+' div:last');
 
    // use this to pull the images in the order they appear in the markup
    var $next =  $active.next().length ? $active.next()
        : $('#'+id+' div:first');
 
    // uncomment the 3 lines below to pull the images in random order
 
    // var $sibs  = $active.siblings();
    // var rndNum = Math.floor(Math.random() * $sibs.length );
    // var $next  = $( $sibs[ rndNum ] );
 
    $active.removeClass('active');
    $next.addClass('active');
}

$(function() {
    setInterval( "slideSwitch('slideshow')", 10000 );
    setInterval( "slideSwitch('slideshow2')", 10000 );
});

$(document).ready(function(){
	
    $("div.msgok").fadeOut(5000);
    //$("div.errors").fadeOut(5000);
 
    // Buscador a 0
	$("input#textoLibre").click( 
		    function() {	    	
		    	$(this).val('');
		    	} 
		);	    
  
	
  // Funcion ajax para obtener los tipos de operaciones.
  $(function(){
    var url=$("input.t_anuncio_url").val();
	$("select#cat").change(function(){
		$.post(url,{id: $(this).val()}, function(j){
             $("div#features").fadeIn(1000);
             $("div#features").html(j);
              $(document).ready(function(){
                    //$('label.pre').labelOver('over');
	                  $('.currency').blur(function()
	                	        {
	                	            $('.currency').formatCurrency();
	                	        });            	  
                    })
		})
	})
})

  // Funcion para cambiar el titulo de particular o empresa.
  $(function(){
	$("#anuncio_de_e").click(function(){
         $("#nomb_e").fadeIn(1000);
         $("#serv_e").fadeOut(1000);
        })
})
  // Funcion para cambiar el titulo de particular o empresa.
  $(function(){
	$("#anuncio_de_p").click(function(){
         $("#nomb_e").fadeOut(1000);
         $("#serv_e").fadeIn(1000);
        })
})

// Funcion para mostrar la busqueda avanzada
$(function(){
	$("a.ad_search").click(function(){
            $("#ad_search").fadeIn(1000);
        })
})

uploadImg ();
// La funcion para el upload de fotos.
function uploadImg()
{
	var nm=$("#upload_sp").attr("maxLength");
	nnn=nm;
		if (nm==0)
		$("#upload_images").hide();
		else
			$("#upload_images").show();

	  $('#upload_sp').MultiFile({
		  accept:'gif|jpg|jpeg', STRING: {
		   remove:'[Quitar imagen]',
		   selected:'Selecionado: $file',
		   denied:'Los ficheros $ext no estan permitidos. Ficheros permitidos: .gif, .jpg, .jpeg'
		  }
             
		 });	  
}

// Funcion para la galeria de imagenes
$(function() {
		
	var thumbLinks = $('#thumb a');
	var thumbCount = thumbLinks.length;
	var thumbImages = $('#thumb img');
	var image = $("#main_img");
	var fadeSpeed = "fast";

	image.hide();
	setTimeout("$('#main_img').fadeIn('fadeSpeed')", 3);

	thumbLinks.each(function(i) {

		var current = (i+1);
	

			this.onclick = function () {

				var imageUrl = this.getAttribute('href'); 
					
				var imageDescription = $(this).find("img").attr("alt");

				image.fadeOut(fadeSpeed, function() {

					$("#main_img img").attr({ src: imageUrl, alt: imageDescription});

					setTimeout("$('#main_img').fadeIn('fadeSpeed')", 3); 
				})


				return false;	
			}
	})
});	

jQuery.fn.maxLength = function(max){
	this.each(function(){
		//Get the type of the matched element
		var type = this.tagName.toLowerCase();
		//If the type property exists, save it in lower case
		var inputType = this.type? this.type.toLowerCase() : null;
		//Check if is a input type=text OR type=password
		if(type == "input" && inputType == "text" || inputType == "password"){
			//Apply the standard maxLength
			this.maxLength = max;
		}
		//Check if the element is a textarea
		else if(type == "textarea"){
			//Add the key press event
			this.onkeypress = function(e){
				//Get the event object (for IE)
				var ob = e || event;
				//Get the code of key pressed
				var keyCode = ob.keyCode;
				//Check if it has a selected text
				var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
				//return false if can't write more
				return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
			};
			//Add the key up event
			this.onkeyup = function(){
				//If the keypress fail and allow write more text that required, this event will remove it
				if(this.value.length > max){
					this.value = this.value.substring(0,max);
				}
			};
		}
	});
};


  // Funcion para borrar las imagenes.
$(function(){
    var url=$("input.located_url_img").val();
	var a;
    $(".img_img").click( function(){
		var cont;
		
		if ($("#upload_sp").attr("maxlength")==null){
			cont=nnn+1;
		}else
			cont = parseInt($("#upload_sp").attr("maxlength"))+1;              
		
		var id_ref=$(this).attr("href");   
		// Añado 1 mas.
		//$("#upload_sp").maxLength(cont);
	//	alert(cont);
		$("#upload_sp").attr("maxlength",cont);
		$.getJSON(url,{id_img: id_ref}, function(x){
				div_id="#"+x[0].id;
				$(div_id).fadeOut(1000);
				
				a="<h2><?php echo $str_lang['lang_fotos_anuncio_nuevas']?> <?php echo getMessageError($error,'file')?></h2>";
				a+="<input type='file' id='upload_sp' name='upload_file[]'  maxlength='"+cont+"'/>";
				$("#upload_images").empty();
				$("#upload_images").html(a);
				uploadImg();
			   })				                                                        
	});
  })
      
     /* Mostrar div de recordatorio de contraseñaa */
    $("a.link_forgot").toggle(
    	function(){$("#forgot").fadeIn(1000);},
    	function(){
    		$("#forgot").fadeOut(1000);
    		$("p.ok").hide();
    		$('#email').removeAttr("disabled");
    		$('#b_forgot').removeAttr("disabled");
    		$('#email').val('')}
    	)
	
	/* Recordar contrase�a */
	$(function(){
	    var url=$("#located_url").val();
		$("#b_forgot").click(function(){
				$.post(url,{email: $("#email").val()}, function(j){
				// Ejecuta el php, pero no hace nada mas
				})		
				$('#email').attr("disabled", true);
				$('#b_forgot').attr("disabled", true);
				$("p.ok").fadeIn(1000);
		})
	})    
  
	$("h3.asociados a").toggle( 
	    function() {
	    	$("div."+$(this).attr("class")+"").fadeIn();
	    	},
	    function() {$("div."+$(this).attr("class")+"").fadeOut();} 
	); 

	/* Envio formulario de pago */
	//$("#frm_pay").submit();

        /* Funcion hover para imagen */
	$(".logo_isla img").hover(function(){		
		var image = $(".logo_isla img").attr('alt');		
	  $(".logo_isla img").attr({ src: "http://www.euromercadillo.com/img/" +image+"_hover.jpg" });
	  },function(){
		  var image = $(".logo_isla img").attr('alt');
	  $(".logo_isla img").attr({ src: "http://www.euromercadillo.com/img/" +image+".jpg" });
	  });
	
	
	
	
	/* Funcion para formatear el currency */
        $('.currency').blur(function()
        {
            $('.currency').formatCurrency();
        });
        
        //$('#panelfrm #enviar').click(function()
        //{
            $('.currency').formatCurrency();
        //});
        
        
        /* Filtros categoria en busqueda */
        $(function(){
      	$("select#str_cat").change(function(){
      		
      		var cat = $(this).val();
                var url=$("#located_url").val();

                $.getJSON(url,{idcat: cat}, function(j){

                    var x = 0;
                    for (var i = 0; i < j.length; i++) {

                       if (x == 0) {
                           
                            if (j[i].id == 198) // inmobiliaria
                            {
                                    $("table.motor").show();
                                    $("table.inmo").hide();
                                    $("#showTipoOp").show();
                                    x=1;
                            }
                            else if (j[i].id == 190) // coches
                            {
                                    $("table.motor").hide();                                   
                                    $("table.inmo").show();
                                    $("#showTipoOp").show();
                                    x=1;
                            }
                            else if (j[i].id == 286 || j[i].id == 244)
                            {
                                    $("table.motor").hide();
                                    $("table.inmo").hide();
                                    $("#showTipoOp").hide();
                                    x=1;
                            }
                       }

                   }

                   if (x==0){
                        $("table.motor").hide();
                        $("table.inmo").hide();
                        $("#showTipoOp").show();
                   }
                })

      	})
      })        


   /* Detectar navegador */
   var msie= $.browser.msie();
   if ($("#actualizarnavegador").length==0) {// Si no existe el id, estamos en cualquier pagina
    if ((msie == true) && ($.browser.version.number()<7)) { // defaults to undefined       
        document.location.href="http://www.euromercadillo.com/su-navegador-debe-ser-actualizado/";
    }
   }
   else {
        alert("Su navegador es una versión antigua, y no soporta la tecnología web de este portal. Actualícelo a una versión superior (Internet Explorer 8.0 o superior, Firefox 2.0 o superior)"); // defaults to 'Unknown'       
   }

    $("#form1 select#provincias").change(function(){
        document.location.href= $(this).val();
    });


        $(function(){
      	$(".check_oferta").click(function(){

      		var id = $(this).val();
                var pack=$("#pack").val();
                var url=$("#located_url_oferta").val();

                $.getJSON(url,{id: id, pack:pack}, function(j){
                    if (j[0].ret ==1) {
                        alert("Has superado el máximo de anuncios como ofertas exclusivas");
                        $("#oferta_"+j[1].id).attr("checked", false);
                    }
                    else alert("Oferta Exclusiva actualizada");
                })
        })
        });



 /* FIN DOCUMENT READY */
 
    })
 /* FIN DOCUMENT READY */


//Funcio para lista inmuebles.
  $(function(){
    var url=$("#located_url").val();
	$("a.list_link").click(function(){
		$("#carga_img").fadeIn(1000);
		$.post(url,{id: $(this).attr("href")}, function(j){
             $("div#result_content").html(j);
             $("#carga_img").fadeOut(1000);
		})
	})
})

// Funcion mostrar ocultar capas.
$(function() {
		
	var links = $('span.link a');
	var linksCount = links.length;
	var fadeSpeed = "fast";
	
	links.each(function(i) {
		var current = (i+1);
			this.onclick = function () {
	 			$("#"+i).toggle();
			}
	})
});
