

//______________________________________________________________________________________CLASES_PARA_LOS_LISTADOS 

function extendLists(scope) {
    var scope = scope || document;
    $('li:first-child', scope).addClass('first');
    $('li:last-child', scope).addClass('last');
	
    var numLi = $('.button-tabs').children().size();
    $('.button-tabs').addClass('numLi'+numLi);
}

//____________________________________________________________________________EVENTOS_ESPECIALES_PARA_LOS_ENLACES

function extendLinks(scope) {
    var scope = scope || document;
    $('a[rel=external]', scope).attr({
        target: '_blank'
    });
    $('a[rel=submit', scope).click(function() {
        $(this).closest('form').submit();
    });
}

//__________________________________________________________________________________________________ALTURA_CUERPO

function alturaCuerpo() {
    var altura = (parseInt($('#main-container').height()/51))*51;
    if(altura < '525') { altura = '525'; }
    // alert(altura);
    $('#left-col').css({"min-height":altura+"px"});
}

//______________________________________________________________________LISTA_RECUADROS_VS_TABLA_RECALCULO_ALTURA

$('.list-options-tab > li > a').live('click', function() {
    alturaCuerpo()
});

//______________________________________________________________________________________________CHECK_FORMULARIOS

function $F(idForm, str,tipo) {
		
		var valor = $('#'+idForm+' :input[name='+ str +']').val();
		
		switch(tipo)
    {
     	case 'texto':
					var titulo = $('#'+idForm+' :input[name='+ str +']').attr("title");
					if(valor.length < 3 || valor == titulo) { 
							$('#'+idForm+' :input[name='+ str +']').addClass('error');
							return false; 
					}
			break;
			case 'mail':
					var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
					if (!filter.test(valor)) {
			        $('#'+idForm+' :input[name='+ str +']').addClass('error');
							return false; 
		      }
			break;
			case 'check':
					if ( !$('#'+idForm+' input[name='+ str +']').attr('checked') ){ 
				      $('#'+idForm+' span').addClass('error');
				      return false; 
				  }
					
			break;
		}
}

//_____________________________________________________________________________________________SUBMIT_FORMULARIOS

function submitFormularios() {

		 $(".formularios").submit(function(){
		 	
		 		var ok = true;
		 		var idForm = $(this).attr("id");

		 		
		 		switch(idForm)
        {
		        case 'left-contact-form': 
		        
		        		if( $F(idForm,"name","texto") == false ) { ok = false }
		        		if( $F(idForm,"email","mail") == false ) { ok = false }
		        		if( $F(idForm,"aviso_legal","check") == false ) { ok = false }
		        		var procesaForm = 'contactar';
		
		        break;
		        case 'enviar-amigo-form':
		        		
								if( $F(idForm,"name","texto") == false ) { ok = false }
		        		if( $F(idForm,"email","mail") == false ) { ok = false }
		        		if( $F(idForm,"nameAmigo","texto") == false ) { ok = false }
		        		if( $F(idForm,"emailAmigo","mail") == false ) { ok = false }
		        		if( $F(idForm,"aviso_legal","check") == false ) { ok = false }
		        		var procesaForm = 'enviar_amigo';
		        		
		        break;
		        case 'result-null-form':
		        
		        		if( $F(idForm,"name","texto") == false ) { ok = false }
		        		if( $F(idForm,"email","mail") == false ) { ok = false }
		        		if( $F(idForm,"aviso_legal","check") == false ) { ok = false }
		        		var procesaForm = 'contacto_send';
		        break;
      	}
      	
      	var datos = $(this).serialize();

      	if(ok == true) {

      		  $("#"+idForm+" div.lcf").hide();
      		  $("#"+idForm+" div.lcf-se").show();
      		
            $.ajax({
                type: "POST",
                url: BASE_URL+""+LANG+"/home/"+procesaForm,
                data: datos,
                success: function( resp ){
                		$("#"+idForm+" div.lcf-se").hide();
                    if ( resp == "OK" ){
                        $("#"+idForm+" div.lcf-ok").show();
                        if( idForm != "enviar-amigo-form") { 
                        		ppcconversion(); 
                        		// $("#conversion").load(BASE_URL+"conversor.php");
                        }
                    }else{
                        $("#"+idForm+" div.lcf-er").show();
                    }
                },
                error: function(){
                		$("#"+idForm+" div.lcf-se").hide();
                    $("#"+idForm+" div.lcf-er").show();
                }
            });
        }

		 		return false;
		 });

}

