
String.prototype.trim = function() {
  a = this.replace(/^\s+/, '');
  return a.replace(/\s+$/, '');
};
       
// Progress Dialog
var dlgProgress = function(){
	var dlg;
	
	return {
		hideDialog : function(){ dlg.hide(); },
				
    showDialog : function()
    {	
			// lazy initialize the dialog and only create it once
      if(!dlg)
      {             
        dlg = new Ext.Window({
          contentEl:"progress-dlg",
          modal:true,
          width:200,
          height:100,
          shadow:true,
          collapsible: false,
          closable:false, 
          resizable: false,
          layout: 'fit',
          header: true,
          title: 'Searching',
          bodyStyle: 'background-color:#FFFFFF;'
         
        });
      } 
      dlg.show('btnSearch');     
    }
  }
}();
 
// create the Search Dialog (single instance)
var Search = function(){
    
    // define some private variables
    var dialog, showBtn;
    
    // return a public interface
    return {
        init : function(){
             showBtn = Ext.get('show-dialog-btn');
             // attach to click event
             showBtn.on('click', this.showDialog, this);            
                          
             Ext.get('search_text').addKeyListener(13, submitSearch);                  
        },
       		
				hideDialog : function(){
								
          if (document.getElementById('headerHide')) document.getElementById('headerHide').style.visibility = "visible";

					dialog.hide(showBtn);
				},
				
			showDialog : function(){
				if(!dialog){ // lazy initialize the dialog and only create it once
					//set the dialog width based on the longest elements being displayed
					var dialog_width = 410;
					if(document.getElementById('search_classifieds') || document.getElementById('search_announcements')) {
						dialog_width = 470;
					}
                
                
					dialog = new Ext.Window({ 
						contentEl:'search-dlg',                      
						modal:false,
						width:dialog_width,
						autoHeight:true,
						shadow:true,
						minWidth:300,
						minHeight:250,                        
						collapsible: false,                      
						title: 'Advanced Search',
						keys:[
							{
								key: Ext.EventObject.ESC,
								fn: this.hideDialog,
								scope: Search
							},
							{
								key: Ext.EventObject.ENTER,
								fn: processText,
								scope: Search
							}
						],
						buttons:[                   
							{
								text: 'Search',
								handler: processText,
								scope:this
							},
							{
								text: 'Close',
								handler: this.hideDialog,
								scope:this
							}
						]
					});
				}
            
				//This allows the ext dialog to be displayed "above" a flash header
            if (document.getElementById('headerHide')) document.getElementById('headerHide').style.visibility = "hidden";
            //this is here because function "HM_f_PageClick" in HMScriptDOM.js gets called on every page on mouse down by default and pulls flash headers in front of the dialog
            var bodyEl = Ext.get(window.document);
            bodyEl.addListener('mousedown', function (){ if (document.getElementById('headerHide')) { document.getElementById('headerHide').style.visibility = "hidden"; } });

            
            //clear values, if any exist
            Ext.get('search_all').dom.value = '';
            Ext.get('search_exact_phrase').dom.value = '';
            Ext.get('search_at_least_one').dom.value = '';
            Ext.get('search_without').dom.value = '';
            
            //parse search_text prepopulate dialog text boxes based on 'Search Criteria' value
            var search_text = Ext.get('search_text').dom.value.replace(/\s{2,}/g, ' ');
            
            var search_all = '';
            var search_exact_phrase = '';
            var search_without = '';
            var search_at_least_one = '';

            if(search_text != '')
            {
              //check to see if advanced search characters/words are present
              if(search_text.indexOf('"') != -1 || search_text.indexOf(' -') != -1 || search_text.toUpperCase().indexOf(' OR ') != -1 || search_text.toUpperCase().indexOf(' AND ') != -1)
              {
                var firstQuote = search_text.indexOf('"');            
                var lastQuote = search_text.lastIndexOf('"');
               
                if(firstQuote != -1 && (firstQuote != lastQuote)) //if two quotes do exist,
                {
                  search_exact_phrase = search_text.slice(firstQuote + 1, lastQuote);
                  Ext.get('search_exact_phrase').dom.value = search_exact_phrase;
                  search_text = search_text.replace('"' + search_exact_phrase + '"', '');                
                }
                
              //'without' terms present
                if(search_text.indexOf(' -') != -1)   
                {
                  var arrWithout = search_text.split(' ');
                  
                  for(i = 0; i < arrWithout.length; i++)
                  {
                    if(arrWithout[i].indexOf('-') == 0)   //if '-' is the first character, it is a 'without' term
                    {                    
                      search_without += arrWithout[i].replace('-', ' ');
                      search_text = search_text.replace(arrWithout[i], '')
                      search_text = search_text.replace(/\s{2,}/g, ' ');   //replace any double spaces (or triple, etc)
                      search_text = search_text.trim();
                    }
                    
                    search_without = search_without.trim();
                    Ext.get('search_without').dom.value = search_without;
                  } 
                }
                
                var search_text_temp = ''; 
                
              //Parse Specified Logical 'And'  [ specified AND's take precedence over ORs,]
               //  [Normally, ANDs are not displayed...So, Specified ORs take precedence over implied ANDs]
                if(search_text.toUpperCase().indexOf(' AND ') != -1)
                {
                  search_text_temp = search_text.replace(/ AND /gi, '&&');   //replace ' AND ' with && (basically, remove spaces to help deliniate search text)            
                  
                  var arrAll = search_text_temp.split(' ');     //split by remaining whitespace into logical 'AND' Groupings  
                  
                  for(i = 0; i < arrAll.length; i++)
                  {
                    if(arrAll[i].indexOf('&&') != -1)   //&&'s exist-->is part of an 'all the words' term
                    {
                      //split 'all the words' terms
                      var arrAllWords = arrAll[i].split('&&');
                      for(ix = 0; ix < arrAllWords.length; ix++)
                      {
                        search_all += arrAllWords[ix] + ' ';
                      }                                            
                      
                      //remove the concatenated 'all words' criteria...the remaining words are the 'at least one' terms
                      search_text_temp = search_text_temp.replace(arrAll[i], '').trim();
                      search_text_temp = search_text_temp.replace(/\s{2,}/g, ' ');   //replace any double spaces (or triple, etc)
                    }
                  } 
                  
                  search_text = search_text_temp;
                  
                  Ext.get('search_all').dom.value = search_all.trim();               
                }
                
                
                //Parse Logical 'OR'              
                if(search_text.toUpperCase().indexOf(' OR ') != -1 || search_text.toUpperCase().indexOf('OR ') != -1 || search_text.toUpperCase().indexOf(' OR') != -1)
                {
                  search_text_temp = search_text.replace(/ OR /gi, '||');   //replace ' OR ' with pipes (basically, remove spaces to help deliniate search text)
                  search_text_temp = search_text_temp.replace(/OR /gi, '||');   //replace 'OR ' with pipes (in case removing the 'AND' terms left a dangling OR
                  search_text_temp = search_text_temp.replace(/ OR/gi, '||');   //replace ' OR' with pipes (in case removing the 'AND' terms left a dangling OR
                  
                  var arrOne = search_text_temp.split(' ');    //split into logical 'OR' Groupings
                  
                  for(i = 0; i < arrOne.length; i++)
                  {
                    if(arrOne[i].indexOf('||') != -1)   //pipes exist-->is part of 'at least one' term
                    {
                      //split 'at least one' terms
                      var arrAtLeastOne = arrOne[i].split('||');
                      for(ix = 0; ix < arrAtLeastOne.length; ix++)
                      {
                        search_at_least_one += arrAtLeastOne[ix] + ' ';
                      }                                            
                      
                      //remove the concatenated 'at least one' criteria...the remaining words are also 'at least one' terms
                      search_text_temp = search_text_temp.replace(arrOne[i], '').trim();
                      search_text_temp = search_text_temp.replace(/\s{2,}/g, ' ');   //replace any double spaces (or triple, etc)
                    }
                  } 
                                                                     
                  search_text = search_text_temp;
               
                  Ext.get('search_at_least_one').dom.value = search_at_least_one.trim();               
                }                                
                
                //All remaining terms are also part of 'search all words'.                 
                
               search_all += ' ' + search_text.trim();
               Ext.get('search_all').dom.value = search_all.trim();  
         
              }
              else { Ext.get('search_all').dom.value = search_text; }   //do simple search (logical AND)              
            }            
            dialog.show(showBtn);                              
        }               
    };
}();


