modules.loadActions.prototype.search = function(){
  
  search = this.search;
  search.form = $$('form.'+SiteVars.modules.Search.formClass);
  search.hvcbMemberSearch = $$('form.'+SiteVars.modules.Search.memberClass);
  search.vacationDirectory = $$('form.vacationdirectory');
  
  search.regExTerm = new RegExp('"|\'|\&|\<|\>','gi');
  search.escapeXSL = new RegExp('(\&)(\#[0-9]*|amp)(\;)','gi');
  search.keywordsPhrase = SiteVars.modules.Search.keywordsPhrase;
  
  //{{{ search.loadSearch = function()
  search.loadSearch = function(){
    
    $A(search.form).each(function(sForm){
      
      try{
        sForm.selects = $A(sForm.getElementsByTagName('select')).map(Element.extend);
        sForm.sfInput = Element.select(sForm, 'input[name="searchText"]')[0];
        sForm.hasPaging = Element.select(sForm, '.paging');
        sForm.alphaNav = Element.select(sForm, '.pagination-letter')[0];
        sForm.rHandler = Element.select(Element.ancestors(sForm)[0], '.request-handler')[0];
        
        sForm.searchResults = Element.select(sForm, '.search-results')[0];
        
        
        
        sForm.sfInput.value = sForm.sfInput.value.replace(search.escapeXSL, '');
        SiteVars.modules.Search.defaultValue = SiteVars.modules.Search.defaultValue.replace(search.escapeXSL, '');
        sForm.isNewsSearch = Element.select(sForm, '.search-news-form-field')[0];
        if(sForm.useKeywords){
          //console.log('hi');
          sForm.useKeywords.value = sForm.useKeywords.value.replace(search.escapeXSL, '');
        }
      }
      catch(e){
        //console.dir(e);
      }
      
      try{
        if(sForm.sfInput.type=='text'){
          Event.observe(sForm.sfInput, 'focus', function(){
              if(sForm.sfInput.value==SiteVars.modules.Search.defaultValue){
                sForm.sfInput.value = '';
              }
          });
          
          Event.observe(sForm.sfInput, 'blur', function(){
              if(sForm.sfInput.value==''){
                sForm.sfInput.value = SiteVars.modules.Search.defaultValue;
              }
          });
        }
      }catch(e){
        //console.dir(e);
      }
      
      if(Element.select(sForm, '.submitlink')[0]){
        
        $A(Element.select(sForm, '.submitlink')).each(function(sLink){
            //alert('we have a link 3');
            Event.observe(sLink, 'click', function(e){
                //console.log(unescape(Form.serialize(sForm)).replace(/&#34;/gi, '"' ));
                document.location = sLink.href + '?' + unescape(Form.serialize(sForm)).replace(/&#34;/gi, '"' );
                Event.stop(e);
            });
        });
      }
      
      sForm.buildSortingProps = function(){
      
        sForm.autoSelects = Element.select(sForm, '.autochange');
        sForm.clearButtons = $$('#search-filter .restart');
        //console.log(sForm.clearButtons);
        try{
          if(sForm.autoSelects[0]){
            sForm.autoSelects.each(function(select){
                Event.observe(select, 'change', function(e){
                    //alert("hi");
                    //sForm.submit();
                    var useAlpha = (Element.select(sForm.alphaNav, '.selected')[0])? '&' + Element.select(sForm.alphaNav, '.selected')[0].rel : '' ;
                    search.setMId(sForm.selectIslandId);
                    
                    if(Element.hasClassName(sForm, 'eventsform')){
                      //sForm.ajaxCalls.url = sForm.action + 'paged'
                    }
                    else {
                      sForm.ajaxCalls.url = SiteVars.path_to_top + '/directory/search-paged';
                    }
                    //console.log('BBBBBBBBBBBBBBBBBBB');
                    /* sForm.ajaxCalls.params = Form.serialize(sForm) + useAlpha;
                    
                    modules.sendAsync(sForm.ajaxCalls); 
                    Event.stop(e) */;
                    sForm.runSubmit(e);
                });
                
            });
          }
          
          if(sForm.clearButtons[0]){
            
            sForm.clearButtons.each(function(cB){
                
                Event.observe(cB, 'click', function(e){
                    //console.log(e);
                    if(Element.hasClassName(sForm, 'membersearchform') || Element.hasClassName(sForm, 'multidestination')){
                      try{
                        sForm.runReset();
                      }
                      catch(err){
                        console.dir(err);
                      }
                    }
                    Event.stop(e);
                }).bind(sForm);
                
            });
          }
          
          
        }catch(e){
          //console.dir(e);
        }
      }
      
      try{
      if('hasPaging' in sForm){
        
        sForm.buildPagingProps = function(){
          
          sForm.paging = null;
          sForm.paging = {};
          
          sForm.alphLinks = null;
          sForm.alphLinks = {};
          
          
          try{
            
            sForm.btnRefresh = Element.select(sForm, 'div.submit input.image')[0];
            
            sForm.paging = Element.select(sForm, '.paging')[0];
            sForm.paging.PageNumber = Element.select(sForm, 'input[class="pageNum"]')[0];
            sForm.paging.links = Element.select(sForm, '.paging a[rel]');
            sForm.paging.searchFilter = Element.select(sForm, '.search-filter')[0];
            sForm.paging.searchTools = Element.select(sForm, '.search-tools')[0];
            sForm.paging.paginationTop = Element.select(sForm, '.pagination')[0];
            sForm.paging.paginationBottom = Element.select(sForm, '.pagination')[1];
            
            sForm.alphaNav = Element.select(sForm, '.pagination-letter')[0];
            sForm.alphaNav.links = Element.select(sForm.alphaNav, 'a[rel]');
            
            sForm.hiddenFields = Element.select(sForm, '.hidden-fields')[0];
            
            sForm.ajaxCalls = {
              evalScripts:true,
              url:sForm.action,
              updateElem:sForm.rHandler,
              onLoad:function(){
                sForm.searchResults.innerHTML = '';
                sForm.paging.paginationBottom.innerHTML = '';
                modules.addLoadingClass(sForm.searchResults, 'async-loading');
              },
              onSuccess:function(){},
              onComplete:function(){
                if(!Element.hasClassName(sForm, 'mylistform')){ sForm.setState(); }
                modules.removeLoadingClass(sForm.searchResults, 'async-loading');
                sForm.parseResults();
                
                if('objMapIt' in window) {
                  objMapIt.reload();
                }
                
              }
            }
            
          }
          catch(e){
            //console.dir(e);
          }
          try{
            sForm.paging.siteFilters = Element.select(sForm, '.site-filters')[0];
          }catch(e){}
          
          
          if(sForm.btnRefresh){
            Event.observe(sForm.btnRefresh, 'click', function(e){
                //console.log('gotcha?');
                //sForm.submit();
                //Event.stop(e);
            });
          }
          
          try{
            sForm.typeFilters = null;
            sForm.typeFilters = {};
            sForm.typeFilters = Element.select(sForm, '.type-filters');
            
            sForm.typeFilters.each(function(filter){
                Event.observe(filter, 'click', function(){
                    if(filter.checked && Element.hasClassName(filter, 'nofilter')){
                      sForm.resetFilters(true);
                    }
                    else if(filter.checked && !Element.hasClassName(filter, 'nofilter')){
                      sForm.resetFilters(false);
                    }
                });
            });
            
            sForm.resetFilters = function(reset){
              if(reset){
                sForm.typeFilters.each(function(filter){
                    if(!Element.hasClassName(filter, 'nofilter')){
                      filter.checked = false;
                    }
                });
              }
              else{
                sForm.typeFilters.each(function(filter){
                    if(Element.hasClassName(filter, 'nofilter')){
                      filter.checked = false;
                    }
                });
              }
            }
            
          }catch(e){}
          
          sForm.paging.links.each(function(link){

              Event.observe(link, 'click', function(e){
                  
                  Event.stop(e);
                  
                  var useAlpha = (Element.select(sForm.alphaNav, '.selected')[0])? '&' + Element.select(sForm.alphaNav, '.selected')[0].rel : '' ;
                  try{
                    sForm.membersSortField.value = (useAlpha!='') ? 'SortName' : sForm.membersSortField.value;
                  }catch(e){}
                  sForm.paging.PageNumber.value = link.rel;
                  
                  if(Element.hasClassName(sForm, 'eventsform')){
                    sForm.ajaxCalls.url = sForm.action + 'paged'
                  }
                  else if(Element.hasClassName(sForm, 'featuredform')){
                    sForm.ajaxCalls.url = sForm.action + '';
                  }
                  else if(Element.hasClassName(sForm, 'mylistform')){
                    sForm.ajaxCalls.url = SiteVars.path_to_top + '/myhawaii-paged';
                  }
                  else if(Element.hasClassName(sForm, 'sfresultscontent')){
                    sForm.ajaxCalls.url = SiteVars.path_to_top + '/async-content/search';
                  }
                  else if(Element.hasClassName(sForm, 'sfmediacontent')){
                    sForm.ajaxCalls.url = SiteVars.path_to_top + '/media/async-content/search';
                  }
                  else{
                    sForm.ajaxCalls.url = SiteVars.path_to_top + '/directory/search-paged';
                  }
                  
                  search.setMId(sForm.selectIslandId);
                  
                  sForm.ajaxCalls.params = Form.serialize(sForm) + useAlpha;
                  
                  modules.sendAsync(sForm.ajaxCalls); 
                  
                  //Event.stop(e);
                  
              }.bind(sForm));
          });
          
          sForm.alphaNav.links.each(function(link){
            
              Event.observe(link, 'click', function(e){
                  sForm.paging.PageNumber.value = 1;
                  if(Element.hasClassName(link, 'alpha-reset')){
                    sForm.membersSortField.selectedIndex=0;
                    sForm.searchTerm.value = sForm.searchTerm.value.substring(0, sForm.searchTerm.value.indexOf(' AND __FirstLetter:'));
                  }
                  else{
                    sForm.membersSortField.value = 'SortName';
                  }
                  search.setMId(sForm.selectIslandId);
                  if(Element.hasClassName(sForm, 'eventsform')){
                    sForm.ajaxCalls.url = sForm.action
                  }
                  else {
                    sForm.ajaxCalls.url = SiteVars.path_to_top + '/directory/search-paged';
                  }
                  sForm.ajaxCalls.params = Form.serialize(sForm) + '&' + link.rel;
                  
                  modules.sendAsync(sForm.ajaxCalls);
                  Event.stop(e);
              }.bind(sForm));
          });
          
        }
        
        sForm.setState = function(){
          var paramsString = Form.serialize(sForm);
          sForm.formState = {
            id:sForm.id,
            url:sForm.ajaxCalls.url,
            params:paramsString
          }
          location.hash = 'formState={"id":"'+sForm.formState.id+'","url":"'+sForm.formState.url+'","params":"'+escape(sForm.formState.params)+'"}';

          // sForm.ajaxHistoryForm.params.value = sForm.ajaxHistoryForm.params.value + 1;
          // sForm.ajaxHistoryForm.submit();
          // sForm.ajaxHistory.savedSearch = paramsString;
        }
        
        sForm.readState = function(){
          var hashString = location.hash.replace('#formState=', '');
          sForm.formState = modules.sanitizeResponse(hashString, {})
          sForm.ajaxCalls.url = sForm.formState.url;
          sForm.ajaxCalls.params = sForm.formState.params;
          // var updateParams = sForm.formState.params.replace(/([^&]*)=([^&]*)[&]*/gi, '"$1":"$2" , ');
          // sForm.updateObj = modules.sanitizeResponse('{'+updateParams+'}', {});
        }
        
        
        sForm.parseResults = function(){
          //try collection the recieved markup and replacing bits of the current form in bundles - use if instead of try (fails in IE7)
          if(typeof(sForm.paging.siteFilters)!='undefined'){
            try{
              sForm.rHandler.siteFilters = Element.select(sForm.rHandler, '.site-filters')[0];
              sForm.paging.siteFilters.innerHTML = sForm.rHandler.siteFilters.innerHTML;
              sForm.rHandler.siteFilters.innerHTML = null;
            }
            catch(e){
              //e.description
              //alert(e);
            }
          }
          
          if(typeof(sForm.hiddenFields)!='undefined'){
            try{
              sForm.rHandler.hiddenFields = Element.select(sForm.rHandler, '.hidden-fields')[0];
              sForm.hiddenFields.innerHTML = sForm.rHandler.hiddenFields.innerHTML;
              sForm.rHandler.hiddenFields.innerHTML = null;
            }
            catch(e){
              //alert(e);
            }
          }
          
          if(typeof(sForm.paging.searchFilter)!='undefined'){
            try{
              sForm.rHandler.searchFilter = Element.select(sForm.rHandler, '.search-filter')[0];
              sForm.paging.searchFilter.innerHTML = sForm.rHandler.searchFilter.innerHTML;
              sForm.rHandler.searchFilter.innerHTML = null;
            }
            catch(e){
              //alert(e);
            }
          }
          if(typeof(sForm.paging.searchTools)!='undefined'){
            try{
              sForm.rHandler.searchTools = Element.select(sForm.rHandler, '.search-tools')[0];
              sForm.paging.searchTools.innerHTML = sForm.rHandler.searchTools.innerHTML;
              sForm.rHandler.searchTools.innerHTML = null;
            }
            catch(e){
              //alert(e);
            }
          }
          
          if(typeof(sForm.paging.paginationTop)!='undefined'){
            try{
              sForm.rHandler.paginationTop = Element.select(sForm.rHandler, '.pagination')[0];
              sForm.rHandler.paginationBottom = Element.select(sForm.rHandler, '.pagination')[1];
              sForm.paging.paginationTop.innerHTML = sForm.rHandler.paginationTop.innerHTML;
              sForm.paging.paginationBottom.innerHTML = sForm.rHandler.paginationBottom.innerHTML;
              sForm.rHandler.paginationTop.innerHTML = null;
              sForm.rHandler.paginationBottom.innerHTML = null;
            }
            catch(e){
              //alert(e);
            }
          }
          
          if(typeof(sForm.searchResults)!='undefined'){
            try{
              sForm.rHandler.searchResults = Element.select(sForm.rHandler, '.search-results')[0];
              sForm.searchResults.innerHTML = sForm.rHandler.searchResults.innerHTML;
              sForm.rHandler.searchResults.innerHTML = null;
            }
            catch(e){
              alert(e); // here
            }
          }
          
          if(typeof(modules.actions.print)!='undefined'){
            modules.actions.print.elem = $$('#'+SiteVars.modules.print.rootId)[0];
            modules.actions.print.load();
          }
          
          if(typeof(sForm.mFormControls)!='undefined' && !Element.hasClassName(sForm, 'multidestination')){
            try{
              sForm.mFormControls();
            }
            catch(e){
              //alert(e);
            }
          }
          
          try{
            sForm.buildSortingProps();
            sForm.buildPagingProps();
          }
          catch(e){
            //alert(e);
          }
          
          Event.fire(window, 'ajax:search-success');
        }
        
        sForm.buildSortingProps();
        sForm.buildPagingProps();
        
      }
      }catch(e){
        //console.log(e);
      }
      
      //console.log(search.hvcbMemberSearch);
      
      sForm.runReset = function(){
        //console.log('here in sForm.runReset');
        Form.getElements(sForm).each(function(field){
            switch(field.type.toLowerCase()){
              case 'select-one':
                field.selectedIndex = 0;
                break;
                
              case 'checkbox':
                field.checked = (field.name == 'searchByType' && field.value=='') ? true : false;
                break;
                
              case 'text':
                if(field.name == 'startdate'){
                  var sDate = new Date();
                  var eDate = new Date(sDate.getFullYear(), sDate.getMonth() + 4, sDate.getDate());
                  Element.select(sForm, '.input-date input')[0].value = SiteVars.modules.Vacation.month_phrases[sDate.getMonth()] + ' ' + sDate.getDate() + ', ' + sDate.getFullYear() ;
                  Element.select(sForm, '.input-date input')[1].value = SiteVars.modules.Vacation.month_phrases[eDate.getMonth()] + ' ' + eDate.getDate() + ', ' + eDate.getFullYear() ;
                }
                else if(field.name == 'enddate'){
                }
                else{
                  field.value = (field.id=='useKeywords') ? search.keywordsPhrase : '';
                }
                break;
                
              default:
                break;
            }
        });
      }
      
      sForm.setTypeFilter = function(){
        if(sForm.typeFilters[0]){
          
          var startTerm = '';
          var appendTerm = '';
          var clearTerm = false;

          sForm.typeFilters.each(function(filter){
              if(filter.checked && filter.value!=''){
                startTerm = 'AND Type:(';
                appendTerm += filter.value + ' OR ';

              }
              if(filter.checked && filter.value=='' && sForm.searchByTypeString.value != ''){
                //console.dir(filter);
                clearTerm = true;
              }
          });
          if(clearTerm == true){
            sForm.searchByTypeString.value = '';
          }
          else if(startTerm!=''){
            var subResult = appendTerm.substring(0, appendTerm.length - 3);
            sForm.searchByTypeString.value = startTerm + subResult + ')';
          }
        }
        
        //console.log(sForm.searchByTypeString.value);
        
      }
      
      try{
        if(sForm.selectIslandId.options){
        }
        else if(SiteVars.siteId == 'hvcb' && SiteVars.islandId == 'statewide' ){
          sForm.mIslandId.value = '(kauai OR oahu OR lanai OR molokai OR maui OR big-island OR statewide)' ;
        }
        else if(SiteVars.siteId == 'hvcb' && SiteVars.islandId != 'statewide'){
          sForm.mIslandId.value = '"' + SiteVars.islandId + '"';
        }
      }catch(e){
        //console.dir(e);
      }
      
      
      
      sForm.runSubmit = function(e){
        if('categoryRestriction' in sForm){
           sForm.categoryRestriction.value = '';
        }
        if('Category' in sForm){
          if(sForm.Category.value == 'Accommodations' || sForm.Category.value == 'Activities'){
            sForm.SellerSplit.value = 'SellerProvider,';
            if(sForm.membersSortField.options[sForm.membersSortField.selectedIndex].value.indexOf('SellerProvider,') ==-1){
              sForm.membersSortField.options[sForm.membersSortField.selectedIndex].value = 'SellerProvider,' + sForm.membersSortField.options[sForm.membersSortField.selectedIndex].value;
            }
            //alert(sForm.membersSortField.value);
          }
          else{
            if('SellerSplit' in sForm ){
              sForm.SellerSplit.value = '';
            }
            if('sellerRestriction' in sForm ){
              sForm.sellerRestriction.value = '';
            }
          }
        }
        if('ajaxCalls' in sForm){
           sForm.ajaxCalls.url = sForm.action;
        }
        
        if(sForm.id == 'sfsimple' && e!='load'){
          // media specific
          return search.returnAction(sForm, SiteVars.modules.Search.mode);
        }
        else if(sForm.id == 'sfresults' && sForm.isNewsSearch){
          return search.returnAction(sForm, SiteVars.modules.Search.mode);
        }
        else{
          
          //Run some specific validation and data checking
          if (('selectIslandId' in sForm) && (typeof sForm.selectIslandId.options != 'undefined')) {
            var useIslandId = sForm.selectIslandId.options[sForm.selectIslandId.options.selectedIndex].className;
            if(sForm.selectIslandId.options[sForm.selectIslandId.options.selectedIndex].value == 'all'){
              sForm.islandId.value = 'statewide';
            }
            else{
              sForm.islandId.value = useIslandId;
            }
          }
          
          search.setMId(sForm.selectIslandId);
          
          
          if(sForm.useKeywords){
            if(sForm.useKeywords.value != search.keywordsPhrase){
              var regexVal = new String(sForm.useKeywords.value);
              regexVal = regexVal.replace(search.regExTerm, '');
              sForm.keywords.value = ' AND ( Title:"' + regexVal + '" OR Keywords:"' + regexVal +'" OR Summary:"' + regexVal + '" OR "' + regexVal + '"  )';
            }
            else{
              sForm.useKeywords.value = search.keywordsPhrase;
              sForm.keywords.value = '';
            }
          }
          
          if('startdate' in sForm){
            var sd = jQuery.trim(sForm.startdate.value);
            var ed = jQuery.trim(sForm.enddate.value);
            
            res = search.validateEventDates(sForm, sd, ed);
            var emsg = 'Your search dates are invalid'; 
              if (res == false) {
                alert(emsg);
                Event.stop(e);
                return false;
              }
              else{
                search.checkDates(sForm);
              }
                
          }
          
           
            
            
          //Only stop the event if we can make an ajax call, otherwise let the form submit naturally
          if(Element.hasClassName(sForm, 'mediasitesearchform')){
            var filter = false;
            var filterset = new Array();
            
            sForm.setTypeFilter();
            var st1 = '';
            var st2 = '';
            var st3 = '';
            var st4 = '';
            var st5 = '';
         
            
            var fs = $('filterSort').value;
            
            if (fs == 'press') {
              st1 = '^10000';
            } else if (fs == 'media') {
              st2 = '^10000'; 
            } else if (fs == 'hvcb') {
              st3 = '^10000' 
            } else if (fs == 'blog') {
              st4 = '^10000'; 
            } else if (fs == 'event') {
              st5 = '^10000'; 
            }
            
            // why is events not showing up?????
            
            var sf1 = '((Type:HVCBMediaArticle OR Type:StoryIdea) AND _RepositoryPath:/sitebuilder/content/groups/MediaNewsArticles)' + st1; // press group
            //var sf2 = '(siteId:media AND _RepositoryPath:(/xml_content/public/media  OR /sitebuilder/content OR (/resources/public/media AND /brochures)))' + st2; // media group
            var sf2 = '((siteId:media AND _RepositoryPath:(/xml_content/public/media  OR /sitebuilder/content OR (/resources/public/media AND /brochures))) OR (Type:Blog AND _RepositoryPath:/xml_content/public/media/blog))' + st2; // media group
            
            //var sf3 = '(siteId:hvcb  AND (_RepositoryPath:(/sitebuilder/content))' + st3; // gohawaii.com group
            var sf3 = '((siteId:hvcb  AND _RepositoryPath:(/sitebuilder/content)) OR (_RepositoryPath:/xml_content/public/events AND Type:Event))' + st3; // gohawaii.com
            var sf4 = '(Type:Blog AND _RepositoryPath:/xml_content/public/media/blog)' + st4; // blog group
            var sf5 = '(Type:Event AND _RepositoryPath:/xml_content/public/events)' + st5; // event group
            
            
            // if using a filter, then we only use one of the groups above,
            // otherwise we use sfall
            
            var sfall = '(' + sf1 + ' OR ' + sf2 + ' OR ' + sf3 + ' OR ' + sf4 + ' OR ' + sf5 + ')';
            
            //alert('SF3 ' + st3);
            
            
            
            if (sForm.filterPress.value == 'true') {
               filterset.push(sf1);
               filter = true;
            }
            
            if (sForm.filterMedia.value == 'true') {
               filterset.push(sf2);
               filter = true;
            }
            
            if (sForm.filterHVCB.value == 'true') {
               filterset.push(sf3);
               filter = true;
            }
            
            if (filter == true) {
              sForm.filterSearch.value = filterset.join(' OR ');  
            } else {
              sForm.filterSearch.value = sfall;
            }

            
            
            
            /* ok now setup the island */
            
            if ($('selectIslandId').value != '' && $('selectIslandId').value != 'statewide') {
              $('filterIsland').value = ' AND (islandId:' + $('selectIslandId').value + ')'
            } else {
              $('filterIsland').value = ' AND (islandId:("kauai" OR "oahu" OR "lanai" OR "molokai" OR "maui" OR "big-island" OR "statewide"))'
            }
            
            if(sForm.selectIslandId.value == ''){
              sForm.selectIslandId.value = 'statewide';
            }
            
            if(sForm.selectIslandId.value != SiteVars.islandId){
              sForm.repositoryPath.value = '';
              sForm.filterCriteria.value = '';
              sForm.typeRestrictions.value = '';
              sForm.filterSearch.value = ''
              sForm.ajaxCalls.params = Form.serialize(sForm);
              
              var unEscp = unescape(sForm.ajaxCalls.params)
              unEscp.replace(/\s{2,}|\n|\t|\r/gi," ");
              var url = SiteVars.path_to_top + '/' + sForm.mIslandId.value + '/search?' + unEscp;
              //alert(unEscp);
              document.location.replace(url);
            }
            else{
              sForm.ajaxCalls.params = Form.serialize(sForm);
              modules.sendAsync(sForm.ajaxCalls);
              //alert(new Date());
              //location.hash = new Date();
            }
            Event.stop(e);
            
          } 
          else  if(Element.hasClassName(sForm, 'multidestination')){
            sForm.setTypeFilter();
            sForm.ajaxCalls.params = Form.serialize(sForm);
            
            modules.sendAsync(sForm.ajaxCalls);
            Event.stop(e);
          }
          else if(Element.hasClassName(sForm, 'featured-events')){
            //do nothing, pass the event naturally
          }
          else if(sForm.islandId.value == SiteVars.islandId){
            sForm.ajaxCalls.params = Form.serialize(sForm);
            modules.sendAsync(sForm.ajaxCalls);
            if(e!='load'){
              Event.stop(e);
            }
          }
        }
      }
      
      sForm.updateMediaResultsGraphics = function(){
        // need to worry about: filterPress, filterMedia, filterHVCB, selectIslandId, filterSort
        if(sForm.filterPress.value == 'true'){
          var cbDiv = Element.up(sForm.filterPress, '.checkbox-option');
          Element.addClassName(cbDiv,'selected');
        }
        if(sForm.filterMedia.value == 'true'){
          var cbDiv = Element.up(sForm.filterMedia, '.checkbox-option');
          Element.addClassName(cbDiv,'selected');
        }
        if(sForm.filterHVCB.value == 'true'){
          var cbDiv = Element.up(sForm.filterHVCB, '.checkbox-option');
          Element.addClassName(cbDiv,'selected');
        }
        if(sForm.selectIslandId.value != ''){
          var selectParent = Element.up(sForm.selectIslandId)
          var selected = Element.select(selectParent, 'strong')[0];
          var selectedValue = Element.select(selectParent, 'ul li a[class='+sForm.selectIslandId.value+']')[0];
          
          selected.innerHTML = selectedValue.innerHTML;
        }
        if(sForm.filterSort.value != ''){
          var selectParent = Element.up(sForm.filterSort)
          var selected = Element.select(selectParent, 'strong')[0];
          var selectedValue = Element.select(selectParent, 'ul li a[class='+sForm.filterSort.value+']')[0];
          
          selected.innerHTML = selectedValue.innerHTML;
        }
      }
      
      Event.observe(sForm, 'submit', function(e){
          sForm.runSubmit(e);
      });
      
      
      if(Element.hasClassName(sForm, 'featuredform') || Element.hasClassName(sForm, 'featured-events')){
      }
      else if(sForm.id != 'sfsimple'){ //changing the search results to always load via ajax, even on page 1

        //Need to create an iframe to handle the history of browsing through a set of search results
        /* Element.insert($$('body')[0], '<div id="ajax-history-'+sForm.id+'" style="display:none;" />');
        sForm.ajaxHistory = $('ajax-history-'+sForm.id);
        
        Element.insert(sForm.ajaxHistory, '<iframe id="ajax-iframe-'+sForm.id+'" name="ajax-iframe-'+sForm.id+'" style="display:none;"/>')
        Element.insert(sForm.ajaxHistory, '<form id="ajax-form-'+sForm.id+'" style="display:none;" method="GET" target="ajax-iframe-'+sForm.id+'"><input type="hidden" name="params" /></form>')
        sForm.ajaxHistoryIframe = $('ajax-iframe-'+sForm.id);
        sForm.ajaxHistoryForm = $('ajax-form-'+sForm.id);
        sForm.ajaxHistoryIframe.src = SiteVars.path_to_top +'/ajax-history-cache'
        
        Event.observe(sForm.ajaxHistoryForm, 'submit', function(e){
            e.stopPropogation = true;
        });
        
        Event.observe(sForm.ajaxHistoryIframe, 'load', function(e){
            if(sForm.ajaxHistoryIframe.contentWindow.location.search != ''){
            console.log(e);
            console.log(sForm.ajaxHistory.savedSearch);
            console.log(sForm.formState.params);
              if(sForm.ajaxHistory.savedSearch != sForm.formState.params){
                sForm.readState();
                unescape(sForm.ajaxCalls.params);
                modules.sendAsync(sForm.ajaxCalls);
              }
            }
        }.bind(sForm)); */
        
        if(location.hash!=''){
          sForm.readState();
          if(Element.hasClassName(sForm, 'sfmediacontent')){
            sForm.updateMediaResultsGraphics();
            unescape(sForm.ajaxCalls.params);
          }
        }
        else{
          sForm.ajaxCalls.params = Form.serialize(sForm);
          if(Element.hasClassName(sForm, 'sfmediacontent')){
            sForm.ajaxCalls.url = SiteVars.path_to_top +'/media/async-content/search'
          }
          /* else if(Element.hasClassName(sForm, 'featuredform')){
            sForm.ajaxCalls.url = SiteVars.path_to_top + '/featuredmember/ajaxpage';
          } */
          else if(sForm.id != 'sfsimple'){
            sForm.ajaxCalls.url = SiteVars.path_to_top + '/directory/search-paged';
          }
        }
        //console.dir(sForm.ajaxCalls)
        //console.log(sForm.ajaxCalls.params)
        if(SiteVars.siteId == 'media'){ //this test will need to eventually be removed
          modules.sendAsync(sForm.ajaxCalls);
        }
      }
      
    });
    
    
    search.hvcbMemberSearch.each(function(mForm){
        mForm.mHandler = true;
        
        mForm.mFormControls = function(){
          mForm.selects = $A(mForm.getElementsByTagName('select')).map(Element.extend);
          mForm.switchset = Element.select(mForm, '.switchset');
          mForm.activeNum = 0;
          
          swNum = 0;
          mForm.switchset.each(function(sw){
              
              sw.isActive = false;
              sw.setNum = swNum;
              sw.baseOptions = Element.select(sw, 'option');
              sw.allOptions = Element.select(sw, 'option');
              
              Event.observe(sw, 'change', function(e){
                  sw.isActive = true;
                  mForm.runSwitch();
              });
              
              swNum++;
          });
          
          mForm.runSwitch();
        }
        
        mForm.runSwitch = function(){
          
          mForm.switchset.each(function(sw){
              if(sw.isActive){
                mForm.activeNum = sw.setNum;
                sw.isActive = false;
              }
              
              sw.currentVal = Form.Element.getValue(sw);
              
              if(sw.setNum > mForm.activeNum){
                sw.count = 0;
                sw.allOptions = Element.select(sw, 'option');
                sw.allOptions.each(function(opt){
                    if(sw.count > 0){
                      opt.remove();
                    }
                    sw.count++;
                });
                
                sw.allClasses = $A(sw.className.split(' '));
                
                sw.compareClass = '';
                sw.allClasses.each(function(cName){
                    if(cName.indexOf('switchable-')!=-1){
                      var tempName = cName.substring(11, cName.length);
                      var compareAgainst = Element.select(mForm, '.key-'+tempName)[0];
                      
                      sw.compareClass += Form.Element.getValue(compareAgainst);
                      
                      sw.baseOptions.each(function(opt){
                            
                            if(Element.hasClassName(opt, sw.compareClass)){
                              Element.insert(sw, opt);
                              if(opt.value == sw.currentVal){
                                opt.setAttribute('selected','selected');
                                //opt.focus();
                              }
                            }
                          
                      });
                    }
                    
                });
                
              }
          });
        }
        
        mForm.mFormControls();
        
        /* Event.observe(mForm, 'submit', function(e){
        }); */
    });
    
    
    
  } //}}}
  
  //{{{ search.updateFilters = function(tf)
  search.updateFilters = function(tf) {
    var filter = false;
    var filterset = new Array();
    var sf1 = '((Type:HVCBMediaArticle OR Type:StoryIdea) AND _RepositoryPath:/sitebuilder/content/groups/MediaNewsArticles)'; // press group
    var sf2 = '((siteId:media AND _RepositoryPath:(/xml_content/public/media  OR /sitebuilder/content OR (/resources/public/media AND /brochures))) OR (Type:Blog AND _RepositoryPath:/xml_content/public/media/blog))'; // media group
    
    var sf3 = '((siteId:hvcb  AND _RepositoryPath:(/sitebuilder/content)) OR (_RepositoryPath:/xml_content/public/events AND Type:Event))'; // gohawaii.com
    
    var sf4 = '(Type:Blog AND _RepositoryPath:/xml_content/public/media/blog)'; // blog
    var sf5 = '(Type:Event AND _RepositoryPath:/xml_content/public/events)';      // events
    var sfall = '(' + sf1 + ' OR ' + sf2 + ' OR ' + sf3 + ' OR ' + sf4 + ' OR ' + sf5 + ')';
    
    if (tf.filterPress.value == 'true') {
      filterset.push(sf1);
      filter = true;
    }
    
    if (tf.filterMedia.value == 'true') {
      filterset.push(sf2);
      filter = true; 
    }
    
    if (tf.filterHVCB.value == 'true') {
      filterset.push(sf3);
      filter = true; 
    }
    
    
    
    if (filter == true) {
      return('(' + filterset.join(' OR ') + ')');
    } 
    
    
    return(sfall);
  } //}}}
  
  //{{{ search.returnAction = function(tf,jsSearchType)
  search.returnAction = function(tf,jsSearchType) { 
    try{
      if (jsSearchType != 'newsarticle' && tf.searchLoc && tf.searchLoc[1].checked) {
        if (tf.searchText.value != '') {
          window.open('http://www.google.ca/search?q=' + tf.searchText.value,'googlesearch');
        }
        return false;
      }
    }
    catch(e){}
    var searchTerm = '';
    if (tf.searchText.value != '') { 
      var terms = tf.searchText.value.split(' ');
      for (var i=0; i< terms.length; i++) {
        var prevTerm = "";
        if (i>0) prevTerm = terms[i-1];
        searchTerm += addSearchTerm(terms[i],false,false,true,prevTerm);
      }
    }
    tf.keywords.value = tf.searchText.value;      
    if (jsSearchType != 'simple') {
      if (tf.andWords && tf.andWords.value != '') {
        //alert("andwords"+tf.andWords.value);
        searchTerm += ' AND '; 
        if (tf.keywords.value != '') { tf.keywords.value += ' AND '; }
        searchTerm += '(';
        var terms = tf.andWords.value.split(' ');
        for (var i=0; i< terms.length; i++) {
          searchTerm += addSearchTerm(terms[i],false,false);
          tf.keywords.value += terms[i];
          if (i < terms.length-1) {
            searchTerm += ' AND ';
            tf.keywords.value += ' AND ';
          }
         // alert("searchTerm"+searchTerm);
        }
        searchTerm += ')';
      }
      if (tf.exactWords && tf.exactWords.value != '') {
        searchTerm += ' AND ';
        if (tf.keywords.value != '') { tf.keywords.value += ' AND '; }
        searchTerm += addSearchTerm(tf.exactWords.value, true,false);
        var terms = tf.exactWords.value.split(' ');
        for (var i=0; i< terms.length; i++) {
          tf.keywords.value += terms[i];
          if (i < terms.length-1) {
            tf.keywords.value += ' AND ';
          }
        }
      }
       if (tf.orWords && tf.orWords.value != '') {
        searchTerm += ' AND ';
        if (tf.keywords.value != '') { tf.keywords.value += ' AND '; }
        searchTerm += '(';
        var terms = tf.orWords.value.split(' ');
        for (var i=0; i< terms.length; i++) {
          searchTerm += addSearchTerm(terms[i],false,false);
          tf.keywords.value += terms[i];
          if (i < terms.length-1) {
            searchTerm += ' OR ';
            tf.keywords.value += ' OR ';
          }
        }
        searchTerm += ')';
       }
       if (tf.notWords && tf.notWords.value != '') {
        var terms = tf.notWords.value.split(' ');
        for (var i=0; i< terms.length; i++) {
          searchTerm += addSearchTerm(terms[i],false,true);
          tf.keywords.value += 'NOT ' + terms[i];
        }
        }
      }
      if (jsSearchType == 'advanced') {
        //alert("Getting Advanced Options");
        
        searchTerm += getAdvancedOptions(tf);
      }
      if (jsSearchType == 'newsarticle') {
        searchTerm += getNewsArticleAdvancedSearchTerm(tf);
      }
      if (jsSearchType == 'task') {
        searchTerm += getTaskAdvancedSearchTerm(tf);
      }
      if (jsSearchType != 'simple') {
       if (tf.useDate && tf.useDate.checked) {
        searchTerm += '@between('
          + tf.dateType[tf.dateType.selectedIndex].value
          + ',' + getDate('after')
          + ',' + getDate('before') + ')';
       }
      }
      
      var extra = '';
      if (SiteVars.siteId=='media' && jsSearchType=='simple') {
        
            extra = search.updateFilters(tf);
            //alert(extra);
      }
      
      
      tf.searchTerm.value = searchTerm;// + ' OR **Keyword**Title:("'+tf.searchText.value+'") ';
      if('filterQuery' in tf){ //new for media
        tf.filterQuery.value = extra;
      }
      
      
      
      
      return true;
      //return confirm(searchTerm);
    
    
      function addSearchTerm(term,addQuot,isNot,useAnd,prevTerm) {
        regexp1 = new RegExp('"','gi');
        regexp2 = new RegExp("'",'gi');
        regexp3 = new RegExp("&", 'gi');
        regexp4 = new RegExp("<", 'gi');
        regexp5 = new RegExp(">", 'gi');
        regexp6 = new RegExp("-", 'gi');
        regexp7 = new RegExp("^", 'gi');
        regexp8 = new RegExp("~", 'gi');
        regexp9 = new RegExp("\\\\", 'gi');
        result = term.replace(regexp1,'');
        result = result.replace(regexp2,'');
        result = result.replace(regexp3,'');
        result = result.replace(regexp4,'');
        result = result.replace(regexp5,'');
        result = result.replace(regexp6,'');
        result = result.replace(regexp7,'');
        result = result.replace(regexp8,'');
        result = result.replace(regexp9,'');
        if (result == '' || result == ' ') {
          return '';
        }
        else if (result.indexOf(':') != -1) {
          return result + ' ';
        }
        else if (result == 'AND' || result == 'OR' || result == 'NOT') {
          return result + ' ';
        }
        else {
          if (addQuot) { xtra = '"'; } else { xtra = '';}
          if (isNot) {
            return  'NOT ' + xtra + result + xtra
                + ' NOT Description:' + xtra + result + xtra
                + ' NOT Use:' + xtra + result + xtra
                + ' NOT Title:' + xtra + result + xtra
                + ' ';
          }
          else {
            var joiner = "";
            if (useAnd && (prevTerm != 'AND'
                                   && prevTerm != 'OR'
                                   && prevTerm != 'NOT')) joiner = " AND ";
            return  joiner + '(' + xtra + result + xtra
                + ' OR Description:' + xtra + result + xtra
                + ' OR Use:' + xtra + result + xtra
                + ' OR Title:' + xtra + result + xtra
                + ' OR _DocumentID:' + xtra + result + xtra              
                + ') ';
          }
        }
      }
      function updateDR(sel) {
        if (sel.selectedIndex == 0) {
          dateRestriction.style.visibility = 'hidden';
          dateRestriction.style.display = 'none';
        }
        else {
          dateRestriction.style.visibility = 'visible';
          dateRestriction.style.display = '';
        }
      }
      function getDate(pref) {
        var yrF = document.getElementById(pref+'Year');
        var mnF = document.getElementById(pref+'Month');
        var dyF = document.getElementById(pref+'Day');
        return yrF[yrF.selectedIndex].value +
               mnF[mnF.selectedIndex].value +
               dyF[dyF.selectedIndex].value;
      }
      function toggleSearchOptions() {
        sopts = document.getElementById('searchOptions');
        stog = document.getElementById('sotog');
        sdiv = document.getElementById('soDiv');
        if (sdiv.style.visibility == 'hidden') {
          stog.innerText = "hide";
          sdiv.style.display = '';
          sdiv.style.visibility = 'visible';
        }
        else {
          stog.innerText = "display";
          sdiv.style.display = 'none';
          sdiv.style.visibility = 'hidden';
        }
      }
      var prevGoogle = '';
      function toggleSearchLocation(val) {
        sdiv = document.getElementById('soDiv');
        if (val == 'google') {
          prevGoogle = sdiv.style.visibility;
          sdiv.style.display = 'none';
          sdiv.style.visibility = 'hidden';
        }
        else if (prevGoogle == 'hidden') {
          sdiv.style.display = 'none';
          sdiv.style.visibility = 'hidden';
        }
        else if (prevGoogle == 'visible' || prevGoogle == '') {
          sdiv.style.display = '';
          sdiv.style.visibility = 'visible';
        }
      }
      function toggleCBField(fn,cb,dpyMode) {
        box = document.getElementById(fn);
        if (dpyMode == 'side') {
          if (cb.checked) {
            box.style.display = '';
            box.style.visibility = 'visible';
          }
          else {
            box.style.display = 'none';
            box.style.visibility = 'hidden';
          }
        }
      }
      var radioBoxes = new Array();
      function registerRadioBox(name) {
        radioBoxes[radioBoxes.length] = name;
      }
      function toggleRadioBox(name, dpyMode, sf) {
        var box;
        var sfid = document.getElementById(sf);
        if (name == '') {
          box = null;
          sfid.useType[0].checked = true;
        } else {
          box = document.getElementById(name + 'Box');
          for (i=1; i<= radioBoxes.length; i++) {
            if (sfid.useType[i].value == name) {
              sfid.useType[i].checked = true;
            }
          }
        }
        if (dpyMode == 'side') {
          for (i=0; i < radioBoxes.length; i++) {
            tmpbox = document.getElementById(radioBoxes[i] + 'Box');
            if (tmpbox != box) {
              tmpbox.style.display = 'none';
              tmpbox.style.visibility = 'hidden';
            }
          }
          if (box != null) {
            box.style.display = '';
            box.style.visibility = 'visible';
          }
        }
      }
      function addList(name, field) {
        var selectedCount = 0;
        var len = field.options.length;
        var returnValue="";
    
        for (i = 0; i < len; i++)
          if (field.options[i].selected &&
              field.options[i].value != '')
            selectedCount++;
    
        if (selectedCount > 0) {
          var returnValue = ' AND (';
          selectedCount = 0;
          for (i = 0; i < len; i++) {
            if(field.options[i].selected) {
              if( selectedCount != 0 ) returnValue += ' OR ';
              returnValue += name + ':"'+ field.options[i].value + '" ';
              selectedCount++;
            }
          }
          returnValue += ')';
        }
        return returnValue;
      }
      function addCheckBox(name, frm, pfx){
      var selectedCount = 0;
      var len = frm.elements.length;
      var returnValue="";
  
      for (i = 0; i < len; i++){
        var isGroup = (pfx) ? frm.elements[i].name.indexOf(pfx):0;
        if (isGroup != -1 && frm.elements[i].checked){
          selectedCount++;
        }
      }
  
      if (selectedCount > 0) {
        var returnValue = ' AND (';
        selectedCount = 0;
        for (i = 0; i < len; i++) {
          if(frm.elements[i].checked) {
            if( selectedCount != 0 ) returnValue += ' OR ';
            returnValue += name + ':"'+ frm.elements[i].value + '" ';
            selectedCount++;
          }
        }
        returnValue += ')';
      }
      
      
      
      return returnValue;
    }
  } //}}}
  
  //{{{ search.getMultiValueCheckbox = function(element)
  search.getMultiValueCheckbox = function(form){
    var f = form;
    var result = "";
    
    var fCat = Element.select(f,'input[name="Category"]')[0];
    var oTypes = ('omniTypes' in f) ? f.omniTypes : false;
    //console.log(oTypes=='');
    for (var i=0; i<f.elements.length; i++) {
      if (f.elements[i].checked) {
        var parent = Element.up(f.elements[i], 'div.field');
        if(parent.style.display != 'none'){
          result += '"' + fCat.value + '>' + f.elements[i].value + '" OR ' ;
          if(oTypes){
            oTypes.value += f.elements[i].value + ',';
          }
        }
      }
    }
    if(oTypes.value == '' || oTypes.value == ',' || oTypes.value == 'All Types,'){
      oTypes.value = 'All Types'
    }
    //console.log(f.omniTypes.value);
    
    var subResult = result.substring(0, result.length - 3);
    if(result!='' && result!=' ' ){
      Element.select(f,'input[name="SubCategory"]')[0].value = '( ' + subResult + ')';
    }
    else{
      Element.select(f,'input[name="SubCategory"]')[0].value = '';//f.select('input[name="Category"]')[0].value+'>';
    }
    
    //console.log(subResult);
    
    /* Also need to check categories */
    if(fCat.value == 'all'){
      //console.log('all');
      fCat.value = '';
      //console.log(Element.select(f,'input[name="Category"]')[0]);
    }
    
    /* Always need to run a check to make sure the form is submiting the Seller/Provider logic split correctly */
    /* Split should only be applied to Accommodations > Any Type and Activities > Any Type */
    /* Syntax for value should be SellerProvider, (will be prefixed to other sort fields when applicable) */
    if('SellerSplit' in f){
      if(fCat.value == 'Accommodations' || fCat.value == 'Activities'){
        f.SellerSplit.value = 'SellerProvider,';
      }
      else{
        f.SellerSplit.value = '';
        if('sellerRestriction' in f ){
          f.sellerRestriction.value = '';
        }
      }
    }
    
    
    //return result;
  } //}}}
  
  //{{{ search.setMId = function(element)
  search.setMId = function(element, clsName){
    //console.dir(element);
    var f = (element.jquery) ? element[0].form : element.form;
    var val = (element.jquery) ? element[0].value : Form.Element.getValue(element);
    var useClass = (clsName) ? clsName : '.mIslandId';
    var mIsland = Element.select(f,useClass)[0];
    var island = Element.select(f,'.islandId')[0];
    
    //console.log(val);
    //console.log(mIsland);
    
    if(val == 'all'){
      try{
        Form.Element.setValue(mIsland, '(kauai OR oahu OR lanai OR molokai OR maui OR big-island OR statewide)');
      }
      catch(e){
        mIsland.value = '(kauai OR oahu OR lanai OR molokai OR maui OR big-island OR statewide)';
      }
      island.value = 'statewide';
    }
    else{
      mIsland.value = val;
      island.value = val;
    }
  } //}}}
  
  //{{{ search.runTypeCheck = function(elem)
  search.runTypeCheck = function(elem){
    var type = $(elem[0]);
    var typeUl = Element.ancestors(type)[0];
    var allTypes = Element.select(typeUl, 'li');
    if(Element.hasClassName(type, 'all')){
      allTypes.shift();
      allTypes.each(function(item){
          if(Element.hasClassName(item, 'selected')){
            Element.removeClassName(item, 'selected');
            Element.select(item, 'input')[0].checked = false;
          }
      });
    }
    else if(Element.hasClassName(allTypes[0], 'selected')){
      Element.removeClassName(allTypes[0], 'selected');
      Element.select(allTypes[0], 'input')[0].checked = false;
    }
    type = null;
    typeUl = null;
    alltypes = null;
  }
   //}}}
  
  //{{{ search.validateEventDates = function(form, sd, ed) 
  search.validateEventDates = function(form, sd, ed) {
    var sdate = new Date();
    var edate = new Date();
    
    sdate.setTime(Date.parse(sd));
    edate.setTime(Date.parse(ed));
    
    
    var smonth = (sdate.getMonth() + 1 < 10) ? '0' + (sdate.getMonth() + 1) : sdate.getMonth() + 1;
    var emonth = (edate.getMonth() + 1 < 10) ? '0' + (edate.getMonth() + 1) : edate.getMonth() + 1;
    var sday = (sdate.getDate() + 1 < 10) ? '0' + sdate.getDate() : sdate.getDate();
    var eday = (edate.getDate() + 1 < 10) ? '0' + edate.getDate() : edate.getDate();
    
    
    var sdatestr = sdate.getFullYear() + '' + smonth + '' + sday;
    var edatestr = edate.getFullYear() + '' + emonth + '' + eday;
    
    
    //var de = Date.parse(ed);
    
    if ((sd == '' && ed == '')) {
      return false;
    }
    
    if (ed != '') {
      if ( sdatestr > edatestr ) {
        return false;
      }
    }
    return true;
    
    
  } //}}}
  
  //{{{ search.checkDates = function(form)
  search.checkDates = function(form){
    if(form.startdate){
      
      var sDateString, eDateString;
      var fullDateString = '';
      
      
      
      if(form.startdate.value!=''){
        var sDate = new Date(form.startdate.value);
        var sMonthString = (sDate.getMonth() < 9) ? '0' + String(sDate.getMonth()+1) : String(sDate.getMonth()+1);
        var sDayString = (sDate.getDate() < 10) ? '0' + String(sDate.getDate()) : String(sDate.getDate());
        sDateString = String(sDate.getFullYear()) + sMonthString + sDayString + '0000.00';
        form.sDateString.value = sDateString;
      }
      if(form.enddate.value!=''){
        var eDate = new Date(form.enddate.value);
        var eMonthString = (eDate.getMonth() < 9) ? '0' + String(eDate.getMonth()+1) : String(eDate.getMonth()+1);
        var eDayString = (eDate.getDate() < 10) ? '0' + String(eDate.getDate()) : String(eDate.getDate());
        var closeString = (form.startdate.value == form.enddate.value) ? '2359.59' : '0000.00' ;
        eDateString = String(eDate.getFullYear()) + eMonthString + eDayString + closeString;
        form.eDateString.value = eDateString;
      }
      //console.log(form.sDateString.value)
      //console.log(form.eDateString.value)
    }
  } //}}}
  
  //{{{ search.loadVacationSearch = function()
  search.loadVacationSearch = function(){
    search.vacationDirectory.each(function(form){
      Event.observe(form, 'submit', function(e){
          search.getMultiValueCheckbox(form);
          if('startdate' in form){
            var sd = jQuery.trim(form.startdate.value);
            var ed = jQuery.trim(form.enddate.value);
            res = search.validateEventDates(form, sd, ed);
            var emsg = 'Your search dates are invalid'; 
            if (res == false) {
              alert(emsg);
              Event.stop(e);
            }
            else{
              search.checkDates(form);
            }
          }
          //Event.stop(e);
      });
    });
  } //}}}
  
  //{{{ search.setOmniture = function(form)
  search.setOmniture = function(form){
    //Need to set omniture data here
    
    if('s' in window){
      
      var s=s_gi(SiteVars.omniture_id);
      
      //don't always want to track these ones
      var eVar11Track = (form.searchDisplayType.value == 'activities') ? 'eVar11,' : '' ;
      var eVar12Track = (form.searchDisplayType.value == 'events') ? 'eVar12,' : '' ;
      s.linkTrackVars='eVar8,eVar9,eVar10,' +eVar11Track+ '' +eVar12Track+ 'events';
      s.linkTrackEvents='event3';
      
      //console.dir(s);
      s.eVar8  = form.searchDisplayType.value; //VC search category (activities | accommodations | events)
      s.eVar9  = form.islandId.value //Island Name (not islandId? same as s.channel?)
      s.eVar10 = (form.searchDisplayType.value == 'activities') ? form.Category.value : form.omniTypes.value ; //Category for Activities, Type for Accommodations and Events
      s.eVar11 = (form.searchDisplayType.value == 'activities') ? form.omniTypes.value: '' ; //Type (only for Activities)
      
      if(form.searchDisplayType.value == 'events'){
        var oDate = new Date(Element.select(form, '.input-date input')[0].value);
        var oDateString = SiteVars.modules.Vacation.month_phrases[oDate.getMonth()] + ', ' + oDate.getFullYear();
        s.eVar12 = oDateString; //Month, Year (note only for Events)
      }
      else{
        s.eVar12 = ''
      }
      //s.events+=",event3" //event3 means VC form submission 
      s.events='event3';

      s.tl(form,'o','Vacation Directory'); 
      
      /* if (window.console) console.log('========== OMNITURE VC Tracking ============');
      if (window.console) console.log('s.linkTrackVars = %s',s.linkTrackVars);
      if (window.console) console.log('s.events = %s',s.events);
      if (window.console) console.log('s.eVar8 = %s',s.eVar8);
      if (window.console) console.log('s.eVar9 = %s',s.eVar9);
      if (window.console) console.log('s.eVar10 = %s',s.eVar10);
      if (window.console) console.log('s.eVar11 = %s',s.eVar11);
      if (window.console) console.log('s.eVar12 = %s',s.eVar12);
        
      alert('stop');  */
    }
    
    //console.dir(s);
    
  } //}}}
  
  
  if(search.form[0] || search.hvcbMemberSearch[0]){
    search.loadSearch();
  }
  
  
}
  
  
//{{{ loadAsyncDirectory = function()
var loadAsyncDirectory = function(){
  //alert("called loadAsyncDirectory");
  modules.loadActions.prototype.search.vacationDirectory = $$('form.vacationdirectory');
  //alert("loading modules.protoype");
  modules.loadActions.prototype.search.vacationDirectory.each(function(form){
    Event.observe(form, 'submit', function(e){
        modules.actions.search.getMultiValueCheckbox(form);
        if('startdate' in form){
          var sd = jQuery.trim(form.startdate.value);
          var ed = jQuery.trim(form.enddate.value);
          res = search.validateEventDates(form, sd, ed);
          var emsg = 'Your search dates are invalid'; 
          if (res == false) {
            alert(emsg);
            Event.stop(e);
          }
          else{
            modules.actions.search.checkDates(form);
          }
        }
        
        search.setOmniture(form);
        //Event.stop(e);
    });
  });
} //}}}


/*
  MEDIA EVENTS FORM... 
 */
//{{{ loadFeaturedEvents = function()
var loadFeaturedEvents = function(){
  
  
  
  var self = this;
  var keywordPhrase = SiteVars.modules.Search.keywordsPhrase;
  var misland = '';
  var mfilter = '';
  var island_change = ''; // if populated, then we need to switch to that island

  
  initPaging = function() {
    // now update paging
    
    $$('.paging a').each(function(link) {
        self.updatePaging(link);
    }); 
  }
  
  initReset = function() {
    var reset = $$('.image-reset')[0];
    var sForm = $$('.featured-events')[0];

    
    
    sForm.runReset = function(){
      island_change = 'statewide'; // defaults to all
      
      Form.getElements(sForm).each(function(field){
          switch(field.type.toLowerCase()){
            case 'select-one':
              field.selectedIndex = 0;
              break;
              
            case 'checkbox':
              field.checked = (field.name == 'searchByType' && field.value=='') ? true : false;
              break;
              
            case 'text':
              if(field.name == 'startdate'){
                var sDate = new Date();
                var eDate = new Date(sDate.getFullYear(), sDate.getMonth() + 4, sDate.getDate());
                Element.select(sForm, '.input-date input')[0].value = SiteVars.modules.Vacation.month_phrases_short[sDate.getMonth()] + ' ' + sDate.getDate() + ', ' + sDate.getFullYear() ;
                Element.select(sForm, '.input-date input')[1].value = SiteVars.modules.Vacation.month_phrases_short[eDate.getMonth()] + ' ' + eDate.getDate() + ', ' + eDate.getFullYear() ;
              }
              else if(field.name == 'enddate'){
              }
              else{
                field.value = (field.id=='useKeywords') ? search.keywordsPhrase : '';
              }
              break;
              
            default:
              break;
          }
          

      });
    }    
    
    if(reset){
      reset.stopObserving('click');
      Event.observe(reset, 'click', function(e){
          sForm.runReset();
          Event.stop(e);
      });
    }   
  }
  
  changeIsland = function() {
    var mForm = $$('.featured-events')[0];
    
    Event.observe(mForm.selectIslandId, 'change', function() {
       //self.island_change = island
       var island = mForm.selectIslandId.options[mForm.selectIslandId.selectedIndex].value;
       island_change = island;
       
       
    });
    
    
  }
  
  updatePaging = function(link) {
    
    var form = $$('#featured form')[0];
    
    var furl = SiteVars.path_to_top + '/featured-island-events/search';
   
    if (form.useKeywords.value == SiteVars.modules.Search.defaultValue ||
        form.useKeywords.value == keywordPhrase) {
    
       form.useKeywords.value = '';
    }
    
    /* todo */
    
    
    
    Event.observe(link, 'click', function(e) {
       
       var mForm = $$('.featured-events')[0];
       var temp_misland = mForm.selectIslandId.options[mForm.selectIslandId.selectedIndex].className;
       var temp_mfilter = mForm.SubCategory.options[mForm.SubCategory.selectedIndex].value;
       
         
        //link.rel
        var elmNum = $$('.pageNum')[0];
        
        elmNum.value = link.rel;
        
        /*
        
        if (misland == '' || misland == 'all') {
          var regexVal = new String($('useKeywords').value);
          regexVal = regexVal.replace(search.regExTerm, '');
          
              
          $('resultsMIslandId').value = '("kauai" OR "oahu" OR "molokai" OR "lanai" OR "maui" OR "big-island")'
          $('resultsKeywords').value = ' AND ( Title:"' + regexVal + '" OR Keywords:"' + regexVal +'" OR Summary:"' + regexVal + '" OR "' + regexVal + '"  )';
        }
        */
        if (mForm.useKeywords.value == SiteVars.modules.Search.defaultValue ||
            mForm.useKeywords.value == keywordPhrase) {
           mForm.useKeywords.value = '';
        }

        
        if (mForm.useKeywords.value != keywordPhrase || mForm.useKeywords.value != '' ) {
            
            
           var regexVal = new String(mForm.useKeywords.value);
           regexVal = regexVal.replace(search.regExTerm, '');
          
              
           
           form.keywords.value = ' AND ( Title:"' + regexVal + '" OR Keywords:"' + regexVal +'" OR Summary:"' + regexVal + '" OR "' + regexVal + '"  )';
        } 
        
        
        
        if (temp_misland == '' || temp_misland == 'all') {
            form.mIslandId.value = '("kauai" OR "oahu" OR "molokai" OR "lanai" OR "maui" OR "big-island")';
            
        } else {
          form.mIslandId.value = temp_misland; 
        }
                
        
        
        var fparams = Form.serialize(form);  
         
       
         
         var ajaxCalls = {
           url:furl,
           params:fparams,
           evalScripts:true,
           onComplete:function(r) {
                
               var elm = new Element('div');
               elm.innerHTML = r.responseText;
               
               var html = $(elm).select('.MainContent')[0].innerHTML;

               $('featured').innerHTML = html;
               self.initReset();
               
               
               var myScripts = html.extractScripts();
               var myReturnedValues = myScripts.map(function(script) {
                  return eval(script);
               });
               
               // now update paging
               $$('.paging a').each(function(link) {
                  self.updatePaging(link);
               });
               
               
               
               var mForm = $$('.featured-events')[0];
           
               self.updateAjaxForm(mForm, temp_misland, temp_mfilter); 
               
               form.useKeywords.value = keywordPhrase;
           }
         }
         
         modules.sendAsync(ajaxCalls);        
        
        
    });
  }
  
  updateAjaxForm = function(form, misland, mfilter) {
      
       var mForm = $$('.featured-events')[0];
       //var misland = mForm.selectIslandId.options[form.selectIslandId.selectedIndex].className;
       //var mfilter = mForm.SubCategory.options[form.SubCategory.selectedIndex].value;
   
       //misland = form.mIslandId.value;
       //alert('island: ' + misland);
       
       //mfilter seems empty
                
                //mForm.mIslandId.value = misland;
                mForm.mHandler = true;
                
                if (mForm.useKeywords.value == '') {
                 mForm.useKeywords.value = keywordPhrase; 
                }
                
                
               
                var options = Element.select(mForm.selectIslandId, 'option');
                options.each(function(opt) {
                    if (Element.hasClassName(opt, misland)) {
                      
                      opt.setAttribute('selected', 'selected'); 
                    }
                });
                //mfilter
                var options = Element.select(mForm.SubCategory, 'option.' + misland);
                options.each(function(opt) {
                    if (opt.value ==  mfilter) {
                      opt.setAttribute('selected', 'selected'); 
                    }
                });
                
                mForm.mFormControls = function(){
                  
                  
                  mForm.selects = $A(mForm.getElementsByTagName('select')).map(Element.extend);
                  mForm.switchset = Element.select(mForm, '.switchset');
                  mForm.activeNum = 0;
                  
                  
                  
                  swNum = 0;
                  mForm.switchset.each(function(sw){
                      
                      
                      
                      sw.isActive = false;
                      sw.setNum = swNum;
                      sw.baseOptions = Element.select(sw, 'option');
                      sw.allOptions = Element.select(sw, 'option');
                      
                      Event.observe(sw, 'change', function(e){
                          sw.isActive = true;
                          mForm.runSwitch();
                      });
                      
                      swNum++;
                  });

                  mForm.runSwitch();
                  
                }
                
                mForm.runSwitch = function(){
                  
                  mForm.switchset.each(function(sw){
                      if(sw.isActive){
                        mForm.activeNum = sw.setNum;
                        sw.isActive = false;
                      }
                      
                      sw.currentVal = Form.Element.getValue(sw);
                      
                      if(sw.setNum > mForm.activeNum){
                        sw.count = 0;
                        sw.allOptions = Element.select(sw, 'option');
                        sw.allOptions.each(function(opt){
                            if(sw.count > 0){
                              opt.remove();
                            }
                            sw.count++;
                        });
                        
                        sw.allClasses = $A(sw.className.split(' '));
                        
                        sw.compareClass = '';
                        sw.allClasses.each(function(cName){
                            if(cName.indexOf('switchable-')!=-1){
                              var tempName = cName.substring(11, cName.length);
                              var compareAgainst = Element.select(mForm, '.key-'+tempName)[0];
                              
                              sw.compareClass += Form.Element.getValue(compareAgainst);
                              
                              sw.baseOptions.each(function(opt){
                                    
                                    if(Element.hasClassName(opt, sw.compareClass)){
                                      Element.insert(sw, opt);
                                      if(opt.value == sw.currentVal){
                                        opt.setAttribute('selected','selected');
                                        //opt.focus();
                                      }
                                    }
                                  
                              });
                            }
                            
                        });
                        
                      }
                  });
                }                
                
                mForm.mFormControls();   
                
                


  }
  
  //alert("called loadAsyncDirectory");
  modules.loadActions.prototype.search.featuredEvents = $$('form.featured-events');
  //alert("loading modules.protoype");
  modules.loadActions.prototype.search.featuredEvents.each(function(form){

      
      
    form.stopObserving('submit');
    Event.observe(form, 'submit', function(e){
        
        var mstartdate = form.startdate.value;
        var menddate = form.enddate.value;

        
        if (form.useKeywords.value == SiteVars.modules.Search.defaultValue ||
            form.useKeywords.value == keywordPhrase) {
           form.useKeywords.value = '';
        }
        
       // var misland = $('resultsMIslandId').options[$('resultsMIslandId').selectedIndex].className;
       misland = form.selectIslandId.options[form.selectIslandId.selectedIndex].className;
       mfilter = form.SubCategory.options[form.SubCategory.selectedIndex].value;
       
       
       
        if ($('useKeywords').value != keywordPhrase) {
            
            
           var regexVal = new String($('useKeywords').value);
           regexVal = regexVal.replace(search.regExTerm, '');
          
           form.keywords.value = ' AND ( Title:"' + regexVal + '" OR Keywords:"' + regexVal +'" OR Summary:"' + regexVal + '" OR "' + regexVal + '"  )';
        } 
        
        if (misland == '' || misland == 'all') {
            form.mIslandId.value = '("kauai" OR "oahu" OR "molokai" OR "lanai" OR "maui" OR "big-island")';
            
        } else {
          form.mIslandId.value = misland; 
        }
        
        
        if('startdate' in form){
          var sd = jQuery.trim(form.startdate.value);
          var ed = jQuery.trim(form.enddate.value);
          res = search.validateEventDates(form, sd, ed);
          var emsg = 'Your search dates are invalid'; 
          if (res == false) {
            alert(emsg);
            Event.stop(e);
            return;
          }
          else{
            modules.actions.search.checkDates(form);
          }
        }
        
         
        
         var furl = SiteVars.path_to_top + '/featured-island-events/search';
         var fparams = Form.serialize(form);
         
         var ajaxCalls = {
           url:furl,
           params:fparams,
           evalScripts:true,
           onComplete:function(r) {
               
               
               var elm = new Element('div');
               elm.innerHTML = r.responseText;
               
               var html = $(elm).select('.MainContent')[0].innerHTML;
               
               
               
               $$('.MainContent')[0].innerHTML = html;
              //$('featured').innerHTML = html;
               
               
               
               // update filter dropdown
               
               
               
               var myScripts = html.extractScripts();
               var myReturnedValues = myScripts.map(function(script) {
                  return eval(script);
               });
               
               
               
               
               // now update paging
               $$('.paging a').each(function(link) {
                  self.updatePaging(link);
               });
               
               
               
               //=====================
                var mForm = $$('.featured-events')[0];
                
                
                
                self.updateAjaxForm(mForm, misland, mfilter);
                
                
               
                
                mForm.startdate.value = mstartdate;
                mForm.enddate.value = menddate;
                
                
                //var idx = form.selectIslandId.selectedIndex;
                //var selected = form.selectIslandId.options[idx];
                
                
                
                //Element.select(form.selectIslandId, 'option')
                
               
               
               //=====================
               
               
           }
         }
         
         
         // island has changed so we load the page to /island/events/search 
         
         
         if (island_change != '') {
           
           
           var url = SiteVars.path_to_top + '/' + island_change + '/events/search?' + fparams;
           document.location.replace(url);
           
         } else {
         
           modules.sendAsync(ajaxCalls);
         }
         
         Event.stop(e);
        // now find via ajax and update
        
        
        
        //search.setOmniture(form);
        //Event.stop(e);
    });
  });
  
  
  if (SiteVars.this_url.indexOf('/events/search') > -1) {
    initPaging();
  } 
  initReset();
  changeIsland();            
} //}}}