//________________________________________________________________________________________CARGAR_IFRAME-CONVERSOR

function ppcconversion() {
	
		var iframe = document.createElement('iframe');
		iframe.style.width = '0px';
		iframe.style.height = '0px';
		document.body.appendChild(iframe);
		iframe.src = 'http://www.nninmobiliaria.es/conversor.php';
		
};

//___________________________________________________________________________________FLOTACION_FORMULARIO_DERECHO

function leftFlotante() {

		var offset = $("#left-flotante").offset();
    var topPadding = 15;
    $(window).scroll(function() {
    			if ($("#left-flotante").height() < $(window).height() && $(window).scrollTop() > offset.top) {
                
           		$("#left-flotante").addClass('formFijo');
                   
          } else {
            	
            	$("#left-flotante").removeClass('formFijo');
            	
          };
		});
}

//_______________________________________________________________________________________________ACTIVAR_FANCYBOX

function activarFancyBox() {

		$("a.fancy").fancybox({ 'padding':'0','centerOnScroll':true }); // , 'showCloseButton':false
		
}

function activarZonaFancyBox() {

		$("a.fancyZona").fancybox({ 
				'padding':'0',
				'centerOnScroll':true,
				'onClosed': function() {
					
					lanzarSubmit('cualquiera-form');
					
				}
		}); 
		// , 'showCloseButton':false
		
}

//_____________________________________________________________________ LLAMADA_GLOBAL_PARA_LAS_FUNCIONES_DEL_DOM

function extendDOM(scope) {
    var scope = scope || document;
    extendLists(scope);
    extendLinks(scope);
    alturaCuerpo();
    submitFormularios();
    submitBuscador();
    leftFlotante();
    activarFancyBox();
    activarZonaFancyBox();
}

$(function() {
		$("ul.detalle-tabs").tabs("div.detalle-panes > div");
    extendDOM(document);
});




//_______________________________________________________________________________________FORMULARIOS_DE_BUSQUEDA

//__________________________________________________________________LANZAMOS_SUBMIT

function lanzarSubmit(idForm) {
	
    var splitForm = idForm.split("-");
    if(splitForm[1]=='form') { 
    	
    	var altura = $('#search-top-container').height();
    	$('#search-top-container').css({"height":altura+"px"});
    	$(".formTop").hide();   	
    	$(".form-buscador").submit();
 	
    }
	
}

//___________________________________________________________________________SUBMIT

