// Filtersearch.js

/* ***************************************************

   This class sets up the Ajax Search and Paging using the passed in options to get
   hold of all the required <divs> <selects> <forms> etc.


   If the useFilter option is set:true it will init the Filter Search as well.


   Options
   -------

contentDivId:             The ID of the Main Content <div>.
keywordFormId:            The ID of the form that holds the Keyword text <input> and buttons.
keywordTextId:            The ID of the Keyword form text <input>.
keywordSubmitButtonId:    The ID of the Keyword form Submit Button.
keywordResetButtonId:     The ID of the Keyword form Reset Button.
ajaxResponseDivId:        The ID of the <div> that Ajax request returns will populate.
actionPath:               The Ajax action path.
indexPath:                The Normal action path.
userMessageDivId:         The ID of the <tag> used for User Messages.
ajaxLoadingClass:         The CLASS to apply to 'userMessageDiv'
remoteLinkClass:          The CLASS of links that should be made AJAX.
productCount: '20000',    The Maximum site product count.
useFilter: false          Boolean to activate Filter Search.
filterFormId:             The ID of the form that holds the filter menus.
filterSelectClass:        The CLASS of the Filter form <selects>.
filterSubmitButtonId:     The ID of the Filter form Submit Button.
filterResetButtonId:      The ID of the Filter form Reset Button.
resultsPerPageId:         The ID of the <hidden> text field that holds the resultsperpage number.
productCount: '20000',    The Maximum site product count.

 **************************************************** */

