function changeActivityAfterCategoryVisitcalvia(){
	function gup( name ) {
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null )
			return "";
		else
			return results[1];
	}
    $('#id_activity option[value!=-1]').remove();
    $.get('/general/submenu_company_search.js/',{category:$('#id_category').val()},function(d){
        d=d.split('||');
        for(i=0;i<d.length-1;i++){
            t=d[i].split('##');
			selected = '';
            $('#id_activity').append('<option value="'+t[0]+'">'+t[1]+'<\/option>');
        }
		if (gup('activity'))
			$('#id_activity').val(gup('activity'));

    });
}
function resetSendFriendForm(){
    $('#send_friend').slideUp();
    $('#send_friend > .real_content').show();
    $('#send_friend > .result').hide();
    $('#send_friend > .loading_image').hide();
}
$(function(){

// efecto campos formulario
	$("input").click(function(){if($(this).attr("title")==$(this).val())$(this).val("");});
	$("input").blur(function(){if(!$(this).val())$(this).val($(this).attr("title"));});
	$("#comment").click(function(){if($(this).attr("title")==$(this).val())$(this).val("");});
	$("#comment").blur(function(){if(!$(this).val())$(this).val($(this).attr("title"));});

// imprimir
$('.print').click(function(){
    window.print();
    return false;
});

// Efecto slide cabecera
	$('ul#fotillosSlide').innerfade({
		speed: 2000,
		timeout: 5000,
		type: 'sequence',
		containerheight: '406px'
	});
	$('ul#fotillosSlide2').innerfade({
		speed: 1000,
		timeout: 5000,
		type: 'sequence',
		containerheight: '406px'
	});

	$('.fade').innerfade({
		speed: 1000,
		timeout: 6000,
		type: 'random_start',
		containerheight: '1.5em'
	});

// Paso imagen playas
	$('.contImagenPlayas a').click(function(){
		p=$('.contImagenPlayas a').index(this);
		p++;
		p='0'+''+p;
		$('.contImagenPlayas a[class=select]').removeClass('select');
		$(this).addClass('select');
		src=$(this).find('img').attr('src');
		$('.fotoPlaya').find('img').attr('src',src);	
		$('.fotoPlaya').find('span').html(p);
		return false;
	});
	
// datePicker
    lang=$('#language').val();
    lang=(typeof(lang)!='undefined')?lang:'es';
    $.datepicker.setDefaults($.datepicker.regional[lang]);
	$('.date-pick').datepicker();
//	$('.date-pick2').datepicker({startDate:'01/01/1996'});
    dd=new Date('1980/01/01');

    $('.date-pick-birthdate').datepicker({showOn: 'both', buttonImage: '/site_media/img/calendar.gif', changeMonth: true, changeYear: true, yearRange: '1945:2000', defaultDate:dd, dateFormat:'dd/mm/yy', firstDay: 1});
    $('.date-pick-datesearch').datepicker({showOn: 'both', buttonImage: '/site_media/img/calendar.gif', changeMonth: true, changeYear: true, yearRange: '-5:+5', dateFormat:'dd/mm/yy', firstDay: 1});

// Efecto cargar errores en la misma pagina
	$('#login').keyup(function(e){
	    e.preventDefault();
	    if(e.keyCode==13){
	            $('#bt-login').trigger('click');
	            return false;
	            }
	});

    // $('#bt-login').click(function(){
    //  $.post('/login_home',{username:$('#username').val(),password:$('#password').val()},function(d){
    //      $('.error span').hide();
    //      if(parseInt(d.charAt(0))==0){
    //          url=d.split('|');
    //          window.location=url[1];
    //      }else{
    //          $('#log'+d.charAt(0)).show();
    //      }
    //  });
    // });

// Efecto abrir cerrar pestanyas y efecto opacidad en busqueda avanzada
	$('.clickable').click(function(e){
		e.preventDefault();
		apu=$(this).parent().parent();
		if(parseInt(apu.css('left'))==-35){
			apu.animate({left:'-265px'},300,function(){swapImg(apu,0);});
			$('.divBlack').fadeOut(300);
		}else{
			apu.animate({left:'-35px'},300,function(){swapImg(apu,1);});
			$('.divBlack').fadeIn(300);
		}
	});

// Efecto seleccionar deseleccionar lista en eventos relacionados del perfil
	$('.botonesAutorizaNo a').click(function(){
		if($(this).hasClass('add')){e=0;m=1;}else{e=1;m=0;}
		obj=$('.autorizaNoAutoriza:eq('+e+') option:selected');
		if(!isNaN(parseInt(obj.val()))){$('.autorizaNoAutoriza:eq('+m+') select').append(obj);}
		return false;
	});

// Efecto ocultar y mostrar mapa.
	$('.verMapa').click(function(){
		$('.googleMaps').slideToggle(500);
		map.checkResize();
		return false;
	});

// Efecto acordeon en menu izquierdo lovin
	$('.tituloAbrir').click(function(){
		$(this).toggleClass('cerrado').next().slideToggle(500);
		return false;
	});

// Efecto mostrar comentario
	$('.commentOffer').click(function(){
		$(this).toggleClass('cerrado');$('#comment_form').slideToggle(500);
		return false;
	});

// Efecto mostrar campo enviar a un amigo
	$('.friend').click(function(){
		$(this).toggleClass('seleccionado');$('#send_friend').slideToggle(500);
		return false;
	});

// Efecto puntuacion en perfil oferta shoppin
	$('.opcionesUsuario span a').hover(function(){
		if(!$(this).parent().parent().hasClass('votado')){
			var old=$(this).find('img').attr('src');
			old=old.replace('negativo','positivo');
			$(this).find('img').attr('src',old);
		}
	},function(){
		if(!$(this).parent().parent().hasClass('votado')){
			var old=$(this).find('img').attr('src');
			old=old.replace('positivo','negativo');
			$(this).find('img').attr('src',old);
		}
	});

	$('.opcionesUsuario span a').click(function(){
		apa=$(this).parent().parent();
		if(!apa.hasClass('votado')){
			rating=apa.find('span').find('a').index(this);
			type=apa.find('span').attr('class');
			if(type=='Post'){
			    id=apa.find('span').attr('id').replace('post','');
			}
			if(type=='User'){
			    id=apa.find('span').attr('id').replace('user','');
			}
            if(type=='UserPhoto'){
                id=apa.find('span').attr('id').replace('photo','');
            }
            if(type=='UserVideo'){
                id=apa.find('span').attr('id').replace('video','');
            }
			var old=$(this).find('img').attr('src');
			$.post('/set_rating',{rating:rating,type:type,id:id},function(d){
				old=old.replace('negativo','positivo');
				for(i=0;i<=rating;i++){apa.find('span').find('a').eq(i).find('img').attr('src',old);}
				apa.addClass('votado');
				anya=apa.prev().prev();
        		for(i=0;i<anya.find('img').length;i++){
        		    presrc=anya.find('img').eq(i).attr('src');
        		    if(parseInt(d)>=i){
        		        if(presrc.indexOf('positivo')==-1){
        		            presrc=presrc.replace('negativo','positivo');
        		            anya.find('img').eq(i).attr('src',presrc);
        		        }
        		    }else{
        		        if(presrc.indexOf('negativo')==-1){
        		            presrc=presrc.replace('positivo','negativo');
        		            anya.find('img').eq(i).attr('src',presrc);
        		        }
        		    }
        		}

			});
		}
		return false;
	});

	$('#id_offer-zone,#id_offer-theme,#id_offer-tags').change(function(){
	    z=$('.zone').val();
	    th=$('#id_theme').val();
	    ts=$('#id_tags').val();
	    $.post('/general/related_content.js/',{zone:z,theme:th,tags:ts},function(d){
	        $('#help_list option').each(function(){if(!$(this).is(':selected')){$(this).remove();}});
	        for(i=0;i<d.length;i++){
	            if($('#help_list option[value='+d[i].pk+']').length==0){
	                $('#help_list').append('<option value="'+d[i].pk+'">'+d[i].fields.title+'</option>');
                }
	        }
	    },'json');
	});

	$('#save_profile').click(function(){
	    $('#related_contents option').each(function(){$(this).attr('selected','selected')});
	    $('#profile').submit();
	});

	if($('#id_profile-activity').attr('id')=='id_profile-activity'){
	    setText($('#id_profile-activity'));
	    setTextDos($('#id_profile-zone'));
	}

	$('#check-all').click(function(){
	    if($(this).is(':checked')){
	        $('.checks input[type=checkbox]').attr('checked','checked');
	    }else{
	        $('.checks input[type=checkbox]').removeAttr('checked');
	    }
	});

    if(typeof($('#id_offer-title'))!='undefined'){if($('#id_offer-title').val()!=''){$('.containerOferta').show(); }}

	$('#id_profile-activity').change(function(){setText($(this));});
	$('#id_profile-zone').change(function(){setTextDos($(this));});

    $('#favorites').click(function(e){
        e.preventDefault();
        $(this).addClass('add');
        $.post('/general/add_favorite.js/',{type:$(this).next().text(),id:$(this).next().next().text()});
	});

    $('.bt_del_fav').click(function(e){
        e.preventDefault();
        q=$(this);
        $.post('/general/del_favorite.js/',{id:$(this).next().text()},function(r){
            if(r=='ok_cool'){q.parents('div.element').remove();window.location=window.location;}
        });
    });
    

	$('#id_category').change(changeActivityAfterCategoryVisitcalvia);
    
    var mostListUrl = $('.pestas a').eq(1).attr('href');
    if (mostListUrl){
        mostList(mostListUrl);
    }

	$('.pestas a').click(function(){
	    mostList($(this).attr('href'));
	    return false;
	});

    function mostList(url){
        $('.loMas li').remove();
        s=$('.pestas').prev().html();
	    $.post(url,{t:s},function(d){
	        d=d.split('||');
	        for(i=0;i<d.length-1;i++){
	            c=d[i].split('##');
	            $('.loMas').append('<li><a href="'+c[1]+'">'+(i+1)+'. '+c[0]+'<\/a><\/li>');
	        }
	    });

    }

	$('#send_friend').submit(function(){
	    type=$('#send_friend > [name=type]').val();
	    id=$('#send_friend > [name=id]').val();
	    d=$('#destination').val();
	    m=$('#message').val();
	    if(d!=''&&m!=''&&validMail(d)){
            $.post('/general/send_mail/', $('#send_friend').serialize() ,function(d){
                $('#send_friend > .result').html(d);
                $('#send_friend > .loading_image').slideUp();
                $('#send_friend > .result').slideDown();
                window.setTimeout("resetSendFriendForm()", 3000);
            });
            $('#send_friend > .real_content').slideUp();
            $('#send_friend > .loading_image').slideDown();
	    };
        return false;
	});
	
	// Efecto tabs
	$('#tabs a').click(function(){
		$('#tabs a').removeClass('select');
		$(this).addClass('select');
	});
	
	$('#tabs2 a').click(function(){
		$('#tabs2 a').removeClass('select');
		$(this).addClass('select');
	});
});
    function validMail(string){
        var email_re=/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
		if (email_re.test(string)) {
			return true;
		}else{
		    return false;
		}
	}

    function setText(obj){if(obj.val()!=''){$.post('/general/category_finder.js/',{activity:obj.val()},function(d){$('#category').val(d);});}}
    function setTextDos(obj){if(obj.val()!=''){$.post('/general/commercial_zip_street_finder.js/',{zone:obj.val()},function(d){
        d=d.split('||');
        curCity=d[0];
        $('#commercial_zone').val(d[1]);
        $('#zip_code').val(d[2]);
        d=d[3].split('|');
        $('#id_profile-street option').remove();
        for(i=0;i<d.length;i++){
            if(d[i]!=''){
                t=d[i].split('##');
                $('#id_profile-street').append('<option value="'+t[0]+'">'+t[1]+'<\/option>');
            }
        }
		if (curCity!='') {
			$("#id_profile-location").val('');
			$("#id_profile-latitude").val('');
			$("#id_profile-longitude").val('');
			$("div.mapinfo").hide();
		}
		if ($("div.mapinfo").css("display") == "none") {
			$("div.mapinfo").show();
			$.getScript("http://maps.google.com/maps?file=api&v=2.x&key=" + $("#apikey").text() + "&async=2&callback=initMap");
		} else {
			googlemaps.searchLocation();
		}


    });}}

	function swapImg(obj,t){
		img=obj.find('.img');
		src=img.attr('src');
		if(t==0){
			src=src.replace('2.gif','.gif');
			obj.removeClass('open');
		}else{
			src=src.replace('.gif','2.gif');
			obj.addClass('open');
		}
		img.attr('src',src);
	}