function submitBuscador() {

		 $(".form-buscador, .form-texto").submit(function(){
				
					var idForm = $(this).attr("id");
					var tipo = idForm.split("-");
										
					switch(idForm)
			    {
						case 'viviendas-home-form':
						case 'viviendas-form':
						case 'viviendas-texto-form':
					        
								var alqventa     = $('#'+idForm+' input:hidden[name=alquiler]').val();
        				var zona         = ($('#'+idForm+' input:hidden[name=zona]').val())? $('#'+idForm+' input:hidden[name=zona]').val() : 'Catalunya' ;
        				var habitaciones = ($('#'+idForm+' input:hidden[name=habitaciones]').val())? $('#'+idForm+' input:hidden[name=habitaciones]').val() : '0,1,2,3,4' ;
        				var precio       = ($('#'+idForm+' select[name=precio-'+alqventa+']').val()) ? $('#'+idForm+' select[name=precio-'+alqventa+']').val() : '99999999';
								
								var masUrl = "/viviendas/search/"+zona+"/"+alqventa+"/"+habitaciones+"/"+precio;
						break;
						
						case 'oficinas-home-form':
						case 'oficinas-form':
						case 'oficinas-texto-form':
						case 'locales-home-form':
						case 'locales-form':
						case 'locales-texto-form':					
								
								var zona         = ($('#'+idForm+' input:hidden[name=zona]').val())? $('#'+idForm+' input:hidden[name=zona]').val() : 'Catalunya';
        				var rango   		 = ($('#'+idForm+' select[name=rango-'+tipo[0]+']').val()) ? $('#'+idForm+' select[name=rango-'+tipo[0]+']').val() : 'sin_minimo';
        				var precio   		 = ($('#'+idForm+' select[name=precio-'+tipo[0]+']').val()) ? $('#'+idForm+' select[name=precio-'+tipo[0]+']').val() : '99999999';
								var tipologia    = ($('#'+idForm+' select[name=tipologia-'+tipo[0]+']').val()) ? $('#'+idForm+' select[name=tipologia-'+tipo[0]+']').val() : 'indiferente';
								
								if(tipo[0] == 'locales') { var tipologia = '0'; }
						
								var masUrl = "/"+tipo[0]+"/search/"+zona+"/alquiler/"+rango+"/"+precio+"/"+tipologia;
						
						break;
						
						case 'naves-home-form':
						case 'naves-form':
						case 'naves-texto-form':
						
								var zona         = ($('#'+idForm+' input:hidden[name=zona]').val())? $('#'+idForm+' input:hidden[name=zona]').val() : 'Catalunya' ;
        				var precio   		 = ($('#'+idForm+' select[name=precio-naves]').val()) ? $('#'+idForm+' select[name=precio-naves]').val() : '99999999' ;
						
								var masUrl = "/naves/search/"+zona+"/alquiler/"+precio;
						
						break;
					}
					
					
					if( tipo[1] == 'texto' ) {
						
							var texto = $('#'+idForm+' input:text[name=texto]').val();
							var textTitle = $('#'+idForm+' input:text[name=texto]').attr('title');
							
							if(texto != textTitle) {
									window.location = BASE_URL+""+LANG+masUrl+"/"+texto;
							}
						
					} else {
						
						window.location = BASE_URL+""+LANG+masUrl;
						
					}
					
				
					
					return false;							
		 });		
}



//_________________________________________________________________LIMPIAMOS_HIDDEN

$(function() {
	
    $('.form-buscador :input[type="hidden"]').each(function () {
				
        if($(this).val() != $(this).attr("title")) {
            $(this).val($(this).attr("title"));
        }		
				
    });
});


//___________________________________________________________________SELECCIONABLES

$('label.opciones a').live('click', function() {
			
    var objeto = $(this).siblings(':input[type="hidden"]');
    var padreId = $(this).parents('label:first').attr("id");
		
    if($(this).attr("class")=="on") {
        $(this).removeClass('on');
    }
    else {
        $(this).addClass('on');
    }
		
    var newValue = "";
    $('#'+padreId+' a').each(function () {
			
        if($(this).attr("class")=="on") { 
            if(newValue) {
                newValue += ',';
            }
            newValue += $(this).attr("href");
        }
			
    });
		
    objeto.val(newValue);
    
    lanzarSubmit($(this).parents('form:first').attr("id"));

    return false;
});

//____________________________________________________________________________RADIO

$('label.radio a').live('click', function() {
		
    if($(this).attr("href")!=$(this).siblings(':input[type="hidden"]').val())
    {
				var padreId = $(this).parents('label:first').attr("id");
				$('#'+padreId+' a').removeClass('on');
					
				$(this).siblings(':input[type="hidden"]').val($(this).attr("href"));	
			  $(this).addClass('on');
			  
			  var idForm = $(this).parents('form:first').attr("id");
			    
			  if( idForm == 'viviendas-form') {
			    
			  		$('#precio-alquiler, #precio-compra').css({'display':'none'}); 
			    	$('#precio-'+$(this).attr("href")).css({'display':'block'}); 
							
			  }
			  
			  lanzarSubmit(idForm);
		}
		
		

    return false;
    
});

//_____________________________________________________AÑADIR_QUITAR_ZONA_POR_BOTON

$('.botonesZona > ul > li > a').live('click', function() {

    if($(this).attr("class") == 'on') {
        offZone($(this));
    } 
    else {
        onZone($(this));
    }

    return false;
		
});

//_______________________________________________________________AÑADIR_ZONA_X_MAPA

