// MooTools based functions for the Dr. Bott Advanced Product Search 
// v1.0 Jeff Leach - 7/12/2011
// v1.1 Jeff Leach - 12/12/2011 - Added Color search
// v1.2 Jeff Leach - 1/20/2012 - Added functions for search segmentation capsules.

		function drbClone(f_objToClone){
		  var l_clone = f_objToClone.clone();
          var baseName = f_objToClone.id.substr(0,(f_objToClone.id.length -2));
          
          //create some global variables to track of the count of fields added to the form
          //these numbers never get decrease, they only increase to make sure I create
          //unique ID's for each one created.
          
          if (typeof window[baseName + '_cnt'] === 'undefined') {
            window[baseName + '_cnt'] = 11;
          }else {
            window[baseName + '_cnt'] = parseInt(window[baseName + '_cnt']) + 1;
          }
                 
          var n_obj = l_clone.inject(f_objToClone,'after');
          n_obj.set('id',baseName + window[baseName + '_cnt']);
          $$('#' + l_clone.id + ' input[value=+]').each(function(ritem) {
                ritem.addEvent('click',function(){drbClone(this.getParent());});
                ritem.addEvent('mouseover',function(){drbSetHelp(this);}); 
                ritem.addEvent('focus',function(){drbSetHelp(this);});   
          });
          $$('#' + l_clone.id + ' input[value=-]').each(function(ritem) {
                ritem.setStyle('visibility','visible');
                ritem.addEvent('click',function(){drbRemoveInput(this.getParent());});
                ritem.addEvent('mouseover',function(){drbSetHelp(this);}); 
                ritem.addEvent('focus',function(){drbSetHelp(this);});   
          });
          $$('#' + l_clone.id + ' input[type=text]').each(function(ritem) {
              ritem.set('value','');
              ritem.addEvent('mouseover',function(){drbSetHelp(this);}); 
              ritem.addEvent('focus',function(){drbSetHelp(this);}); 
              ritem.addEvent('keydown',function(event) {
                                    var acActive = false;
                                    if(event.key == "enter") {
                                        $$('ul.autocompleter-choices').each(function(auitem){
                                            if (auitem.getStyle('visibility')== 'visible'){
                                                acActive = true;
                                            }
                                         });
                                         if (!acActive){
                                         drbFixMultiValues(); 
                                         window.location = drbCreateUrl();
                                         }
                                      }
                                   });             
              new Autocompleter.Request.JSON(ritem, '/advsearch/query_user.php', {
                    'postVar': '' + ritem.get('name').toLowerCase(),
                    'multiple': false,
            		separator: '|'
              });
              ritem.focus();
          });
        }
        function drbRemoveInput(f_objToRemove){
          //var baseName = f_objToRemove.id.substr(0,(f_objToRemove.id.length -2));
          var baseNum = f_objToRemove.id.substr((f_objToRemove.id.length -2),2);
          //if (typeof window[baseName + '_cnt'] === 'undefined') {
          //  null;
          //}else {
            if (parseInt(baseNum) >= 11){
                //window[baseName + '_cnt'] = parseInt(window[baseName + '_cnt']) - 1;
                f_objToRemove.destroy();
            }
          //} 
        }
        function drbFixMultiValues() {
              // Replace spaces with pipe symbols. If someone pastes in a list of values with CR or spaces - will fix it up.
              // note - IE input field reacts different and truncates list with CR rather than converting them to spaces like FF or Safari
              // Just do this on productnumber
              $$('#fe-productnumber').each(function(ritem2) {
                curVal = ritem2.get('value').toUpperCase(); 
                if(curVal !== '' ){
                    //To replace every occurrence of a string in JavaScript, you must provide the replace() method a regular expression with a global modifier as the first parameter:
                    ritem2.set('value',curVal.replace(/ /g,'|'));
                }
            });
            
        }
        function drbCreateUrl(fcurobj){
           // var newUrl = '/search/?';
            var newUrl = ''; //'$('drbsite').get('value') + '?';
            var asItem = '';
            //concat - all dynamic fields into hidden fields an 
            $$('#demo1content input[type=text]').each(function(ritem){
                        curRootVal = $(ritem.name + "-hid").get('value');
                        if (ritem.get('value') !== ''){
                            if (curRootVal.substr(curRootVal.length-1,1)=='|'){
                                curRootVal = curRootVal.substr(0,curRootVal.length-1);
                            }
                            if (curRootVal !==''){
                                asItem = curRootVal + '|' + ritem.get('value');
                            }else{
                                asItem = ritem.get('value');
                            }
                            //8/1/2011 JBL replace spaces with + so %20 doesn't show up in the search string
                            asItem = asItem.replace(/ /g,'+');           
                            $(ritem.name + "-hid").set('value',asItem);
                        }               
            });
            // then using hidden fields to build the destination url
            $$('#drbFinalSearch input[type=text]').each(function(ritem) {
                    curVal = ritem.get('value');
                    if(curVal !== '' ){
                        if (newUrl == ''){
                            newUrl = $('drbsite').get('value') + '?' + ritem.get('name').toLowerCase()+ '=' + curVal;
                        }else{
                    	    newUrl = newUrl + '&' + ritem.get('name').toLowerCase()+ '=' + curVal;
                        }
                    }
            });
            return newUrl;
        }
        function drbSetHelp(f_curObj) {
            $$('.greyBox .greyContentContainer .greyContentList ul .firsthlp').each(function(ritem){
                var curField = f_curObj.get('name');
                var helpText = '';
                switch(curField)
                {
                case 'long':
                  helpText = 'The product name search will search for product names that \"begin with\" the entered value.';
                  break;
                case 'cat':
                  helpText = 'The category search will retrieve all products in the entered category OR categories that contain the entered value.';
                  break;
                case 'vend':
                  helpText = 'The manufacturer search will retrieve all products made by the requested manufacturer OR all manufacturers that \"begin with\" the entered value.';
                  break;
                case 'compatibility':
                  helpText = 'The compatibility search will retrieve all products compatible with either the product name entered OR products names that contain the entered value.';
                  break;
                case 'productnumber':
                  helpText = 'The part number search will retrieve exact matches for the entered part number or numbers.  This search will try to match the entered part number against the following: Dr. Bott product code, Manufacturer part number, UPC or ISBN';
                  break;
                case 'color':
                  helpText = 'The color search will retrieve products having the selected color attribute.';
                  break;                  
                case 'quicksearch':
                  helpText = "Quick Search is similar to a \"google\" search.  It finds products similar to words in your search phrase.";
                  break;
                default:
                    var curField = f_curObj.get('value');
                    switch(curField){
                        case '+':
                            helpText = 'Need to search for more than one item? Click the \"+\" button to add an additional input field';
                            break;
                        case '-':
                            helpText = 'Remove extra search fields with the \"-\" button';
                            break;
                        default: helpText = '';
                    }
                }
                if (helpText != ''){
                ritem.innerHTML = helpText;
                }
            })
        }
	 	function drbAdvSearch() {
	 	    //turning this off always at the moment because the autocompleter fields
            //don't scroll with the lightbox if scroll happens when they are open
           /* if(Browser.Platform.ipod) {
                   var drbScroll =  false;
                   }
            else{
                    var drbScroll = false;
            }
            if (Browser.ie6){
                alert('Sorry, advanced search is not available on IE version 6.  Please upgrade your browser.');
                return;
            } */           
	 	    var drbScroll =  false;
         
            if (typeof lfbox === 'undefined') {
                        lfbox = new LightFace.Request({
        	 			title: 'Advanced Search',
        	 			//content: $('demo1content').innerHTML,
        				url: '/advsearch/adv_search_ajax.php',
        				draggable: true,
                        multiple: false,
                        resetOnScroll: drbScroll,
                        position: 'nocenter',
                        altFocusNode: 'fe-name',
                        request: { 
        						method: 'post'
        					},
                        onSuccess: function(){
                            
                            //Add AutoCompleter
                            // 7/15/2011 Eric didn't want the multiple values in one field: setting to false 
                            new Autocompleter.Request.JSON('fe-vendor', '/advsearch/query_user.php', {
                                'postVar': 'vend',
                                'multiple': false,
                        		separator: '|'
                            });
                            new Autocompleter.Request.JSON('fe-category', '/advsearch/query_user.php', {
                                'postVar': 'cat',
                                'multiple': false,
                        		separator: '|',
                                separatorSplit: /\s*[|;]\s*/
                            });
                            new Autocompleter.Request.JSON('fe-compatibility', '/advsearch/query_user.php', {
                                'postVar': 'compatibility',
                                'multiple': false,
                        		separator: '|',
                                separatorSplit: /\s*[|;]\s*/
                            });
                            new Autocompleter.Request.JSON('fe-name', '/advsearch/query_user.php', {
                                'postVar': 'long',
                                'multiple': false,
                        		separator: '|',
                                separatorSplit: /\s*[|;]\s*/
                            });                             
                            drbcolor = new Autocompleter.Request.JSON('fe-color', '/advsearch/query_user.php', {
                                'postVar': 'color',
                                'multiple': false,
                        		separator: '|',
                                separatorSplit: /\s*[|;]\s*/
                            });   
                             $$('#fe-color').each(function(ritem) {
                                    ritem.addEvent('focus',function(){if(this.value=='') {this.value='%';drbcolor.observer.onFired();this.value='';}});   
                             });                         
                            $$('#demo1content .drbAdd').each(function(ritem) {
                                ritem.addEvent('click',function(){drbClone(this.getParent());});  
                            });
                            $$('#demo1content .drbMinus').each(function(ritem) {
                                ritem.addEvent('click',function(){drbRemoveInput(this.getParent());});  
                            });
                            $$('#demo1content input').each(function(ritem) {
                                ritem.addEvents({
                                    mouseover: function(){drbSetHelp(this);},  
                                    focus: function(){drbSetHelp(this);},
                                    keydown:function(event) {
                                    var acActive = false;
                                    if(event.key == "enter") {
                                        $$('ul.autocompleter-choices').each(function(auitem){
                                            if (auitem.getStyle('visibility')== 'visible'){
                                                acActive = true;
                                            }
                                         });
                                         if (!acActive){
                                         drbFixMultiValues(); 
                                         window.location = drbCreateUrl();
                                         }
                                      }
                                   }
                                });
                            });  
                        },
                        onClose: function(){
                            $$('#demo1content input[type=text]').each(function(ritem) {
                                  ritem.set('value','');
                            });  
                        },
           	            buttons: [
                            { 
        						title: 'Search',
        						color: 'blue', 
                                event: function() {drbFixMultiValues(); window.location = drbCreateUrl();return false;/*document.forms["DrBottAdvSearch"].submit();*/}
                        	},
        					{
        						title: 'Cancel',
        						event: function() { this.close(); 
                                        }
        					}
        				]
        	 		}).open();
                } 
            else {
                lfbox.open();

            }
            return;
	 	}
	 	function drbSearchSegments(f_seg,f_this,f_title) {
	 	    //doing the next line causes mootools to extend the methods and attributes that are missing on some dom elements in IE 
            myPosElem = document.id(f_this);
            myPos = myPosElem.getPosition();
            if (typeof drbReload === 'undefined' || drbReload == false){
                if (typeof drbSSlfbox === 'undefined') {
                            drbSSlfbox = new Array();
                };
               if (typeof drbSSlfbox[f_seg] === 'undefined'){
                            
                            drbSSlfbox[f_seg] = new LightFace.Static({
                            title: f_title + '<span id="leftNavContent" style="font-size:10px;float:right;padding-top:3px;padding-right:0px;"><a onclick="javascript:drbAdvSearch();" href="#" id="drbsearch">Go to Advanced Search</a></span>',
            	 			content: $('drbSS' + f_seg).innerHTML,
            				draggable: true,
                            resetOnScroll: false,
                            useShadowBox: false,
                            useMaxHeight: false,
                            position: 'nocenter',
                            offsets: {
                    			x: 0,
                    			y: -17
                    		},
                            onOpen: function(){
                                  //register event to Close if clicked outside
                                var closer = function(e) {
                                    var parent = $(drbSSlfbox[f_seg]).getParent('.lightface');
                                    var myElement = document.id(e.target);
                                   	if(e.target != parent && ! parent.hasChild(e.target) &&  (myElement.id != 'drbseg' + f_seg && myElement.getParent().id != 'drbseg' + f_seg)|| myElement.id == "drbsearch") {
                                        drbSSlfbox[f_seg].close();
                                        document.id(document.body).removeEvent('click',closer);
                                	}
                                };
                                document.id(document.body).addEvent('click',closer);
                            }  
            	 		}).open(false,myPos.x,myPos.y);
                }
                else {
                    drbSSlfbox[f_seg].open(false,myPos.x,myPos.y);
                }
            }
            return;
	 	}
        function drbSearchMod(f_type,f_value,f_keep) {
            drbReload = true;
            var loc = window.location;
            var newSearch = loc.protocol + '//' + loc.host + loc.pathname;  
            if (f_type == 1){
                //alert(f_value);
                f_value = unescape(f_value);
                //alert(f_value);
                //first escape the special regex chars in my expression f_value then use it to remove from the search string
                f_value = f_value.escapeRegExp();             

                //dumb hack for compatibilities that have " in them
                //should use some kind of unescape but I can't find the right combination where php and javascript escape/unescape the same char set
                paramStr =  loc.search
                myregexp = new RegExp('\%22','gi');
                paramStr = paramStr.replace(myregexp,'"');
                
                
                //& or ? at the beginning of the string and & or end of string at the end
                myregexp = new RegExp('(&|)' + f_value + '&','gi');
                paramStr =  paramStr.replace(myregexp,'&');
                myregexp = new RegExp('(&|)' + f_value + '$','gi');
                paramStr =  paramStr.replace(myregexp,'');
                
                //let's reset the pagination
                myregexp = new RegExp('&skip=[0-9]+','gi');
                paramStr = paramStr.replace(myregexp,'');
                
                //a little clean up in case we ended up with & right after the ? in the query string
                myregexp = new RegExp('\\?&','gi');
                paramStr =  paramStr.replace(myregexp,'\?');
                
                //if (paramStr=='?'){
                    //alert("Sorry, clearing all filters would return too many results.  Please try a different search.");
                //    drbReload = false;
                //    return false;
                //}
                newSearch = newSearch + paramStr;
            }
            if (f_type == 2){
                //alert(f_value);
                f_value = unescape(f_value);
                //alert(f_value);
                //let's reset the pagination
                myregexp = new RegExp('&skip=[0-9]+','gi');
                paramStr = loc.search.replace(myregexp,'');
                
                //special handling for &sort=  - want to remove all other sort options if we are setting a new sort.
                if (f_value.indexOf('sort=')== 0){
                    //let's reset the sort
                    myregexp = new RegExp('(\\?|&)sort=[a-z +A-Z]+','gi');
                    if (paramStr.indexOf('?sort=')== 0){
                        paramStr = paramStr.replace(myregexp,'?');
                    }else{
                        paramStr = paramStr.replace(myregexp,'');
                    }
                }
                
                //a little clean up in case we ended up with & right after the ? in the query string
                myregexp = new RegExp('\\?&','gi');
                paramStr =  paramStr.replace(myregexp,'\?');
                newSearch = newSearch + paramStr + '&' + f_value;
            }
            if (f_type == 3 || f_type == 4){
                paramAR = JSON.decode(f_value);
                /*if (typeof f_keep === 'undefined'){
                    paramKeepAR = new Array();
                }else{
                    paramKeepAR = JSON.decode(f_keep);
                }*/
                if (f_type == 3){
                paramStr =  loc.search;
                paramAR.each(function(ritem){
                        //if(paramKeepAR.indexOf(ritem)==-1){
                            //first escape the special regex chars in my expression f_value then use it to remove from the search string
                            ritem = ritem.escapeRegExp();
                         
                            myregexp = new RegExp('(&|)' + ritem + '&','gi');
                            paramStr =  paramStr.replace(myregexp,'&');
                            myregexp = new RegExp('(&|)' + ritem + '$','gi');
                            paramStr =  paramStr.replace(myregexp,'');
                        //}
                        }
                        )
                }
                if (f_type == 4){
                    paramStr = '?';
                    paramAR.each(function(ritem){
                        if (paramStr !== '?'){
                            paramStr = paramStr + '&';
                        }
                        paramStr = paramStr + ritem;    
                    })
                }
                //let's reset the pagination
                myregexp = new RegExp('&skip=[0-9]+','gi');
                paramStr = paramStr.replace(myregexp,'');
                
                //a little clean up in case we ended up with & right after the ? in the query string
                myregexp = new RegExp('\\?&','gi');
                paramStr =  paramStr.replace(myregexp,'\?');
                
               // if (paramStr=='?'){
               //     alert("Sorry, clearing all filters would return too many results.  Please try a different search.");
               //     drbReload = false;
               //     return false;
               // }                
                newSearch = newSearch + paramStr; 
            }            
            if (loc.hash!=''){
                newSearch = newSearch + loc.hash;
            }
            window.location = newSearch;
        }




