/** 
 * @desc 
 * <div id="ingredients_1" class="box_1">
 * <div class="selected_value">Schweppes</div>
 * <div id="first" class="select_box_values" style="display: none;">
 * 		<ul>
 * 			<li id="ingredient_7" class="all">Alle Cocktails</li>
 * 		</ul>
 *	</div>
 * </div>
 * 
 * the id of div.box_1 is also used as indexname for the ajax request
 * 
 * @author skendlba 
 * @param {Array} params : select boxes (<ul id=""><li id="key_1">Value</li></ul>)
 */
var selector = function(params){
	
	var that = {};
	var select_object = params;
	
	//
	var configs = {
		ajax_target			:	URL.base_url + "jax/filter",		
		ajax_target_session	:	URL.base_url + "jax/session",
		disabled_class		:	"disabled",
		tooltip_text:{
	        ".box_1": "Welches Schweppes Produkt soll in deinen Cocktail?",
	        ".box_2": "Wähle gleich die alkoholfreie Variante oder such eine Spirituose aus.",
	        ".box_3": "Hast Du vielleicht auch einen Geschmacks-<br />wunsch?"
    	},
		default_values:{
			"ingredients_1":"Schweppes",
			"ingredients_2":"Spirituose",
			"flavors":"Geschmack",
			"mood":"Anlass"
		}
	};	
	
	var paging_items 			= 	".pages a",
		search_button 			= 	"#search_submit",
		search_text_field 		= 	"#search_value",
		alphabet_triggers 		= 	".teaser_alphabet div",
		cocktail_container_id 	= 	"#cocktails.teaser",
		value_holder_class 		= 	".selected_value";

	var select_boxen;
 	var select_boxen_array = [];
	
	//configs
	var click_disabled_item = false,search_in_clicked_ul=false;
	
	//
	var targetLetter = "A",divider = "LETTER_";
	//	
	
	var session_event_name = "cocktail";
	var session_event_obj = jQuery.Event(session_event_name);
	//
	var parent_obj,clicked_li;
	//
	var page = 1;
	var search_text = "";
    var current_alpha = false;
	var mood=false;
	
	//	
	var ajax_response,li_select_key,parent_id,siblings;
	//	
	
	var listeners = {
		//
		"search_button":function(){
            
            $(search_text_field).live("keypress", function(event){
                if (event.keyCode == 13) {
                    $(search_button).trigger("click");
                }
            }).live("click", function(){
                this.value = '';
            }).live("focus", function(){
                this.select();
            }).live("blur", function(){
                this.value = !this.value ? 'Suche verfeinern' : this.value;
            });
			
			
            $(search_button).live("click", function(){
                search_text = $(search_text_field).val();
				kill_current_selection(select_boxen_array);
                load_cocktails();
                return false;
            });
           
		},
		 //
		"cocktail_click":function(){
            $(".teaser_content div.item").click(function(e){
            
                var item = $(this).find("a");
                window.location = item[0].href;
                
            });
		},
		 //
		"set_alphabet":function(){
			
			hide_sitemap_content(targetLetter);	        
	        if ($(alphabet_triggers).length > 0) {//only on sitemap page			
				$(alphabet_triggers).live("click", function(e){
					e.stopPropagation();
					var new_alpha = $.trim($(this).text());
					if (current_alpha == new_alpha) {
						return false;
					}
					
					cocktail_container_id = "#sitemap.teaser";
					current_alpha = new_alpha;
					hide_sitemap_content(current_alpha);
				});
			}
		},		
		"paging_click": function(){
	        $(paging_items).live('click', function(e){
	        
	            var a = $(this);
	            var url_array = a.attr("href").split("/");
	            
	            page = url_array[url_array.length - 1].split("_")[1];
	            
	            e.preventDefault();
	            
	            load_cocktails();
	            
	        });
    	},
		 //
		"session": function(){
			set_session_event_listener();
		}
	};
	/**
	 * 
	 */	
	var set_listeners=function(){
		listeners.search_button.call();
		listeners.cocktail_click.call();		
		listeners.set_alphabet.call();
		listeners.session.call();
		listeners.paging_click.call();
	};
	/**
	 * 
	 */
	var init = function(){			
		
		set_listeners();	
		hover_select_layer();
		toggle_select_layer();	
     	select_boxen = $(select_boxen_array.join(','));
        
        //set click function
        $("li", select_boxen).filter(function(){
			return $(this).attr("id") != "none"; 
		}).click(li_click_listener);
                
       
		//session_filter is dynamically set in the view : teaser/cocktails.php
		if(typeof session_filter=="undefined"){
			session_filter={};			
		}
		//		
		
        //hold select elements in object boxes
        $.each(select_boxen, function(i, item){
            var key = $(item).attr("id");
            select_boxen_array[i] = {
                id: key,
                object: item,
                selected_key: 	typeof session_filter[key] != undefined ? session_filter[key] : false,
                headline: configs.default_values[key]
            };
        });
        //
	
	};//init
	
	var intervalId;
	var css_position={
		".box_1":	"175px",
		".box_2":	"300px",
		".box_3":	"425px"
	};	
	/**
	 * 
	 */
    var reset_bg = function(){
        $(this).parent().css({
            backgroundPosition: "0px 0px"
        });
    };
	
	/**
	 * change background of select form
	 */
	var hover_select_layer=function(){
		
		$("#select_box .box_1").hover(function(){
            $(this).parent().css({
                backgroundPosition: "0px -19px"
            });
		},reset_bg);
		
		$("#select_box .box_2").hover(function(){
            $(this).parent().css({
                backgroundPosition: "0px -38px"
            });
		},reset_bg);
		
		$("#select_box .box_3").hover(function(){
            $(this).parent().css({
                backgroundPosition: "0px -57px"
            });
		},reset_bg);	
	};
	/**
	 * display functionality - show/hide the select layer
	 */
	var toggle_select_layer=function(){
		
        $.each(select_object, function(i, item){
        
            var content = $(item.content), trigger = $(item.trigger);			
            select_boxen_array.push(item.trigger);            
           	content.hide();						
            trigger.mouseover(function(){
				            
                if (item.trigger == ".box_4") {
                    $(item.trigger).find(value_holder_class).addClass("mouseover");
                }
                else {
                    $(".search_bar_tooltip").animate({
                        left: css_position[item.trigger]
                    }, 200, function(){
                    $(this).html(configs.tooltip_text[item.trigger]);
                        clearInterval(intervalId);
                        
                        intervalId = setInterval(function(){
                        
                            $(".search_bar_tooltip").hide();
                        }, 2000);
                    }).show();
                }
                if (content.is(":hidden")) {
                 	content.show();
                }
            });
			
			trigger.mouseout(function(evt){
				 if (item.trigger == ".box_4") {
                    $(item.trigger).find(value_holder_class).removeClass("mouseover");
                }
				content.hide();			
            });
        });//each
	    
	};
	/**
     *
     */
    var hide_sitemap_content = function(target){
    
        var all_items = $(".alphabet");
        var target_items = all_items.filter(function(){
            return $(this).attr("id").split(divider)[1] == target;
        });
        
        all_items.hide();
        target_items.show();
        
    };
	/**
	 * 
	 */
	var set_session_event_listener=function(){
		//
        $('body').bind('cocktail', function(e){
        
            var params = {};
            
            params = collect_ajax_params();
            
            if (current_alpha != false) {
                params.alpha = current_alpha;
            }
            else {
                params.page = page;
                
                if (search_text != "") {
					params.search_text = search_text;
				}
                
            }
            
			//make ajax request
            $.post(configs.ajax_target_session, params, function(response){
            
            }, "json");
            
        });
        //	
	};	
	/**
	 * generate ajax params out of select_boxen_array
	 * 
	 */
	var collect_ajax_params = function(){
		
		var ajax_params = {};		
		$.each(select_boxen_array,function(i,item){
			if(item.selected_key){
				ajax_params[item.id]=item.selected_key;	
			}			
		});
		
		if (current_alpha !== false) {
            ajax_params.alpha = current_alpha;
        }
        else {
            ajax_params.search_text = search_text;
            ajax_params.page = page;
            //ajax_params.filter = current_filter;
        }
		return ajax_params;
	};	
	
	/**
	 * 
	 * @param {Object} e
	 */
	var li_click_listener = function(e){		
		//
		page=1;
		search_text = "";
		mood = false;
		//
		
		clicked_li = $(this);
		parent_obj = clicked_li.parent().parent().parent();
	
		/**
		 * currently there are four different select elements with the ids
		 * group1: 	ingredients_1, ingredients_2, flavors
		 * group2:	mood
		 * the elements of group1 interact with each other
		 * group2 is stand-alone -> is handled differently 
		 */
		parent_id = parent_obj.attr("id");
	
		var li_id = clicked_li.attr("id");	
		var li_class = 	clicked_li.attr("class");
		li_select_key = li_id.split("_")[1];
	
	
		//disabled list elements don't return values
		if(li_class.indexOf(configs.disabled_class) != -1 && click_disabled_item === true){
			return false;			
		};
		//
		clicked_li.addClass("selected").siblings().removeClass("selected");
		
		//	
		if(li_class.indexOf("all") != -1){			
			li_select_key		=	false;
		}		
		
		//the mood selection doesn't interact with other selections
		//reset current selection 
		//no siblings to search in	
		if (parent_id == "mood") {
			kill_current_selection(select_boxen_array);
		}
		
		else {
			//reset mood selection			
			kill_current_selection([select_boxen_array[3]]);
			
			//get siblings elements
			siblings = $(select_boxen_array).filter(function(i, item){
				return item.id !== parent_id && item.id != "mood";
			});
		}		
	
		//change html - set selected value
        $(value_holder_class,parent_obj).html(clicked_li.html());
		set_selected_key();
		load_cocktails();
	};
	
	/**
	 * reset the object values
	 */
	var kill_current_selection=function(elements){
	
		$.each(elements,function(i,item){
			if (item.id != parent_id) {
				item.selected_key = false;
				$("li", item.object).removeClass(configs.disabled_class);
				$(value_holder_class, item.object).html(item.headline);
			}	
		});			
	};
	
	/**
	 * set selected key in ul object
	 */
	var set_selected_key =function(){
		$.each(select_boxen_array,function(i,item){
			if(item.id==parent_id){			
				item.selected_key=li_select_key;
			}			
		});
				
	};
	/**
	 * triggered in ajax callback
	 * highlights/disables elements which deliver no cocktails
	 */
	var hide_unrelated_filter_elements=function(){
		
        var needle,haystack_index;
        if (typeof siblings != "undefined") {//other filter elements = select boxes
        	
			for (var i = 0; i < siblings.length; i++) {				
					
					//haystack is index of ajax_response
					//ajax_response is an object -> currently of this form:
					//data{
					//	available_ingredients:[],
					//	available_flavors:[],
					//	html:"",				
					//}
					haystack_index =get_ajax_index(siblings[i].id);
					
					//to highlight elements, which deliver no available cocktails 
					//the response array e.g. data.available_ingredients is searched for the 
					//li content				
					
					//search through array
					
					//if ($(siblings[i].object).find("li.selected").length == 0) {
					
						$(siblings[i].object).find("li").filter(function(){
							return $(this).attr("class").indexOf("all") == -1;
						}).addClass(configs.disabled_class).each(function(j, li_item){						
														
								//needle is the value of the list element 
								//loop throu the ajax request
								needle = $.trim($(li_item).html().replace(/mit /, ""));
								$.each(ajax_response[haystack_index], function(j, inner_item){
									if (inner_item.indexOf(needle) !== -1) {
										$(li_item).removeClass(configs.disabled_class);
									}
								});
						});//each
					//}
						
            }//for
			
        }//siblings handling finished
		
		if(search_in_clicked_ul === true){
			//handle parent object		
			haystack_index = get_ajax_index(parent_id);
					
			$(parent_obj).find("li").filter(function(){
				return $(this).attr("class").indexOf("all") == -1;
			}).addClass(configs.disabled_class).each(function(j, li_item){
				
				needle = $.trim($(li_item).html().replace(/mit /, ""));			
				$.each(ajax_response[haystack_index], function(j, inner_item){
					if (inner_item.indexOf(needle) !== -1) {
						$(li_item).removeClass(configs.disabled_class);
					}
				});			
			});//each
			//
		}
		
		
		//extra case			
		if(ajax_response.available_non_alcoholic===true){
			$(".non_alcoholic").removeClass(configs.disabled_class);			
		}	
		//
		
		//all was clicked - remove disabled class - there can be an empty answer from the ajax request
		if(li_select_key === false){
			//clicked_li.siblings().removeClass(configs.disabled_class);	
		}
		
		var params = collect_ajax_params();
		if(typeof params.ingredients_1 == "undefined" && typeof params.ingredients_2  == "undefined" && typeof params.flavors == "undefined" ){			
			$("body").find("." + configs.disabled_class).removeClass(configs.disabled_class);
		}
	};	
	/**	  
	 * @param {Object} id
	 */
	var get_ajax_index = function(id){
		var haystack;
		
		if (id == "ingredients_1" || id== "ingredients_2") 
			haystack = "available_ingredients";
					
		if (id == "flavors") 
			haystack = "available_flavors";
			
		return haystack;	
	};
	
	/**
	 * 
	 */
	var load_cocktails=function(){		
		show_cocktail_div();	
		do_ajax();
	};
	/**
	 * show cocktail div if its hidden
	 */
	var show_cocktail_div=function(){
		//check if cocktail content div is visible
		var cocktails_visible = $("#cocktails .teaser_content").is(":hidden");
		if(cocktails_visible){
			$("#cocktails .teaser_head").trigger("click");	
		}
	};	
	/**
	 * 
	 */
	var do_ajax = function(){
		var params = 	collect_ajax_params();		
		$.ajax( {
			url : configs.ajax_target,
			data : params,
			type : "post",
			dataTypeString : 'json',
			success : do_ajax_cb
		});	
	};
	/**
	 * 
	 * @param {Object} data
	 */
	var do_ajax_cb=function(response) {			
        
        ajax_response = response;
        //update html response				
        $(cocktail_container_id + " .teaser_content").html(response.html);
        //			
        
        //hide unrelated filter items
		if (parent_id !== "mood") {
			hide_unrelated_filter_elements(response);
		}
        //
        
        //
        $("body").trigger(session_event_obj);
        //				
        
        //
		listeners.cocktail_click.call();
        //	
					
	};
	
	that.init = init;
	return that;
}

