window.SiteSearch = function() {
  
  this.debug = false;
  this.debugOutput = function(txt) {
    alert(txt);
  };
  
  this.currentResultNum = 1;
  this.currentSearch = null;
  
  this.settings = {
    encoding :  "iso-8859-1",
    fe : "rbs_com_press_releases",
    client : "rbs_com",
    host : "search.rbs.com",
    collections : [
      {
        label : "All",
        id   : "rbs_com"
      }
    ]
  };
  
  this.ui = {
    isInternetExplorer : document.all ? true:false,
    queryTextBox : null,
	day1TextBox : null,
	day2EndTextBox : null,
	month1TextBox : null,
	month2EndTextBox : null,
	year1TextBox : null,
	year2EndTextBox : null,
	prRegionList : null,
    contentPanel : null,
    heading1 : null,
    heading2 : null,
    createSearchNavigation : false,
    previousButtonText : "<< Previous",
    nextButtonText : "Next >>",
    loadingImageSource : "/images/interface/preloader.gif",
    nextInputImageSource : "/images/interface/next.jpg",
    previousInputImageSource : "/images/interface/previous.jpg",
   // noQueryMessage : "Please enter your search terms above. You can also filter by date or region(optional).",
    noResultsMessage : "No results found matching the search \"$a\".",
    spellingSuggestionMessage : "Did you mean : ",
    synonymSuggestionMessage : "You could also try : ",
    heading1Text : "Searching in $a",
    heading2Text : "Results matching $a searching in $b"	
  };
  
  this.query = {

    setText : function(txt) {
      this.ui.queryTextBox.value = txt;
    },  
    
    getText : function() {
		var notDateStart = new String(this.ui.day1TextBox.value);
		var notDateEnd = new String(this.ui.day2TextBox.value);
		if((notDateStart == "") || (notDateEnd == "")){
		var rawText = new String(this.ui.queryTextBox.value);
		return rawText;
		}
		else{
		var dateStart = new String(this.ui.year1TextBox.value + "-" + this.ui.month1TextBox.value + "-" + this.ui.day1TextBox.value);
		var dateEnd = new String(this.ui.year2TextBox.value + "-" + this.ui.month2TextBox.value + "-" + this.ui.day2TextBox.value);
		var rawText = new String(this.ui.queryTextBox.value + " inmeta:date:daterange:" + dateStart + ".." + dateEnd);
		return rawText;
		}
    },
	
	
	
	
	
    
    currentCollection : null,
    
    getSearchCollectionName : function() {
      var name = "";
      for(var i = 0; i < this.settings.collections.length; i++) {
        if(this.settings.collections[i].id == this.currentCollection) {
          name = this.settings.collections[i].label;
        }
      }
      return name;
    } 
  };
  
  this.query.ui = this.ui;
  this.query.settings = this.settings;
  
  this.addScript = function(url) {  
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = url;
    document.getElementsByTagName("head")[0].appendChild(script);
  };

  this.submit = function() {    
    return this.submit(null);
  };
  
  this.submit = function(start) {
    if(start == null) {start = 0;}
	var prRegionListValue = new String(this.ui.prRegionList.value);
    var url = "http://" + this.settings.host + "/search?access=p&output=xml_no_dtd&getfields=description.date&filter=0&sort=date:D:S:d1&client=";
    url += this.settings.client + "&proxystylesheet=" + this.settings.fe + "&ie=" + this.settings.encoding + "&oe=" + this.settings.encoding;	
	if (prRegionListValue!="")
	{url += "&requiredfields=prRegion:" + prRegionListValue;}
    if(this.debug){this.debugOutput("Debug on"); this.debugOutput("Contacting server via " + url);}
    url += "&start=" + start + "&q=" + this.query.getText() + "&site=" + this.query.currentCollection;
  
    this.clearAll();
    this.setHeadings();
    this.setLoadingStatus();
    this.currentResultNum = start;
    this.addScript(url);
    return false;
  };
  
  this.getNextResults = function() {
    var next = this.currentResultNum + 10;
    this.submit(next);    
  };
  
  this.getPreviousResults = function() {
    var previous = (this.currentResultNum >= 11) ?  this.currentResultNum - 10 : 0;
    this.submit(previous);
  };
  
  this.setHeadings = function() {
    
    if(this.debug){this.debugOutput("Setting headings");}
    
    var heading1 = this.ui.heading1;
    var heading2 = this.ui.heading2;
    
    if(heading1 != null) {
      var h1Text = this.ui.heading1Text.replace("\$a", this.query.getSearchCollectionName());   
      this.removeChildNodes(heading1);
      heading1.appendChild(document.createTextNode(h1Text));
    }
    
    if(heading2 != null) {
      this.removeChildNodes(heading2);
      if(this.query.getText() != ""){
        var h2text = this.ui.heading2Text.replace("\$a", this.query.getText());
        var h2text = h2text.replace("\$b", this.query.getSearchCollectionName());
        heading2.appendChild(document.createTextNode(h2text));
        heading2.style.display = "none";
      }
    }
  };
  
  this.setLoadingStatus = function() {
    if(this.debug){this.debugOutput("Setting loading icon");}
    this.loading = this.ui.contentPanel.appendChild(document.createElement("div"));
    this.loading.style.height = "540px";
    this.loading.style.listStyleImage = "none";
    this.loading.style.listStyleType = "none";
    this.loading.style.textAlign = "center";
    this.loading.style.paddingTop = "200px";
    var loadingImg = this.loading.appendChild(document.createElement("img"));
    loadingImg.setAttribute("src", this.ui.loadingImageSource);
  };

  this.removeChildNodes = function (element) {
    if(element.childNodes.length > 0) {
      var currentChild = element.childNodes.item(0);
      var nextChild;
      while(currentChild){
        nextChild = currentChild.nextSibling;
        element.removeChild(currentChild);
        currentChild = nextChild;
      }
    }
  };
  
  this.setStatusText = function(GSP) {
    
    if(this.debug){this.debugOutput("Setting status text");}
	
    this.ui.statusText = this.ui.contentPanel.appendChild(document.createElement("div"));
    this.ui.statusText.className = "statusText";
    
    var message;
    
    if(GSP.queryDetails.estimatedTotal > 0){
			
		if(this.ui.queryTextBox.value == ""){		
			message = "Results matching your search criteria.";	  
		}
	  else if(this.ui.prRegionList.value!="")
	  {
		var w = this.ui.prRegionList.selectedIndex;
		var selected_text = this.ui.prRegionList.options[w].text;
		message = "Results matching the query \"" + this.ui.queryTextBox.value + "\" in region \"" + selected_text + "\".";
	  }
	  else {
	  message = "Results matching the query \"" + this.ui.queryTextBox.value + "\".";
	  }
    }
    else {

	  if(!this.ui.queryTextBox.value == ""){
       // message = this.ui.noQueryMessage;
	   message = this.ui.noResultsMessage.replace("\$a", this.ui.queryTextBox.value);
      }
    } 
	if(message)
	{
		this.ui.statusText.appendChild(document.createElement("p")).appendChild(document.createTextNode(message));
	}
    this.loadSuggestions(GSP.spelling, this.ui.spellingSuggestionMessage);
    this.loadSuggestions(GSP.synonyms, this.ui.synonymSuggestionMessage);
  };
  
  this.loadSuggestions = function(ar, message) {
    
    if(this.debug){this.debugOutput("Loading " + ar.length + " suggestions");}
    
    if(ar.length > 0){  
      var cur_item;   
      var suggestion = this.ui.statusText.appendChild(document.createElement("p"));
      suggestion.appendChild(document.createTextNode(message));
      suggestion.id = "spelling";     
      for(var i = 0; i < ar.length; i++){
        cur_item = suggestion.appendChild(document.createElement("a"));
        cur_item.href = "#";
        cur_item.onclick = trySuggestion;
        cur_item.appendChild(document.createTextNode(ar[i].q));
      }
    }
  };
  
  this.createNavigation = function(GSP) {
    
    if(this.debug){this.debugOutput("Creating navigation bar");}
    
    var previousButton;
    var nextButton;
    var pageNum = ((GSP.queryDetails.startRecordNum - 1) / 10) + 1;
    var s = (Math.floor((pageNum-1)/10) * 10) + 1;
    var e = s + 9;
    var epc = GSP.queryDetails.estimatedTotal / 10;
    
    var navigator = this.ui.contentPanel.appendChild(document.createElement("div"));
    navigator.className = "searchNavigation";
    
    if(epc > 1) {
      
      if (GSP.queryDetails.hasPrevious) {
        previousButton = document.createElement("input");
        previousButton.setAttribute('src', this.ui.previousInputImageSource);
        previousButton.setAttribute('alt', this.ui.previousButtonText);
        previousButton.type = 'image';
        previousButton.className = "previous";
        previousButton.onclick = getPreviousResults;
        previousButton.onkeypress = getPreviousResults;
        navigator.appendChild(previousButton);
      }

      if (GSP.queryDetails.hasNext) {
        nextButton = document.createElement("input");
        nextButton.setAttribute('src', this.ui.nextInputImageSource);
        nextButton.setAttribute('alt', this.ui.nextButtonText);
        nextButton.type = 'image';
        nextButton.className = "next";
        nextButton.onclick = getNextResults;
        nextButton.onkeypress = getNextResults;
        navigator.appendChild(nextButton);
      }
    }
  };
  
  this.trackEvent = function(GSP) {
    try {
      var ev1 = _hbEvent("search");
      ev1.keywords = GSP.queryDetails.queryText;
      ev1.results = GSP.queryDetails.estimatedTotal;
      ev1.attr1 = GSP.queryDetails.site;
    }
    catch(e) {}
  };
  
  this.clearAll = function() {
    if(this.debug){this.debugOutput("Clearing all content");}
    this.removeChildNodes(this.ui.contentPanel);
  };

  this.loadResults = function(GSP) {
    var result;
    var listItem;
    var anchor;
    var para;
	var para1;
	var paraurl;
    var summaryText;
    var summaryDate;
	
    if(this.debug){this.debugOutput("Loading results");}
    
    document.title = "Search";

    this.clearAll();
    this.setStatusText(GSP);
    
    if(GSP.queryDetails.estimatedTotal > 0){
      
      if(this.debug){this.debugOutput(GSP.results.length + " results found");}
      
      this.resultsList = this.ui.contentPanel.appendChild(document.createElement("ol"));
      this.resultsList.className = "feed";
      for(var i = 0; i < GSP.results.length; i++) {
        result = GSP.results[i];
        if(result.title != "") {
          listItem = this.resultsList.appendChild(document.createElement("li"));
          anchor = listItem.appendChild(document.createElement("h4")).appendChild(document.createElement("a"));     
          anchor.href = result.url;
          anchor.title = result.title;
          if(anchor.innerHTML) {
            anchor.innerHTML = result.title; 
          }
          else {
            
            anchor.appendChild(document.createTextNode(this.cleanText(result.title)));
          }
		  //Date
		  
		  para1 = listItem.appendChild(document.createElement("strong")).appendChild(document.createElement("p"));
          summaryDate = result.format_date
		  para1.innerHTML = result.format_date;
		  
		  // Description - words around search term
		  para = listItem.appendChild(document.createElement("p"));
		  summaryText = (result.description == "") ? result.summary : result.description;
		  //summaryText = result.summary;
          if(para.innerHTML) 
		  {
		  para.innerHTML = summaryText;
		  }
          else {
		  para.appendChild(document.createTextNode(this.cleanText(summaryText)));
		  }
		  document.getElementById('h2LatestPressReleases').style.display='none';
		  document.getElementById('dlLatestPressRelease').style.display='none';
        }
      }      
      this.createNavigation(GSP);	  
    }
    else {      
      if(this.debug){this.debugOutput("No results returned");}
    }
    
    if(typeof(this.onLoaded) == "function") this.onLoaded.call();
    
    this.currentSearch = GSP;
    this.trackEvent(GSP);
  };
  
  this.onLoaded = null;
  
  this.cleanText = function(txt) {
    var cleanTxt = txt;
	cleanTxt = cleanTxt.replace(/http:\/\//g, "");
	cleanTxt = cleanTxt.replace(/RBS - /g, "");
	cleanTxt = cleanTxt.replace("‘", "'");
	cleanTxt = cleanTxt.replace("\"", "'");
	cleanTxt = cleanTxt.replace(/&quot;/g, "'");
    cleanTxt = cleanTxt.replace(/(<\/?b>)/g, "");
    cleanTxt = cleanTxt.replace(/&amp;/g, "&");
    cleanTxt = cleanTxt.replace(/&#39;/g, "'");
    return cleanTxt;
  };
}

function changePage() { 
  var a = (ie) ? window.event.srcElement : window.event.target;
  var txt = (a.innerText) ? a.innerText : a.childNodes[0].nodeValue;
  var start = ((parseInt(txt) - 1) * 10);
  search.submit(start);
}

function trySuggestion(e) {
  if(!e) {e = window.event}
  var a = (ie) ? e.srcElement : e.target;
  var txt = (a.innerText) ? a.innerText : a.childNodes[0].nodeValue;
  search.query.setText(txt);
  search.submit();
}

function getNextResults() {
  search.getNextResults()
}

function getPreviousResults() {
  search.getPreviousResults()
}

function loadSearch(GSP) {
  search.loadResults(GSP)
}