function add_zone(value){
	
    var obj = $('.botonesZona > ul > li > a[rel='+value+']');
    
    if(obj.attr("class") != 'on') {
        onZone(obj);
    }
    
    
}

//_____________________________________________________________________ACTIVAR_ZONA

function onZone(value) {
	
    value.addClass('on');
    var selLink = value.attr("rel");
    var selText = value.text();
    var idForm = $('#fancy-seleccion-zona').attr("rel");
    refreshInput(idForm);
	
		$('#'+idForm+' .zones-selected').append('<a rel="'+selLink+'" class="on">'+selText+'</a>');
}


//__________________________________________________________________DESACTIVAR_ZONA

function offZone(value) {
	
    value.removeClass('on');
	
    var idForm = $('#fancy-seleccion-zona').attr("rel");
    $('#'+idForm+' > div.formTop > div.opt > div.zones-selected > a:[rel='+value.attr("rel")+']').remove();
    refreshInput(idForm);
}

//__________________________________________________________________REFRESCAR_INPUT

function refreshInput(idForm) {
	
    var newValue = "";
    $('.botonesZona > ul > li > a').each(function () {
			
        if($(this).attr("class")=="on") { 
            if(newValue) {
                newValue += ',';
            }
            newValue += $(this).attr("rel");
        }
			
    });
	
    document.forms[idForm].elements["zona"].value = newValue;
}

//_______________________________________________________________DESACTIVAR_ZONA_II

$('.zones-selected > a').live('click', function() {

    var idForm = $(this).parents('form:first').attr("id");		
    $(this).remove();
		
    var newValue = '';
    $('#'+idForm+' > div.formTop > div.opt > div.zones-selected > a').each(function () {
			
        if(newValue) { newValue += ','; }
        newValue += $(this).attr("rel");
			
    });
	
    document.forms[idForm].elements["zona"].value = newValue;
    
    lanzarSubmit(idForm);
    return false;
		
});

//_____________________________________________________________________________________________FORMULARIO_DERECHO


$('.formularios :input[type="text"], .formularios :input[type="textarea"], .form-texto :input[type="text"]').live('focusin focusout', function(event) {
		
		var valor = $(this).val();
    var comp = $(this).attr("title");
		
    if(event.type=="focusin") {
    		
    		$(this).removeClass('error');
        if(valor==comp) {
            $(this).val('');
        }
			
    }else{

        if(valor=="") {
            $(this).val(comp);
        }
    }
	 
});

$("#labelLegal").live('click', function (event) {
		$("#labelLegal > span").removeClass('error');
});

//________________________________________________________________________________________________________IMPRIMIR


function imprimirDiv(div) {

	$("#"+div).printElement();
	
}


//_______________________________________________________________________________________________________FAVORITOS

$(".search_favoritos, .addFav").live('click', function(){
	
        var t = $(this);
        $.ajax({
            type: "GET",
            url: BASE_URL+"index.php/"+LANG+"/favoritos/agregar_favorito/"+$(this).attr('rel'),
            success: function( resp ){
                if ( resp == "ADD" ){
                    t.addClass('active');
                    jQuery.noticeAdd({
                            text: '<p class="add">'+ADDFAV+'</p>',
                            stay: false
                    });
                }
                if ( resp == "DEL" ){
                    t.removeClass('active');
                    jQuery.noticeAdd({
                            text: '<p class="del">'+DELFAV+'</p>',
                            stay: false
                    });
                }
                actualize_favorites();
            }
        });
        
});

//______________________________________________________________________SUGEST_HOME

$('.form-texto input[name=texto]').live('focusin', function(event) {
	
		var idForm = $(this).parents('form:first').attr("id");
		var tipo = document.forms[idForm].elements['tipo-inmueble'].value;
		var alquiler = document.forms[idForm].elements['alquiler'].value;
		
		$(this).autoComplete({
			ajax: BASE_URL+''+LANG+'/'+tipo+'/sugest',
			postData: {
				tipo: tipo,
				alquiler: alquiler
			},
			postFormat: function(event, ui){
				// Add the current timestamp to each request
				ui.data.requestTimestamp = (new Date()).getTime();
	
				// Return the data object to be passed with the ajax function
				return ui.data;
			}
		});
	 
});