FilterSearch = new Class({
        options: {
                contentDivId: 'content',
                keywordFormId:'search_panel',
                keywordTextId:'search_term',
                keywordSubmitButtonId: 'btn_submitkeyword',
                keywordResetButtonId: 'btn_resetkeyword',
                ajaxResponseDivId: 'response',
                actionPath: 'index:search.json',
                indexPath: 'index:search.html',
                userMessageDivId: 'request_status',
                ajaxLoadingClass: 'ajax_loading',
                remoteLinkClass: 'remote_link',
                productCount: '20000',
                useFilter: true,
                filterFormId: 'frm_context_options',
                filterSelectClass: 'select',
                filterSubmitButtonId: 'sendsearch',
                filterResetButtonId: 'btn_clear',
                resultsPerPageId: 'resultsperpage',
                singleResetButtonText: false,
                typeAheadOptions: false,
                useConsole: false,
                resetUpdatesResults:false
	    },
        initialize: function(options) {
		    try {
			    this.setOptions(options);

			    if(window.gecko && this.options.useConsole) { this.ff = true; }
			    this.ff=false;

				this.filterform = $(this.options.filterFormId);
				this.filterSelects = $$('.' + this.options.filterSelectClass);
				this.btn_filterreset = $(this.options.filterResetButtonId);
				    
                this.setSelectChangeEvents();
				this.setFilterResetButtonEvent();

			    // Results per page.
			    this.rppEl = $(this.options.resultsPerPageId);
			    this.normal_resultsperpage =  this.getResultsPerPage();
			    if(!this.rppEl || !this.normal_resultsperpage) { throw("Missing 'ResultsPerPage' Element and/or 'ResultsPerPage' Integer!"); }

			    // User Message.
			    this.message = $(this.options.userMessageDivId);

		    } catch(err) { this.handleError(err); }
	    },
        inform:function(info) { if(this.ff) { console.log("FILTERSEARCH INFO: " + info); } },
        handleError:function(err) { 
	        if(this.ff) { 
		        console.log("FILTERSEARCH ERROR: " + err);
	        } 
        },
        setSelectChangeEvents: function() {
			       try {
				       if(this.options.useFilter) {
					       if(this.filterSelects && this.filterSelects.length > 0) {
						       this.filterSelects.each(function(selectEl) {
								       if(selectEl.options.selectedIndex == '1') { selectEl.options.selectedIndex = 0; }
								       // selectEl.removeEvents("change");
								       selectEl.addEvent("change", this.changedFilter.bindWithEvent(this));
                                       selectEl=null;
								       }, this);
					       }
				       }
			       } catch(err) { this.handleError(err); }
		},
        removeSelectChangeEvents: function() {
				  try {
					  if(this.filterSelects && this.filterSelects.length > 0) {
						  this.filterSelects.each(function(selectEl) {
								  selectEl.removeEvents("change");
                                  selectEl=null;
								  }, this);
						  return true;
					  }
					  return false;
				  } catch(err) { this.handleError(err); }
		},
        setFilterResetButtonEvent: function() {
				   try {
					   if(this.options.useFilter) {
						   if(this.btn_filterreset) {
							   // this.btn_filterreset.removeEvents("click");
							   this.btn_filterreset.addEvent("click", this.resetFilterForm.bindWithEvent(this));
							   return true;
						   }                    
					   } 
					   return false;
				   } catch(err) { this.handleError(err); }
		},
        resetOption: function(e) {
		     try {
			     if(this.options.useFilter) {
				     if(!e) { return false; }
				     e = new Event(e).stop();
				     // Get the <select> from the ID of the Mini Reset button.
				     var el_id = e.target.getProperty('id');
				     if(!el_id) { return false; }
				     var parts = el_id.split("_"); 
				     if(!parts || parts.length < 2) { return false; }
				     var select_el = parts[0];
				     if(!select_el) { return false; }
				     // Remove the onchange event as we are changing the selectedIndex.
				     this.removeSelectChangeEvents();
				     selectEl = $(select_el);
				     selectEl.options.selectedIndex = 0;
				     Cookie.set('current_' + select_el, '');
				     // Call the search again.
				     this.changedFilter(selectEl);
				     return true;
			     }
			     return false;
		     } catch(err) { this.handleError(err); }
	    },
        setMessage:function(str) {
		   try {
			   if(str) {
				   this.message.addClass(this.options.ajaxLoadingClass);
				   this.message.setHTML(str);
			   } else {
				   this.message.empty();
				   this.message.removeClass(this.options.ajaxLoadingClass);
			   }
		   } catch(err) { this.handleError(err); }
	    },
        getFiltersBuildQuery: function(type) {
			      try {
				      return (this.filterform && (this.options.useFilter)) ? this.filterform.toQueryString() : "";
			      } catch(err) { this.handleError(err); }
		},
        buildRpcQuery:function() {
		      var ti = Math.round(new Date().getTime()/1000.0);
		      if(!ti) { return false; }
		      var time = "&time=" + ti;
		      var nocache = '&nocache=1';
		      return nocache + time;
	    },
        getUrlPath:function() {
		   try {
			   var current_url = unescape(location.href);
			   var xstart = current_url.lastIndexOf("/") + 1;
			   var xend = current_url.length;
			   var hereName = current_url.substring(xstart,xend);
			   var herePath = current_url.substring(0,xstart);

			   this.url = herePath + this.options.actionPath;
			   this.url2 = herePath + this.options.indexPath;
			   return herePath;
		   } catch(err) { this.handleError(err); }
	   },
       getSearchTermBuildQuery: function() {
				 try {
					 Cookie.set("current_keyword",this.keywordtext.getProperty('value'));            
					 return (this.keywordform) ? this.keywordform.toQueryString() : "";
				 } catch(err) { this.handleError(err); }
		},
        changedFilter: function(e, reset) {
		       try {
			       if(!this.options.useFilter) { return false; }
			       var lc = false;
			       if(e && e.type == 'change') {
				       e = new Event(e).stop();
				       lc = e.target.getProperty('id');
			       } else {
				       lc = $(e).getProperty('id');
			       }
			       if(!lc) { lc = ""; }
			       Cookie.set('lastclicked',lc);
			       this.removeSelectChangeEvents();
			       this.saveOptions();
			       this.setResultsPerPage(this.options.productCount);
			       this.getUrlPath();
			       var nocache = this.buildRpcQuery();
			       var filter_params = this.getFiltersBuildQuery();
			       var keyword_params = this.getSearchTermBuildQuery();
			       var post_data = filter_params + "&" + keyword_params + nocache;
			       if(reset==true) {  post_data = post_data + "&resetfilter=1"; }
			       if(!post_data) {
				       return false;
			       }
			       this.post_data = post_data + "&json=1";
			       var options = {
                        method: 'post',
                        data: this.post_data,
                        evalResponse: false,
                        autoCancel: true,
                        onRequest: function() {
                            this.options.filterMenus.each(function(item) {
                                if(item.id !== lc) {
                                    item.options[0] = new Option("Updating", "");
                                    item.selectedIndex = 0;
                                }
                                item = null;
                            });

		            $$('reset').each(function(resetEl) { resetEl.empty(); }, this);
	                },
                    onComplete: function(resp) {
                        this.options.rpp.value=14;
                        try {
                            if(resp && resp !=="null") {
                                var response = eval(resp); 
                                if(response.fail) {
                                    this.options.filterMenus.each(function(item) { 
                                            var title = item.id;                           
                                            item.options[0] = new Option("Any " + title, "");
                                            item.selectedIndex = 0;                        
                                            item = null;
                                            });
                                    if(this.options.ref) {
                                        this.options.ref.setMessage("No Available Filters");
                                    }
                                } else {                        
                                    if(this.options.ref) { this.options.ref.setMessage(false); }
                                }                    
                            } else {
                                if(this.options.ref) {
                                    // this.options.ref.setMessage(false);
                                    if(this.options.ref.ff) { }  
                                    this.options.ref.setMessage(false);  
                                }
                            }
                        } catch(err) {
                            if(this.options.ref) {
                                this.options.ref.handleError(err);
                                this.options.ref.setMessage(false);
                            }
                        }
                        var last_clicked = Cookie.get("lastclicked");
                        try {

                            this.options.filterMenus.each(function(selectEl) {
                                    var select_id = selectEl.getProperty('id');
                                    if(select_id) {
                                    var menu_block = response[select_id];
                                    if(menu_block) {
                                    selectEl.options.length = 0;
                                    menu_block.each(function(menuEl,c) {
                                        var option_title = menuEl.title;
                                        var option_token = menuEl.token;
                                        if(c == 0) { option_title =  "Any " + option_title; }
                                        selectEl.options[c] = new Option(option_title, option_token);
                                        if(option_title !=='') {
                                        if(Cookie.get("current_" + select_id) == option_title) {
                                        selectEl.options.selectedIndex = c;
                                        }
                                        }
                                        menuEl=null;
                                        }); 
                                    }
                                    }
                                    selectEl=null;
                                    }, this);
                        } catch(err) {
                            if(this.options.ref) {
                                this.options.ref.handleError(err);
                            }
                        } finally {
                            if(this.options.ref) { this.options.ref.setMessage(false); }
                            Window.filterSearchObj.setSelectChangeEvents();
                            this.options.rpp.value=14;
                        }
                    }
			       };

			       var ni = Window.XHRObject.xhrs.length;

			       Window.XHRObject.xhrs[ni] = new Ajax(this.url, 
                        $merge({ ref: this, 
                                reqState: this.message,
                                filterForm: this.filterform, 
                                filterMenus: this.filterSelects, 
                                rpp: this.rppEl}, 
                                options));

			       Window.XHRObject.xhrs[ni].request();

		       } catch(err) {
			       if(this.options.ref) {
				       this.options.ref.handleError(err);
				       this.options.ref.setMessage("Search Request Failed.");  
			       }              
		       }
	    },
        saveOptions: function() {
		     try {
			     if(this.options.useFilter) {
				     this.filterSelects.each(function(selectEl) {
						     var el_id = selectEl.getProperty('id');
						     var el_val = selectEl.getProperty('value');
						     if(el_id) {
						        var cname = "current_" + el_id;
						        Cookie.set(cname, el_val);
						     }
						     selectEl=null;
                         }, this);
				     return true;
			     }
			     return;
		     } catch(err) { this.handleError(err);  }
	    },
        removeSavedOptions: function(id) {
			    try {
				    if(this.options.useFilter) {
					    if(id) { 
						    Cookie.remove("current_" + id);  
						    return true;
					    }
					    this.filterSelects.each(function(selectEl) {
							    var el_id = selectEl.getProperty('id');
							    var el_val = selectEl.getProperty('value');
							    if(el_id) {
							    var cname = "current_" + el_id;
							    if(el_val) {
							    Cookie.remove(cname);
							    }
							    }
                                selectEl=null;
							    }, this);
					    return true;
				    }
				    return false;
			    } catch(err) { this.handleError(err);  }
        },
        resetFilterForm: function(e) {
			 try {

				 if(e) { e = new Event(e).stop(); }
				 else { return false; }

				 if(this.options.useFilter) {
					 this.resetFilters();
					 this.removeSavedOptions();
					 if(this.options.resetUpdatesResults == true) {
						 // this.filterResults(e);
					 } else {
						 this.changedFilter(this.btn_filterreset);
					 }
					 return true;
				 }
				 return false;
			 } catch(err) { this.handleError(err); return false; }
		 },
        resetFilters:function() {
		     try {
			     if(this.options.useFilter) {
				     this.removeSelectChangeEvents();
				     this.filterSelects.each(function(selectEl) { selectEl.options.selectedIndex = 0; selectEl=null; }, this);
				     return true;
			     } return false;
		     } catch(err) { this.handleError(err);  }
	     },
        setResultsPerPage: function(val) {
			   if(!val || val == '') { return false; }
			   try {
				   if(this.rppEl) { 
					   this.rppEl.value = val;
					   return true;
				   }
				   return false; 
			   } catch(err) { this.handleError(err); return false; }  
		},
        getResultsPerPage: function() {
			   try {
				   if(this.rppEl && this.rppEl.value !=='') {
					   return this.rppEl.value;
				   } else { return false; }
			   } catch(err) { this.handleError(err);  }
		   }
    });
    FilterSearch.implement(new Options());

window.addEvent('domready',function() {

	var fsOptions = {
		contentDivId: 'content',
		keywordFormId:'search_panel',
		keywordTextId:'search_term',
		keywordSubmitButtonId: 'btn_submitkeyword',
		keywordResetButtonId: 'btn_resetkeyword',
		ajaxResponseDivId: 'response',
		actionPath: 'index:search.json',
		indexPath: 'index:search.html',
		userMessageDivId: 'request_status',
		ajaxLoadingClass: 'ajax_loading',
		remoteLinkClass: 'remote_link',
		productCount: '20000',
		useFilter: true,
		filterFormId: 'frm_context_options',
		filterSelectClass: 'select',
		filterSubmitButtonId: 'sendsearch',
		filterResetButtonId: 'btn_clear',
		resultsPerPageId: 'resultsperpage',
		singleResetButtonText: false,
		useConsole:true,
		resetUpdatesResults:false
	};

    // filterSearch
    filterSearchObj = new FilterSearch(fsOptions);
});


