var open_block='';
var default_search_input_value = 'Iveco Stralis a Milano';
var jCarouselInitialized = false;
jQuery(function() {
	// non consento l'invio della ricerca se il valore è ancora quello di default
	jQuery('.homepage #ricerca_rapida .search form').submit(function(){
		if (jQuery('.homepage #ricerca_rapida #search_q').val()==default_search_input_value){
			alert('Inserire una ricerca diversa da quella di esempio');
			return false;	
		}	
	});
	// gestisco default input della ricerca rapida in homepage	
	jQuery('.homepage #ricerca_rapida #search_q').click(function(){
		//se è la prima volta che si clicca, resetta il campo
		if (jQuery('.homepage #ricerca_rapida #search_q').val()==default_search_input_value)
		{
			//default_search_input_value = jQuery(this).val();
			jQuery(this).val('');
		}
	});
	jQuery('.homepage #ricerca_rapida #search_q').focusout(function(){
		if (jQuery(this).val()=='')
		{
			jQuery(this).val(default_search_input_value);
		}
	});
    jQuery(".typologies_block").hide();
    jQuery(".typologies_block ul").hide();
    jQuery(".typologies_block").insertBefore( '#typologies_block_other' );
    jQuery(".typologies").click(
        function(){
          this.blur();
          jQuery(".typologies.selected").removeClass('selected');
          jQuery(this).addClass('selected');
          var id=this.id;
          var current_block='block-' + id;
          if(open_block!='' && open_block != current_block){
            jQuery("#" + open_block + ':visible' ).fadeOut( 500 , function(){
              jQuery("#" + current_block + ':hidden' ).fadeIn( 500);
            } );
            open_block = current_block;
          }
          else if(open_block==''){
        	  jQuery("#" + current_block ).show();
            jQuery('.typologies_block') .slideDown();
            open_block = current_block;
          }
          else if(open_block == current_block){
        	 jQuery("#" + current_block + ':visible' ).slideUp( 500 , function(){
        		 jQuery(".typologies_block").hide();
        	 } );
        	 jQuery(".typologies").removeClass('selected');
        	 open_block='';
          }
          else{
        	  open_block = current_block;
          }
          return false;
        }
    );
    jQuery(".typologies_button_all").click(
        function(){
          this.blur();
          jQuery(this).toggleClass('open');
          jQuery(this).parent().next('div.body_equipments').slideToggle(300);
          return false;
        }
    );
	jQuery("#tabs ul li").hover(function() {
		jQuery(this).addClass("hover");
	}, function() {
		jQuery(this).removeClass("hover");
	});
	jQuery("#tabs ul li").click(function() {
		jQuery("#tabs ul li").removeClass("selected");		
		jQuery(this).addClass("selected");
	});	
   if (jQuery("#advanced_form"))
   {
	jQuery.validator.addMethod("dateGreaterThan", function(value, element, params) {
		if (value.length==0) return true;
	    if (!/Invalid|NaN/.test(new Date(value))) {
	        return new Date(value) > new Date(jQuery(params).val());
	    }
	    return isNaN(value) && isNaN(jQuery(params).val()) || (parseFloat(value) > parseFloat(jQuery(params).val())); 
	},'Must be greater than {0}.');
	jQuery.validator.addMethod("numberGreaterThanField", function(value, element, params) {
		if (value.length==0 || document.getElementsByName( params )[0].value.length==0) return true;			
	    if (!isNaN(value)) {	 
	    	var param_value = document.getElementsByName( params )[0].value;
	    	return (value*1)>=(param_value*1);
	    }	    
	    return isNaN(value) && isNaN(jQuery(params).val()) || (parseFloat(value) > parseFloat(jQuery(params).val())); 
	},'Must be greater than {0}.');
	jQuery.validator.addMethod("numberLowerThanField", function(value, element, params) {
		if (value.length==0 || document.getElementsByName( params )[0].value.length==0) return true;
	    if (!isNaN(value)) {	    	
	    	var param_value = document.getElementsByName( params )[0].value;   	
	    	return (value*1)<=(param_value*1);
	    }
	    return isNaN(value) && isNaN(jQuery(params).val()) || (parseFloat(value) > parseFloat(jQuery(params).val())); 
	},'Must be greater than {0}.');
	jQuery('#advanced_form input[type=text], #advanced_form select').click(function(){
		if (jQuery(this).siblings('span').children('.error').css('visibility')=='visible')
		{
			jQuery(this).siblings('span').children('.error').css('visibility','hidden');
		}
		else
		{
			var position = jQuery(this).position();
			var left = jQuery(this).parent().parent().width();
			jQuery(this).siblings('span').children('.error').css('visibility','visible');			
			jQuery(this).siblings('span').children('.error').css('left',left);
			}			
		});
	   var msg_greater_than = "Il primo valore deve essere minore del secondo";
	   var msg_not_a_number = "Questo campo deve essere un numero";

	   jQuery("#advanced_form").validate({
		   submitHandler: function(form){
		    resetAdvancedFormGeneralError();		   
		   	count = countFilledFields();
		   	//se l'utente non ha compilato neanche un campo mostro il messagio d'errore. altrimenti fa il submit
		   	if (!count)
	   		{
		   		showAdvancedFormGeneralError(2,0);
	   		}
		   	else
		   	{		   		
		   		form.submit();	
		   	}
		   },
		   invalidHandler: function(form, validator){
		   		numberOfInvalids = validator.numberOfInvalids();
		   		if (numberOfInvalids)
		   		{
		   			showAdvancedFormGeneralError(1,numberOfInvalids);	
		   		}
		   		else
		   		{
		   			resetAdvancedFormGeneralError();
		   		}  
		   },
	       wrapper: "span",
	       rules: {
	          "trk[trkana001_trklst001_listing_type_cod]": {},
	          "trk[make_id]": {},
	          "trk[trkana001_work_hours][from]": {digits: true, numberLowerThanField: ["trk[trkana001_work_hours][to]"] },
	          "trk[trkana001_work_hours][to]": {digits: true, numberGreaterThanField: ["trk[trkana001_work_hours][from]"] },
	          "trk[trkana001_year_num][from]": {digits: true, numberLowerThanField: ["trk[trkana001_year_num][to]"] },
	          "trk[trkana001_year_num][to]": {digits: true, numberGreaterThanField: ["trk[trkana001_year_num][from]"] },
	          "trk[trkana001_price_num][from]": {digits: true, numberLowerThanField: ["trk[trkana001_price_num][to]"]},
	          "trk[trkana001_price_num][to]": {digits: true, numberGreaterThanField: ["trk[trkana001_price_num][from]"]},
	          "trk[trkana001_km_num][from]": {digits: true, numberLowerThanField: ["trk[trkana001_km_num][to]"]},
	          "trk[trkana001_km_num][to]": {digits: true, numberGreaterThanField: ["trk[trkana001_km_num][from]"]},
	          "trk[trkana001_seat_num]": {},
	          "trk[stc_typology_id]": {},
	          "trk[stc_body_equipment_id]": {},
	          "trk[ptt][from]": {digits: true, numberLowerThanField: ["trk[ptt][to]"]},
	          "trk[ptt][to]": {digits: true, numberGreaterThanField: ["trk[ptt][from]"]},
	          "trk[net_weight][from]": {digits: true, numberLowerThanField: ["trk[net_weight][to]"]},
	          "trk[net_weight][to]": {digits: true, numberGreaterThanField: ["trk[net_weight][from]"]},
	          "trk[lifting_capacity][from]": {digits: true, numberLowerThanField: ["trk[lifting_capacity][to]"]},
	          "trk[lifting_capacity][to]": {digits: true, numberGreaterThanField: ["trk[lifting_capacity][from]"]},
	          "trk[lifting_height][from]": {digits: true, numberLowerThanField: ["trk[lifting_height][to]"]},
	          "trk[lifting_height][to]": {digits: true, numberGreaterThanField: ["trk[lifting_height][from]"]},
	          "trk[glbana001_type_cod]": {},
	          "trk[glbana002_country_cod]": {},
	          "trk[glbana002_region_cod]": {},
	          "trk[glbana002_province_cod]": {},
	          "trk[trkana001_trklst006_fuel_cod]": {},
	          "trk[_csrf_token]": {}
	          },
	        messages: {
	          "trk[trkana001_trklst001_listing_type_cod]": {},
	          "trk[make_id]": {},
	          "trk[trkana001_work_hours][from]": {digits: msg_not_a_number, numberLowerThanField: msg_greater_than},
	          "trk[trkana001_work_hours][to]": {digits: msg_not_a_number, numberGreaterThanField: msg_greater_than},
	          "trk[trkana001_year_num][from]": {digits: msg_not_a_number, numberLowerThanField: msg_greater_than},
	          "trk[trkana001_year_num][to]": {digits: msg_not_a_number, numberGreaterThanField: msg_greater_than},
	          "trk[trkana001_price_num][from]": {digits: msg_not_a_number, numberLowerThanField: msg_greater_than},
	          "trk[trkana001_price_num][to]": {digits: msg_not_a_number, numberGreaterThanField: msg_greater_than},
	          "trk[trkana001_km_num][from]": {digits: msg_not_a_number, numberLowerThanField: msg_greater_than},
	          "trk[trkana001_km_num][to]": {digits: msg_not_a_number, numberGreaterThanField: msg_greater_than},
	          "trk[trkana001_seat_num]": {},
	          "trk[stc_typology_id]": {},
	          "trk[stc_body_equipment_id]": {},
	          "trk[ptt][from]": {digits: msg_not_a_number, numberGreaterThanField: msg_greater_than},
	          "trk[ptt][to]": {digits: msg_not_a_number, numberGreaterThanField: msg_greater_than},
	          "trk[net_weight][from]": {digits: msg_not_a_number, numberLowerThanField: msg_greater_than},
	          "trk[net_weight][to]": {digits: msg_not_a_number, numberGreaterThanField: msg_greater_than},
	          "trk[lifting_capacity][from]": {digits: msg_not_a_number, numberLowerThanField: msg_greater_than},
	          "trk[lifting_capacity][to]": {digits: msg_not_a_number, numberGreaterThanField: msg_greater_than},
	          "trk[lifting_height][from]": {digits: msg_not_a_number, numberLowerThanField: msg_greater_than},
	          "trk[lifting_height][to]": {digits: msg_not_a_number, numberGreaterThanField: msg_greater_than},
	          "trk[glbana001_type_cod]": {},
	          "trk[glbana002_country_cod]": {},
	          "trk[glbana002_region_cod]": {},
	          "trk[glbana002_province_cod]": {},
	          "trk[trkana001_trklst006_fuel_cod]": {},
	          "trk[_csrf_token]": {}
	       }
	   });
   };
   if (jQuery("a.fancybox").length>0)
   {	   
	   jQuery("a.fancybox").fancybox({titleShow: false});   
   };
   jQuery("a.blank").click(
	   function(){
		 window.open(this.href,'mywindow'+Math.floor(Math.random()*11),'');
		 return false;
	   }
   );
   jQuery('.save_search_button').click(function(){
	   
	   //in base al punto in cui viene azionato il processo, imposto la funzione di callback necessaria
	   jQuery('#callback').val('popupSaveSearchForm()');
	   
	   //salvo comunque la ricerca
	   if (jQuery('.save_search_button').attr('rel')!="auth")
	   {	   
		  popupSigninRegistrationForm();
	   }
	   popupSaveSearchForm();
   });
   // chiudo i div della ricerca
	jQuery('body').click(function(event) {
	    if (!jQuery(event.target).closest('#freesearch .filter_options .group h2').length) {
	        jQuery('#freesearch .filter_options div.group ul').hide();
	    };
	    if (!jQuery(event.target).closest('#tab_first .sorting_specific div.button_grey').length) {
	    	jQuery('#tab_first .sorting_specific div.button_grey').removeClass('open');
	    	jQuery('#tab_first .sorting_specific div.button_grey').addClass('closed');
	        jQuery('#tab_first .sorting_specific div.fields').hide();
	    };
	});
   if (jQuery("#freesearch .filter_options .group ul li").length>0)
   {
	   jQuery("#freesearch .filter_options .group ul li").click(function(e){
		   var clicked_filter_option = jQuery.parseJSON(jQuery(this).attr('rel'));	   
		   // salvo lo stato dell'elemento cliccato
		   was_selected = jQuery(this).hasClass('current');
		   if(clicked_filter_option.filteroptions.search=='elimina' && clicked_filter_option.filteroptions.id=='null')
		   {
			   listing_loading();
			   jQuery(this).parents('div.group').detach();
			   jQuery.ajax({
				   	type: 'GET',				   
				   	url: (jQuery("#freesearch .filter_options .group ul li.current").length==0)? route_trk_fulltext_search_ajax_reset : route_trk_fulltext_search_ajax_remove,
				   	data: clicked_filter_option,			 			   	
				   	success: function(data){
				   		listing_restore();
				   		replaceData(data);
			   	   	},
			   	   	dataType: 'html'				  
			   });
		   }
		   else 
		   {
			   // seleziono/deseleziono l'elemento corrente
			   if(!was_selected)
			   {
				   listing_loading();
				   // deseleziono tutti gli elementi dello stesso gruppo
				   jQuery.each(jQuery("#freesearch .filter_options .group ul li.current"), function(){
					   curr_filter_option = jQuery.parseJSON(jQuery(this).attr('rel'));
					   if (curr_filter_option.filteroptions.group_id==clicked_filter_option.filteroptions.group_id)
					   {
						   jQuery(this).removeClass('current');
					   }			   			  
				   });  
				   jQuery(this).addClass('current');
				   var title = jQuery(this).parents('div.group').find('h2 strong').text(clicked_filter_option.filteroptions.search);
				   //aggiunge il filtro
				   jQuery.ajax({
					   	type: 'GET',				   
					   	url: route_trk_fulltext_search_ajax_add,
					   	data: clicked_filter_option,			 			   	
					   	success: function(data){
					   		listing_restore();
					   		replaceData(data);
				   	   	},
				   	   	dataType: 'html'				  
				   });
			   	}
		   }
		   jQuery('#freesearch .filter_options div.group ul').hide();
		   return false;
	   });
   };
   /*
    *  Privato o impresa
    * */
   jQuery(".user_area #edit_profile #type input").bind('click',function(){
	   if (jQuery(this).val()=='privato')
	   {
		   jQuery("#edit_profile form #business").hide();
		   jQuery("#edit_profile form #private").show();		   
	   }   
	   else
	   {
		   jQuery("#edit_profile form #business").show();
		   jQuery("#edit_profile form #private").hide();
	   }
   });
   if ( (!jQuery(".user_area #edit_profile #type input[value=privato]").attr('checked')) && (!jQuery(".user_area #edit_profile #type input[value=azienda]").attr('checked')) )
   {	   
	   if (jQuery.trim(jQuery('#master_contact_piva').val())=='')
	   {	   	   
		   jQuery(".user_area #edit_profile #type input[value=privato]").attr('checked', true);
		   jQuery(".user_area #edit_profile #type input[value=privato]").trigger('click');
	   }   
	   else
	   {
		   jQuery(".user_area #edit_profile #type input[value=azienda]").attr('checked', true);
		   jQuery(".user_area #edit_profile #type input[value=azienda]").trigger('click');
	   }
   }
   else
   {	   
	   if (jQuery(".user_area #edit_profile #type input[value=privato]").attr('checked'))
	   {
		   jQuery("#edit_profile form #business").hide();
		   jQuery("#edit_profile form #private").show();	
	   }
	   else
	   {
		   jQuery("#edit_profile form #business").show();
		   jQuery("#edit_profile form #private").hide();
	   }
   }
   jQuery('.user_area #autocomplete_trk_model_id').focusin(function(){
		jQuery('#hidden_model_info').show();
	});
   jQuery('.user_area #autocomplete_trk_model_id').focusout(function(){
		jQuery('#hidden_model_info').hide();
	});
   var defaults = {
 			containerID: 'moccaUItoTop', // fading element id
			containerHoverClass: 'moccaUIhover', // fading element hover class
			scrollSpeed: 1200
		};
   jQuery().UItoTop();
});
/**
 * Consente di ottenere un parametro da una query string
 * @param key il parametro che si vuole
 * @param default_ il valore di default nel caso in cui non venga restituito alcun valore
 * @param qs la querystring
 * @return string il parametro
 */