function processText()
{  	
	Search.hideDialog();	
	
  parseSearchText();
  //let the animation finish before submitting the search
  setTimeout('submitSearch()', 500);
}

function searchLoad()
{
  //generate currently searching display
  currentlySearching();
  
  Ext.get('search_text').dom.value = Ext.get('search_text').dom.value.replace(/\s{2,}/g, ' ').trim();
  
  Search.init();
}
  
function NoSpecialCharacters(e)
{
    var key;
    var keychar;

    if (window.event) { key = window.event.keyCode; }
    else if (e) { key = e.which; }
    else { return true; }
       
    keychar = String.fromCharCode(key);
    keychar = keychar.toLowerCase();

    // control keys
    if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27) ) { return true; }
       
    // alphas and numbers
    else if ((("abcdefghijklmnopqrstuvwxyz0123456789.'_- ").indexOf(keychar) > -1)) { return true; }
    else { return false; }
}

function currentlySearching()
{   
  if(Ext.get('search_text').dom.value == '')
  {
    //clear currently searching divs
    Ext.get('div_currently_searching_label').dom.innerHTML = '';
    Ext.get('div_currently_searching').dom.innerHTML = '';
    return;
  }
        
  var strCurrentlySearching = "";
  var searchAllModules = true;
  
  if(document.getElementById('search_members'))
  {
    if(Ext.get('search_members').dom.checked == '1') { strCurrentlySearching += 'Directory'; }
    else { searchAllModules = false; }
  }
    
  if(document.getElementById('search_events'))
  {
    if(Ext.get('search_events').dom.checked == '1')
    {
      if(strCurrentlySearching != "")
      {
        strCurrentlySearching += ', Events';
        if(Ext.get('search_events_past').dom.checked == '1') { strCurrentlySearching += ' (past)'; }
      }
      else
      {
        strCurrentlySearching += 'Events';   
        if(Ext.get('search_events_past').dom.checked == '1') { strCurrentlySearching += ' (past)'; }
      }   
    }
    else { searchAllModules = false; }
  }
  
  if(document.getElementById('search_forms'))
  {
    if(Ext.get('search_forms').dom.checked == '1')
    {
      if(strCurrentlySearching != "") { strCurrentlySearching += ', Forms'; }
      else { strCurrentlySearching += 'Forms'; }
    }
    else { searchAllModules = false; }
  }
  
  if(document.getElementById('search_classifieds'))
  {
    if(Ext.get('search_classifieds').dom.checked == '1')
    {
      if(strCurrentlySearching != "")
      {
        strCurrentlySearching += ', Classifieds';
        if(Ext.get('search_classifieds_past').dom.checked == '1') { strCurrentlySearching += ' (past)'; }
      }
      else
      {
        strCurrentlySearching += 'Classifieds';   
        if(Ext.get('search_classifieds_past').dom.checked == '1') { strCurrentlySearching += ' (past)'; }
      }   
    }
    else { searchAllModules = false; }
  }
  
  if(document.getElementById('search_announcements'))
  {
    if(Ext.get('search_announcements').dom.checked == '1')
    {
      if(strCurrentlySearching != "")
      {
        strCurrentlySearching += ', News';
        if(Ext.get('search_announcements_past').dom.checked == '1') { strCurrentlySearching += ' (past)'; }            
      }
      else
      {
        strCurrentlySearching += 'News';   
        if(Ext.get('search_announcements_past').dom.checked == '1') { strCurrentlySearching += ' (past)'; }
      }   
    }
    else { searchAllModules = false; }
  }      
  
  if(document.getElementById('search_docs'))
  {
    if(Ext.get('search_docs').dom.checked == '1')
    {
      if(strCurrentlySearching != "")
        { strCurrentlySearching += ', Resource Center (' + Ext.get('search_docs_cat').dom.options[Ext.get('search_docs_cat').dom.selectedIndex].text + ')'; }
      else
        { strCurrentlySearching += 'Resource Center (' + Ext.get('search_docs_cat').dom.options[Ext.get('search_docs_cat').dom.selectedIndex].text + ')'; }
    }
    else { searchAllModules = false; }
  }
  
  if(document.getElementById('search_weblinks'))
  {
    if(Ext.get('search_weblinks').dom.checked == '1')
    {
      if(strCurrentlySearching != "") { strCurrentlySearching += ', Web Pages'; }
      else { strCurrentlySearching += 'Web Pages'; }
    }
    else { searchAllModules = false; }
  }
  
  if(document.getElementById('search_posts'))
  {
    if(Ext.get('search_posts').dom.checked == '1')
    {
      if(strCurrentlySearching != "")
      {
        strCurrentlySearching += ', Posts';
        if(Ext.get('search_posts_archived').dom.checked == '1') { strCurrentlySearching += ' (past)'; }
      }
      else
      {
        strCurrentlySearching += 'Posts';   
        if(Ext.get('search_posts_archived').dom.checked == '1') { strCurrentlySearching += ' (past)'; }
      }   
    }
    else
      { searchAllModules = false; }
  }
  
  Ext.get('div_currently_searching_label').dom.innerHTML = 'Currently Searching ';
  
  if(searchAllModules) { Ext.get('div_currently_searching').dom.innerHTML = ' - All Modules'; }
  else { Ext.get('div_currently_searching').dom.innerHTML = ' - ' + strCurrentlySearching; }
  
}