/*
 * Tooltip script
 * powered by jQuery (http://www.jquery.com)
 *
 * written by Alen Grakalic (http://cssglobe.com)
 *
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */

this.tooltip = function(){
	/* CONFIG */
		xOffset = -20;
		yOffset = -100;
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
	/* END CONFIG */
	$("a.tooltip").hover(function(e){
		this.t = this.title;
		this.title = "";
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },

	function(){
		this.title = this.t;
		$("#tooltip").remove();
    });
	$("a.tooltip").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};

// starting the script on page load
$(document).ready(function(){
	tooltip();
});

// tooltip2
this.tooltip2 = function(){
	/* CONFIG */
		xOffset = -20;
		yOffset = -40;
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result
	/* END CONFIG */
	$("a.tooltip2").hover(function(e){
		this.t = this.title;
		this.title = "";
		$("body").append("<p id='tooltip2'>"+ this.t +"</p>");
		$("#tooltip2")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },

	function(){
		this.title = this.t;
		$("#tooltip2").remove();
    });
	$("a.tooltip2").mousemove(function(e){
		$("#tooltip2")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});
};

// starting the script on page load
$(document).ready(function(){
	tooltip2();
});

//tags order selecion at /tags/
$(document).ready(function(){
	$('#tags_order_selection').change(function(){
		$('.tags-list').hide();
		$('#' + $('#tags_order_selection').val()).show();
	});
});
$(function(){
	$(".login-to-use-options").click(function(e){
		if (document.getElementById('login')){
			e.preventDefault();
			$("#login a.clickable").click();
			document.getElementById('login').scrollIntoView(true);
		} else {
			return true;
		}
	});
});