function getQuerystring(key, default_, url)
{
	if (default_==null) default_="";
	key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
	var qs = regex.exec(url);
	if(qs == null)
	  return default_;
	else
	  return qs[1];	
};
/**
 * Invia la richiesta ajax della ricerca
 * 
 * @param page il numero di pagina da inviare
 * 
 */
function fulltext_search_ajax(page,sort,sort_type,items){
	jQuery.ajax({
		type: 'GET',				   
		url: route_trk_fulltext_search_ajax,
		data:  {"page":page,"sort":sort,"sort_type":sort_type, "items":items},	
		traditional: true,
		success: function(data){
		  listing_restore();
		  replaceData(data);
		}
	});
};

/**
 * funzioni da far partire dopo la chiamata ajax di nuovi risultati
 */
function replaceData(data){
	 
	  jQuery('#central_content .central_text').html(data);

	  // sostituisco la paginazione attuale con quella generata dal nuovo pager.
	  var pagination_content = jQuery('#pagination_new').html();
	  jQuery('#pagination_new').html('');
	  jQuery('#wrapper .pagination_container').html(pagination_content);
	  
	  // sostituisco l'ordinamento attuale con quello generato
	  var sorting_content = jQuery('#sorting_new').html();
	  jQuery('#sorting_new').html('');
	  jQuery('#wrapper .sorting_specific').html(sorting_content);
	  
	  // risultati per pagina
	  jQuery('.itemsPerPage #items').change(function(){
		   listing_loading();
		   fulltext_search_ajax(null,null,null,jQuery(this).val());
		   jQuery("html:not(:animated),body:not(:animated)").animate({ scrollTop: jQuery('#central_content').offset().top}, 500 );
	  });

	  // al click del numero pagina, invia la richiesta ajax passando il numero di pagina
	  jQuery('.pagination_container .pagination a').click(function(e){
		   listing_loading();
		   var page = getQuerystring('page',null,jQuery(this).attr('href'));
		   fulltext_search_ajax(page,null,null,null);
		   jQuery("html:not(:animated),body:not(:animated)").animate({ scrollTop: jQuery('#central_content').offset().top}, 500 );
		   return false;
	  });
	  
	  jQuery('.sorting_specific .button_grey').click(function (){
	      if (jQuery('.sorting_specific .button_grey').hasClass('closed'))
	      {
	        jQuery('.sorting_specific .fields').slideDown();
	        jQuery('.sorting_specific .button_grey').addClass('open');
	        jQuery('.sorting_specific .button_grey').removeClass('closed');
	      }
	      else
	      {
	        jQuery('.sorting_specific .fields').slideUp();
	        jQuery('.sorting_specific .button_grey').addClass('closed');
	        jQuery('.sorting_specific .button_grey').removeClass('open');
	      }
	    });

	    // al click sull'ordinamento fa una richiesta ajax
	    jQuery('.sorting_specific .fields a').click(function(e){
	        listing_loading();
	        sort      = getQuerystring('sort',null,jQuery(this).attr('href'));
	        sort_type = getQuerystring('sort_type',null,jQuery(this).attr('href'));
	        fulltext_search_ajax(null,sort,sort_type,null);
	        //jQuery('.sorting_specific .fields').slideUp();
	        return false;
	    });
}
/** 
 * mostra l'animazione di caricamento
 */
