(function($){
	$.fn.mainbox = function(options){
		var defaults = {
			open_label: 'maggiori informazioni',
			close_label: 'chiudi'
		}
		var options = $.extend(defaults, options);
		var element_to_close = null;

		this.each(function() {
			var obj = $(this);    
			//opzioni                                           
			obj.options = options;                  
			var open_label = (obj.find('.open_label').text() != '')?obj.find('.open_label').text():obj.options.open_label;
			//proprietà                             
			obj.properties = {
				original_height: getOriginalHeight(obj),
				target_height: getTargetHeight(obj),
				open: false
			} 
			//metodi
			obj.open = function(){
				this.animate({
					height: this.properties.target_height
				});
				element_to_close = this;
				this.properties.open = true;
				$('.more_btn .ico',this).html(this.options.close_label);
			}
			obj.close = function(){
				this.animate({
					height: this.properties.original_height
				});                          
				if (element_to_close == this) element_to_close = null;
				this.properties.open = false;
				$('.more_btn .ico',this).html(open_label);
			}
			
			//controllo se devo usare un titolo piuttosto che l'etichetta
			
			$('.more', obj).prepend('<div class="more_btn"><span class="ico">' + open_label + '</span></div>');
			$('.more_btn', obj).click(function(){
				if(! obj.properties.open){
					if(element_to_close){element_to_close.close()};
					obj.open();                                            
					//azioni per il box di ricerca
					obj.find('.search_simple .actions').addClass('hidden');
					obj.find('.search_advanced .actions').removeClass('hidden');
				}else{
					obj.close();                                                
					obj.find('.search_simple .actions').removeClass('hidden');
					obj.find('.search_advanced .actions').addClass('hidden');
				}
			})
		});                        
		
		//utilities
		function getOriginalHeight(obj){
			return obj.height();
		}                       
		function getTargetHeight(obj){
			return obj.height() + obj.find('.more_details').innerHeight();
		}
	};     
})(jQuery);