function submitSearch()
{
  var text = Ext.get('search_text').dom.value.replace(/\s{2,}/g, ' ').trim();  //remove double spaces

  text = text.replace(/[+*%&=><!\[\]{}@;()#,]/g, '');    //protect against sql injection
  text = text.replace("'", "");
  text = text.replace('\\', '');
  text = text.replace('/', '');
  text = text.replace('--', '');
  
  Ext.get('search_text').dom.value = AV.NoiseWords.remove(text);
  
  if(text == '') {return;}
  
  if(text.indexOf('-"') != -1){alert('Searching "without" an exact phrase is not allowed.'); return;}
  
  if(text.split('"').length > 3) {alert('Searching for multiple exact phrases is not allowed.  The search text contains too many quotation marks.'); return;};
  
  if(text.split('"').length == 2) {alert('Search criteria containing a single quotation mark is not allowed.'); return;};
  
  if( text.toUpperCase().trim()== 'AND' || text.toUpperCase().trim() == 'OR') {alert('Additional Keywords required.'); return;};
  
  if(text.toUpperCase().indexOf(' AND OR ') != -1 || text.toUpperCase().indexOf(' OR AND ') != -1){alert('Operators may not be next to each other.'); return;}
  
  //******************** --write the search_text submit value to a field in the form -- **************************    	
  Ext.get('search_text_for_submit').dom.value = Ext.get('search_text').dom.value;
    	
  document.form1.submit();	  	
  dlgProgress.showDialog();  	  
}

function parseSearchText()
{
  //  /\s{2,}/ replaces multiple spaces with one
  var search_text = '';
  var search_exact = document.getElementById('search_exact_phrase').value.replace(/\s{2,}/g, ' ').trim();
  var search_all = document.getElementById('search_all').value.replace(/\s{2,}/g, ' ').trim();
  var search_one = document.getElementById('search_at_least_one').value.replace(/\s{2,}/g, ' ').trim();
  var search_without = document.getElementById('search_without').value.replace(/\s{2,}/g, ' ').trim();
  
  if(search_exact != "") { search_text +='"' + search_exact + '" '; }
    
  if(search_all != "")
  {
    if(search_text != '') { search_text += ' ' + search_all.replace(/\s{2,}/g, ' ').trim(); }
    else { search_text += search_all.replace(/\s{2,}/g, ' ').trim(); }
  }
  
  if(search_one != "")
  {
     search_one = search_one.trim();
     
     var arrOne = search_one.split(' ');
     var strOne = '';
     for(i = 0; i < arrOne.length; i++)
     {
      if(i != arrOne.length-1 && arrOne.length != 1) { strOne += arrOne[i] + ' OR '; }
      else { strOne += arrOne[i] + ' '; }
     }     

    //if only one 'at least one' term is entered, it becomes a logical AND (per google)
    //a single 'at least one' term constitutes a misuse of the 'at least one' functionality
    if(search_text != '') { search_text += ' ' + strOne + ' '; }    //if search text already exists...
    else { search_text += strOne + ' '; }
  }
  
  if(search_without != "")
  {
     var arrWithout = search_without.split(' ');
     var strWithout = '';
     for(i = 0; i < arrWithout.length; i++) { strWithout += ' -' + arrWithout[i] + ' '; }     
      
     search_text += strWithout;  
  }          
  
  document.getElementById('search_text').value = search_text.trim().replace(/\s{2,}/g, ' ');   //replace any double spaces (or triple, etc);    
}
  
function togglePastBoxes()
{
  for (var n=1; n<arguments.length; n++)
	{
	  if (document.getElementById(arguments[n]))
		  { document.getElementById(arguments[n]).disabled = !arguments[0]; }
	}
}

function toggleBoxes(doCheck)
{
  if(doCheck)  
  {
    //toggle first column of check boxes
    Ext.select('input.toggle1', true).each( function(el, this1, index){
                                              el.dom.checked = true;
                                            });    
    //enable all second column of inputs
    Ext.select('input.toggle2', true).each( function(el, this1, index){
                                              el.dom.disabled = false;
                                            });
    //enable all second column labels                                 
    Ext.select('label.toggle2', true).each( function(el, this1, index){
                                                        el.dom.parentNode.disabled = false;                                 
                                                      });    
    //toggle the select
    var search_docs_cat = document.getElementById('search_docs_cat');
    if(search_docs_cat)    
      search_docs_cat.disabled = false;
    
  }
  else
  {
  
   //toggle first column of check boxes
    Ext.select('input.toggle1', true).each( function(el, this1, index){
                                              el.dom.checked = false;
                                            });
    //toggle second column of check boxes
    Ext.select('input.toggle2', true).each( function(el, this1, index){
                                              el.dom.checked = false;
                                              
                                            });                                            
    //disable all second column labels                                 
    Ext.select('label.toggle2', true).each( function(el, this1, index){
                                              el.dom.parentNode.disabled = true;
                                            });    
    //disable all second column of inputs
    Ext.select('input.toggle2', true).each( function(el, this1, index){
                                              el.dom.disabled = true;
                                            });
    //toggle the select
    var search_docs_cat = document.getElementById('search_docs_cat');
    if(search_docs_cat)    
      search_docs_cat.disabled = true;
  }
}
  
function loadDownload(sdoc_filename) 
{ 
 document.location.href = "/doc/Download.asp?doc_filename=" + escape(sdoc_filename);
}

Ext.EventManager.addListener(window, "load", searchLoad);