function listing_loading(){
	jQuery('.central_text .loader').show();
};
/**
 * nasconde l'animazione di caricamento
 */
function listing_restore(){	
	jQuery('.central_text .loader').hide();
};
function openPage(elem){
  window.open(elem.href,'mywindow'+Math.floor(Math.random()*11),'');
  return false;
};
function send_friend(){
   jQuery('#send_friend_popup img.loader').show();
   var destination_url = jQuery('#send_friend_popup form').attr('action');		   
   var form_data= jQuery('#send_friend_popup form').serialize();
   jQuery.ajax({
	   type: "POST",
	   url: destination_url,
	   data: form_data,
	   success: function(response){			   	   		
			var popup_html = jQuery(response).children();   	   				   
			jQuery('#send_friend_popup').parent().html(popup_html);
			jQuery('#send_friend_popup img.loader').hide();
	   }
   });  
};
function setSelectValues(select_element,values)
{
  jQuery(select_element).html('');
  if (values)
  {
	jQuery(select_element).attr('disabled',false);
	jQuery(select_element).prepend(jQuery('<option selected></option>').val('').html(''));
    jQuery.each(values, function(val, text) {
        jQuery(select_element).append(
            jQuery('<option></option>').val(val).html(text)
        );
    });
  }
};
function resetSelectValues(select_element)
{		
  jQuery(select_element).html('<option value=\'\'></option>');
  jQuery(select_element).attr('disabled',true);
};
function change_region(region)
{	
	jQuery('#dealer_search_cascade_field_rp_glbana002_region_cod').val(region);
	setSelectValues('#dealer_search_cascade_field_rp_glbana002_province_cod',widget_choices_dealer_search_cascade_field_rp_glbana002_province_cod[region]); 
	return false;
};
function search_dealer_submit(form_id)
{	
   var form = jQuery('#'+form_id);
   jQuery('.dealer_search div.loader').show();
   jQuery('.dealer_search #dealer_list').show();
   var destination_url = form.attr('action');		   
   var form_data = form.serialize();
   jQuery.ajax({
	   type: "POST",
	   url: destination_url,
	   data: form_data,
	   success: function(response){				   		
	   		jQuery('#dealer_list_container').html(response);
	   		jQuery('.dealer_search div.loader').hide();
	   }
   });   
   return false;	   
};
function popupSaveSearchForm(){
	jQuery.fancybox({
   		'href'					: route_save_search,
   		'centerOnScroll'		: true,
   		'hideOnOverlayClick'	: true,
   		'padding'				: 40,
   		'scrolling'				: 'no'
   	});
}
//apre il popup di login+registrazione
function popupSigninRegistrationForm()
{
	jQuery.fancybox({
		'href'					: '#user_signin_registration_form',
		'centerOnScroll'		: true,
		'hideOnOverlayClick'	: true,
		'padding'				: 40,
		'scrolling'				: 'no'
	});
};
//fa il login e se ok salva la ricerca, altrimenti mostro gli errori nel form di login
function signin_and_search(form_id)
{
   var form = jQuery('#'+form_id);
   var destination_url = form.attr('action');
   var form_data = form.serialize();
   //resetto gli errori eventualmente generati
   resetFormErrors(form_id);
   jQuery.ajax({
	   url: destination_url,
	   type: "POST",	   
	   data: form_data,
	   success: function(response){
		   	var response_object = eval('(' + response + ')');
		   	//login ok
		   	if (response_object.result==0)
		   	{		   			
		   		eval(jQuery('#callback').val());   		
		   	}
		   	else
		   	{		   				   	
		   		if (response_object.password)
		   		{
		   			jQuery('#signin_password').addClass('error');
		   			jQuery('#signin_password').after('<span class="error">Campo mancante o errato</span>');
	   			}
		   		if (response_object.username)
		   		{
	   				jQuery('#signin_username').addClass('error');
	   				jQuery('#signin_username').after('<span class="error">Campo mancante o errato</span>');
	   			}		 
		   		jQuery('#user_signin_registration_form_login .msg.error').show();		   		
		   	}
   		}
   });   
   return false;	
};
//mostra il popup di salvataggio ricerca. sia se è andato a buon fine, sia nel caso contrario
function popupSaveSearch(message_code,message_text)
{
	var popup_content = '';
	if (message_code==0)
	{
		popup_content = "<div id=\"popup_save_search\"><p><strong>La tua ricerca è stata salvata.</strong><br>Puoi trovare le ricerche salvate nell'area <a title=\"ricerche salvate\" href=\""+route_user_area_my_searches+"\">MyCamion</a>.</p></div>";
	}
	else
	{
		popup_content = "<div id=\"popup_save_search\"><p class=\"error\"><strong>Non è stato possibile salvare la ricerca.</strong><br>"+message_text+"</p></div>";
	}
	jQuery.fancybox({
		//'href'					: '#save_search_popup',
		'centerOnScroll'		: true,
		'hideOnOverlayClick'	: true,
		'padding'				: 40,
		'scrolling'				: 'no',
		'content'				: popup_content
	});
};
//mostra il popup di salvataggio ricerca. sia se è andato a buon fine, sia nel caso contrario
function popupAddTrk(message_code,message_text)
{
	var popup_content = '';
	if (message_code==0)
	{
		popup_content = "<div id=\"popup_save_search\"><p><strong>L'annuncio è stato salvato.</strong><br>Puoi trovare gli annunci nell'area <a title=\"annunci salvati\" href=\""+route_user_area_my_advs+"\">MyCamion</a>.</p></div>";
	}
	else
	{
		popup_content = "<div id=\"popup_save_search\"><p class=\"error\"><strong>Non è stato possibile salvare l'annuncio.</strong><br>"+message_text+"</p></div>";
	}
	jQuery.fancybox({
		//'href'					: '#save_search_popup',
		'centerOnScroll'		: true,
		'hideOnOverlayClick'	: true,
		'padding'				: 40,
		'scrolling'				: 'no',
		'content'				: popup_content
	});
};
//salva la ricerca e, se l'utente è loggato, chiama l'apertura del popup
function processSaveSearch()
{	  
   var form_data = jQuery('#save_search_form').serialize();
   //jQuery('#user_signin_registration_form').html(jQuery('#save_search_popup'));	
   jQuery.ajax({
	   	url: route_user_add_my_search,
	   	type: "POST",	
	   	data: form_data,
	   	success: function(response){
	   		var response_object = eval('(' + response + ')');
	   		//se l'utente non è loggato non mostro l'esito di addMySearch
	   		if (response_object.result!=3)
	   		{
	   			jQuery('.save_search_button').attr('rel','auth');
	   			popupSaveSearch(response_object.result,response_object.message);
	   		}
		}
   });   
   return false;
};
//registra l'utente e, se l'operazione è andata a buon fine, salva la ricerca. altrimenti mostro gli errori nel form di registrazione
function processRegisterUser(form_id)
{	
   var form_data = jQuery('#'+form_id).serialize();
   //resetto gli errori del form
   resetFormErrors(form_id);   	
   jQuery.ajax({
	   	url: route_user_registration,
	   	type: "POST",	   
	   	data: form_data,
	   	success: function(response){
	   		var response_object = eval('(' + response + ')');	   		
	   		if (response_object.result==0)
	   		{	
	   			eval(jQuery('#callback').val());	   			
	   		}
	   		else
	   		{	 	   			
	   			for(var field_name in response_object.fields)
	   			{
	   				field_error_message = response_object.fields[field_name];
	   				jQuery("[name='"+field_name+"']").addClass('error');
	   				jQuery("[name='"+field_name+"']").after('<span class="error">'+field_error_message+'</span>');
	   			}	   
	   			jQuery('#' + form_id + '.msg.error').show();	
	   		}
		}
   });  
   return false;
};
function resetFormErrors(form_id)
{
	var form = jQuery('#'+form_id);	
	var form_fields = form.serializeArray();
	jQuery('#'+form_id+' .msg.error').hide();
	for(var i in form_fields)
	{
		field_name = form_fields[i].name;		
		jQuery("#"+form_id+" [name='"+field_name+"']").removeClass('error');
		jQuery("#"+form_id+" span.error").remove();
	}	
};
function saveTrk(trk_id,user_id)
{
	jQuery('#callback').val('processAddTrk('+trk_id+','+user_id+')');
	if (jQuery('.user_tool .save a').attr('rel')=="auth")
	{
		processAddTrk(trk_id,user_id);	
	}
	else
	{
		popupSigninRegistrationForm();
	}	
	return false;
};
function processAddTrk(trk_id,user_id)
{
	var data = new Array();
	data['trk_id'] = trk_id;	
	if (user_id!=0) data['user_id'] = user_id;
	jQuery('.user_tool .save a').attr('rel','auth');
	//jQuery('#user_signin_registration_form').html(jQuery('#save_search_popup'));	
   jQuery.ajax({
	   	url: route_user_add_my_adv,
	   	type: "POST",	
	   	data: data,
	   	success: function(response){
	   		var response_object = eval('(' + response + ')');
	   		//se l'utente non è loggato non mostro l'esito di addMyAdv
	   		if (response_object.result!=3)
	   		{
	   			popupAddTrk(response_object.result,response_object.message);
	   		}
		}
   });   
   return false;
};
function countFilledFields()
{
	   count = jQuery("#advanced_form input[type=text], #advanced_form select, #advanced_form textarea").filter(function(){
		    return jQuery(this).val() != "";
		}).length;
	   if (count==0) return false;
	   else return count;
};
function showAdvancedFormGeneralError(error_code,errors_count)
{
	var msg = '';
	switch (error_code)
	{
		case 1:
			msg = 'Ci sono degli errori, correggere i campi in rosso';
			break;
		case 2:
			msg = 'E\' necessario compilare almeno un campo';
			break;						
	}
	jQuery('#advanced_form #general_errors').html(msg);
	jQuery('#advanced_form #general_errors').show();
};
function resetAdvancedFormGeneralError()
{
	jQuery('#advanced_form #general_errors').html('');
	jQuery('#advanced_form #general_errors').hide();
};
function openGroup(obj)
{
  jQuery('#' + obj).toggle();
};
function trackEvent( caller , container , content , category, action, opt_label, value )
{
  jQuery(caller).hide();
  jQuery("#" + container).html(content);
  if(!sf_debug) {
	  _gaq.push(['_trackEvent', category, action, opt_label, value]);
  }
};
var domWrite = (function(){            // by Frank Thuerigen
	 // private 
	 var dw = document.write,              // save document.write()
	          myCalls = [],                // contains all outstanding Scripts
	          t = '';                      // timeout
	 function startnext(){                 // start next call in pipeline
	  if ( myCalls.length > 0 ) {
	   // if ( Object.watch ) console.log( 'next is '+myCalls[0].f.toString() );
	   myCalls[0].startCall();
	   }
	  };
	 function evals( pCall ){            // eval embedded script tags in HTML code
	  var scripts = [],
	      script,
	      regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
	  while ((script = regexp.exec(pCall.buf))) scripts.push(script[1]);
	  scripts = scripts.join('\n');
	  if (scripts) {
	   eval(scripts);
	   }
	  };
	 function finishCall( pCall ){
	   pCall.e.innerHTML = pCall.buf;             // write output to element
	   evals( pCall );
	   document.write=dw;                        // restore document.write()
	   myCalls.shift();
	   window.setTimeout( startnext, 10 );
	   };
	 function testDone( pCall ){
	   var myCall = pCall;
	   return function(){
	    if ( myCall.buf !== myCall.oldbuf ){
	     myCall.oldbuf = myCall.buf;
	     t=window.setTimeout( testDone( myCall ), myCall.ms );
	     }
	    else {
	     finishCall( myCall );
	     }
	    };
	   };  
	 function MyCall( pDiv, pSrc, pFunc ){                    // Class
	  this.e = ( typeof pDiv == 'string' ? 
	             document.getElementById( pDiv ) :
	             pDiv ),                     // the div element
	  this.f = pFunc || function(){},
	  this.stat = 0,                         // 0=idle, 1=waiting, 2=running, 3=finished
	  this.src = pSrc,                       // script source address
	  this.buf = '',                         // output string buffer
	  this.oldbuf = '',                      // compare buffer
	  this.ms = 10,                         // milliseconds
	  this.scripttag;                        // the script tag 
	  };
	 MyCall.prototype={
	  startCall: function(){
	   this.f.apply( window );                 // execute settings function
	   this.stat=1;
	   var that = this;                            // status = waiting
	   document.write = (function(){
	    var o=that,
	        cb=testDone( o ),
	        t;
	    return function( pString ){            // overload document.write()
	     window.clearTimeout( t );
	     o.stat=2;                             // status = running
	     window.clearTimeout(t);
	     o.oldbuf = o.buf;
	     o.buf += pString;                     // add string to buffer
	     t=window.setTimeout( cb, o.ms );
	     };
	    })();
	   var s=document.createElement('script');
	   s.setAttribute('language','javascript');
	   s.setAttribute('type','text/javascript');
	   s.setAttribute('src', this.src);
	   document.getElementsByTagName('head')[0].appendChild(s);
	   }
	  };
	 return function( pDiv, pSrc, pFunc ){  // public
	  var c = new MyCall( pDiv, pSrc, pFunc );
	  myCalls.push( c );
	  if ( myCalls.length === 1 ){
	   startnext();
	   }
	  };
	 })();
/*
|--------------------------------------------------------------------------
| UItoTop jQuery Plugin 1.1
| http://www.mattvarone.com/web-design/uitotop-jquery-plugin/
|--------------------------------------------------------------------------
*/
(function(jQuery){
	jQuery.fn.UItoTop = function(options) {
 		var defaults = {
			text: 'Torna su',
			min: 200,
			inDelay:600,
			outDelay:400,
  			containerID: 'toTop',
			containerHoverID: 'toTopHover',
			scrollSpeed: 1200,
			easingType: 'linear'
 		};
 		var settings = jQuery.extend(defaults, options);
		var containerIDhash = '#' + settings.containerID;
		var containerHoverIDHash = '#'+settings.containerHoverID;
		jQuery('body').append('<a href="#" id="'+settings.containerID+'">'+settings.text+'</a>');
		jQuery(containerIDhash).hide().click(function(){
			jQuery('html, body').animate({scrollTop:0}, settings.scrollSpeed, settings.easingType);
			jQuery('#'+settings.containerHoverID, this).stop().animate({'opacity': 0 }, 1, settings.easingType);
			return false;
		})
		.prepend('<span id="'+settings.containerHoverID+'"></span>')
		.hover(function() {
				jQuery(containerHoverIDHash, this).stop().animate({
					'opacity': 1
				}, 1, 'linear');
			}, function() { 
				jQuery(containerHoverIDHash, this).stop().animate({
					'opacity': 0
				}, 1, 'linear');
			});
		jQuery(window).scroll(function() {
			var sd = jQuery(window).scrollTop();
			if(typeof document.body.style.maxHeight === "undefined") {
				jQuery(containerIDhash).css({
					'position': 'absolute',
					'top': jQuery(window).scrollTop() + jQuery(window).height() - 50
				});
			}
			if ( sd > settings.min ) 
				jQuery(containerIDhash).fadeIn(settings.inDelay);
			else 
				jQuery(containerIDhash).fadeOut(settings.Outdelay);
		});
};
})(jQuery);
