/*
Copyright (c) 2003-2008, Peter Tyrrell and Andornot Consulting Inc.

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

Neither the name "Peter Tyrrell" nor "Andornot Consulting Inc."
may be used to endorse or promote products derived from this software
without specific prior written permission.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

/* HELPERS */
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };
String.prototype.trimSeparator = function(separator) 
{
	var output = this;
	if (output.indexOf(separator + separator) != -1)
	{
		output = output.replace(separator + separator, separator);	
	}
	if (output.indexOf(separator) == 0)
	{
		output = output.substring(separator.length, output.length);
	}
	else if (output.lastIndexOf(separator) == (output.length - separator.length))
	{
		output = output.substring(0, (output.length - separator.length));
	} 
	return output;
}
String.prototype.escapeHTML = function() {return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}
String.prototype.unescapeHTML = function() {return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');}

/*
GetQueryParamByKey() returns the query parameter value if any match found for key, or an empty string
*/
function GetQueryParamByKey(key, strQuery)
{
	if (!strQuery)
	{
		strQuery = window.location.search.substring(1);
	}
	var regex = new RegExp(key + "=([^&]+)");
	var keyMatch = strQuery.match(regex);
	var output = "";
	if (keyMatch != null)
	{
	    output = keyMatch[1];
	}
	return output;
}


/********************************
NEXTPREVIOUS
Functions to page back and forth in WebPublisher search results
********************************/

/*
NEXTPREVIOUS GLOBAL VARIABLES
*/

// global page url
var currentUrl = window.location.href;

if (currentUrl.indexOf("?") != -1)
{
	currentUrl = currentUrl.substr(0, currentUrl.indexOf("?")); //snip href minus query string
}

// global link text values
var npFirstText = "First";
var npPreviousText = "Previous {MR}";
var npNextText = "Next {MR}";
var npLastText = "Last";

var npFirstRecordText = "First";
var npPreviousRecordText = "Previous";
var npNextRecordText = "Next";
var npLastRecordText = "Last";

//global page range values
var npPageRange = 10;
var npPageRangePreText = "";
var npPageRangePostText = "";

//global show MR count in link text
var npShowMR = true;

//global css class names
var npLinkCss = "nextprev_link";
var npTextCss = "nextprev_text";


/*
Next/previous BLOCK section 
Use in reports where multiple records shown at a time
*/

function nextprev_First()
{
	var params = window.dbtw_params;
	var text = npFirstText;
	var output = "";
	var first_params = "";
	
	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);
	
	// prepare link text
	if (npShowMR == true)
	{
		text = text.replace(/{MR}/g, mr.toString());
	}
	else 
	{
		text = text.replace(/{MR}/g, "");
	}
	text = text.trim();
	
	// determine whether a link should be made
	if (rn == 0)
	{
		output += "<span class='" + npTextCss + "'>" + text + "</span>";
	}
	else
	{
		var first_params = params.replace((/RN=(\d+)/), "RN=" + mr.toString());
		output += "<a href='" + currentUrl;
		output +=  "?AC=PREV_BLOCK" + first_params;
		output += "' class='" + npLinkCss + "'>"; 
		output += text;
		output += "</a>";
	}
	return output;
}

function nextprev_Previous()
{
	var params = window.dbtw_params;
	var text = npPreviousText;
	var output = "";		

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);
	
	//comparison number for prev block
	var prev_total = (rn - mr);
	
	// prepare link text
	if (npShowMR == true)
	{
		text = text.replace(/{MR}/g, mr.toString());
	}
	else 
	{
		text = text.replace(/{MR}/g, "");
	}
	text = text.trim();
	
	// determine if a link should be made
	if (prev_total >= 0 && mr != 0)
	{
		output += "<a href='" +  currentUrl;
		output +=  "?AC=PREV_BLOCK" + params;
		output += "' class='" + npLinkCss + "'>";
		output += text;
		output += "</a>";
	}
	else if (mr == 0)
	{
		output += "<span class='" + npTextCss + "'>" + text + "</span>";
	}
	else
	{
		output += "<span class='" + npTextCss + "'>" + text + "</span>";
	}
	return output;
}

function nextprev_Next(record_count)
{
	var params = window.dbtw_params;
	var text = npNextText;
	var output = "";
	var rc = parseInt(record_count);		

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);
	
	// prepare link text
	if (npShowMR == true)
	{
		text = text.replace(/{MR}/g, mr.toString());
	}
	else 
	{
		text = text.replace(/{MR}/g, "");
	}
	text = text.trim();
	
	//comparison number for next block
	var next_total = (rc - mr - rn);

	// determine if a link should be made
	if (next_total > 0 && mr != 0)
	{
		output += "<a href='" + currentUrl;
		output +=  "?AC=NEXT_BLOCK" + params;
		output += "' class='" + npLinkCss + "'>";
		output += text;
		output += "</a>";	
	}
	else if (mr == 0)
	{
		output += "<span class='" + npTextCss + "'>"+text;
		output += "</span>";	
	}	
	else
	{
		output += "<span class='" + npTextCss + "'>"+text;
		output += "</span>";	
	}
	return output;
}

function nextprev_Last(record_count)
{
	var params = window.dbtw_params;
	var text = npLastText;
	var output = "";
	var last_params = "";
	var rc = parseInt(record_count);

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);
	
	// prepare link text
	if (npShowMR == true)
	{
		text = text.replace(/{MR}/g, mr.toString());
	}
	else 
	{
		text = text.replace(/{MR}/g, "");
	}
	text = text.trim();
	
	//comparison number for next block
	var last_total = (rc - mr - rn);
		
	// determine if a link should be made
	if (last_total <= 0 || mr <= 0)
	{
		output = "<span class='" + npTextCss + "'>"+text;
		output += "</span>";
	}
	else
	{
		var last_RN = (Math.floor(((rc-1) / mr)) - 1) * mr;
		var last_params = params.replace((/RN=(\d+)/), "RN=" + last_RN);
		
		output += "<a href='" + currentUrl;
		output +=  "?AC=NEXT_BLOCK" + last_params;
		output += "' class='" + npLinkCss + "'>";
		output += text;
		output +="</a>";
	}
	return output;
}

/*
nextprev_PageRange() provides an sliding numeric alternative to next/previous links
*/
function nextprev_PageRange(record_count)
{
	var params = window.dbtw_params;
	var rc = parseInt(record_count);
	var i = 0;
	var j = 0;
	var pre_params = "";
	var post_params = "";
	var pre_link = "";
	var post_link = "";	
	var current_write = "";
		
	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);	
	
	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);	
	
	// determine current page	
	var current_page = (rn / mr) + 1
	
	if ( rc % mr == 0)
	{
		var total_page = rc / mr
	}
	else 
	{
		var total_page = ((rc - (rc%mr)) / mr) + 1
	}	

	// build links before current page
	if ((total_page - current_page) < (Math.round(npPageRange / 2) - 1))
	{
		var PreSlider = (npPageRange - (total_page - current_page)) - 1;
	}
	else
	{
		var PreSlider = Math.round(npPageRange / 2);
	}
	var PreCount = 0;
	for (i = current_page - PreSlider; i < current_page; i++)
	{		
		if (i <= 0)
		{
			continue;	
		}
		else
		{
			pre_params = params.replace((/RN=(\d+)/), "RN=" + (mr * i));
			pre_link += "<a href='" + currentUrl;
			pre_link +=  "?AC=PREV_BLOCK" + pre_params;
			pre_link += "' class='" + npLinkCss + "'>"; 
			pre_link += npPageRangePreText + i + npPageRangePostText;
			pre_link += "</a> ";
			
			PreCount++;
		}
	}	
	
	// build links after current page
	var PostSlider = npPageRange - PreCount;
	for (j = current_page + 1; j < (current_page + PostSlider); j++)
	{		
		if (j > total_page)
		{
			break;	
		}
		else
		{
			post_params = params.replace((/RN=(\d+)/), "RN=" + (mr * (j-2)));
			
			post_link += "<a href='" + currentUrl;
			post_link +=  "?AC=NEXT_BLOCK" + post_params;
			post_link += "' class='" + npLinkCss + "'>";
			post_link += npPageRangePreText + j + npPageRangePostText;
			post_link +="</a> ";	
					
		}
	}
	
	current_write = "<span class='" + npTextCss + "'>" + npPageRangePreText + current_page + npPageRangePostText + "</span> "
	
	return pre_link + current_write + post_link;	
}


/*
Next/previous RECORD section
Use in full display where one record shown at a time
*/

function nextprevRecord_First()
{
	var params = window.dbtw_params;
	var text = npFirstRecordText;
	var output = "";

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);
		
	// determine if a link should be made
	if (rn > 0)
	{
		var first_params = params.replace((/RN=(\d+)/), "RN=1");
		output += "<a href='" + currentUrl;
		output +=  "?AC=PREV_RECORD" + first_params;
		output += "' class='" + npLinkCss + "'>";
		output += text + "</a>";
	}
	else
	{
		output = "<span class='" + npTextCss + "'>"+text+"</span>";	
	}

	return output;
}

function nextprevRecord_Previous()
{
	var params = window.dbtw_params;
	var text = npPreviousRecordText;
	var output = "";

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// determine if a link should be made
	if (rn > 0)
	{
		output += "<a href='" +  currentUrl;
		output +=  "?AC=PREV_RECORD" + params;
		output += "' class='" + npLinkCss + "'>";
		output += text + "</a>";
	}
	else
	{
		output = "<span class='" + npTextCss + "'>"+text+"</span>";	
	}

	return output;
}

function nextprevRecord_Next(record_count)
{
	var params = window.dbtw_params;
	var text = npNextRecordText;
	var output = "";
	var rc = parseInt(record_count);

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);
	
	// determine if a link should be made
	if (rn+1 < rc)
	{
		output += "<a href='" + currentUrl;
		output +=  "?AC=NEXT_RECORD" + params;
		output += "' class='" + npLinkCss + "'>";
		output += text + "</a>";
	}
	else
	{
		output = "<span class='" + npTextCss + "'>"+text+"</span>";	
	}

	return output;
}

function nextprevRecord_Last(record_count)
{
	var params = window.dbtw_params;
	var text = npLastText;
	var output = "";
	var rc = parseInt(record_count);

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);
	
	// determine if a link should be made
	if (rn+1 < rc)
	{
		var last_params = params.replace((/RN=(\d+)/), "RN=" + (rc-2));
		output += "<a href='" + currentUrl;
		output +=  "?AC=NEXT_RECORD" + last_params;
		output += "' class='" + npLinkCss + "'>";
		output += text + "</a>";
	}
	else
	{
		output = "<span class='" + npTextCss + "'>"+text+"</span>";	
	}

	return output;
}

/*
 The original back_to_block method was written by Terry McBride tttmcbride@yahoo.com
 This method takes you from a display of an expanded record back to  the list from the position that the current expanded record would be in.
*/

function back_to_block() 
{
	var params = window.dbtw_params.unescapeHTML();

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);

	// find the lower multiple of mr and add another mr to it to fool PREV_BLOCK
	var remainder = (rn % mr);
	var start = (rn - remainder + mr); 

	var i = params.indexOf("RN=") + 3;
	var j = params.indexOf("&", i);

	var url = currentUrl + "?AC=PREV_BLOCK" + params.substring (0, i) + start + params.substring(j, params.length);

	window.location.href = url; 
}

/*
back_to_block_cookie() sets a cookie with the back_to_block query string
*/

function back_to_block_cookie(Textbase) 
{
	var params = window.dbtw_params.unescapeHTML();

	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);

	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);

	// find the lower multiple of mr and add another mr to it to fool PREV_BLOCK
	var remainder = (rn % mr);
	var start = (rn - remainder + mr); 

	var i = params.indexOf("RN=") + 3;
	var j = params.indexOf("&", i);

	var url = currentUrl + "?AC=PREV_BLOCK" + params.substring (0, i) + start + params.substring(j, params.length);
	
	document.cookie = Textbase + "_DbtwLastResult=" + encodeURIComponent(url) + "; path=/";
}

function back_to_record_cookie(Textbase, RecordNumber)
{
	var params = window.dbtw_params.unescapeHTML();
	var rn = parseInt(RecordNumber) - 1;
	var i = params.indexOf("RN=") + 3;
	var j = params.indexOf("&", i);
	
	// reconstruct the link with only the RN value replaced
	var url = currentUrl + "?AC=GET_RECORD" + params.substring (0, i) + rn + params.substring(j, params.length);
	document.cookie = Textbase+ "_DbtwFullRecord=" + encodeURIComponent(url) + "; path=/";
}

function record_count_cookie(Textbase, RecordCount)
{
	document.cookie = Textbase + "_RecordCount=" + encodeURIComponent(RecordCount) + "; path=/";
}

/*
ExpandRecord() emulates the WebPublisher expand link
*/
function ExpandRecord(recordnum, newWindow)
{
	var params = dbtw_params.unescapeHTML();
	var snipA = "";
	var snipZ = "";
	var myUrl = window.location.href.replace(window.location.search, "");
	
	if (recordnum == 1)
	{
		snipA = params.indexOf("RN=") + 3;
		snipZ = params.indexOf("&", snipA);
		params = params.substring(0, snipA) + (recordnum) + params.substring(snipZ, params.length);
		myUrl += "?AC=PREV_RECORD" + params;
	}
	else
	{
		snipA = params.indexOf("RN=") + 3;
		snipZ = params.indexOf("&", snipA);
		params = params.substring(0, snipA) + (recordnum-2) + params.substring(snipZ, params.length);	
		myUrl += "?AC=NEXT_RECORD" + params;
	}
	
	if (newWindow && newWindow == true)
	{
	    window.open(myUrl);
	}
	else
	{
	    window.location.href = myUrl;
	}
}

/*
LastRecordNumber() gets last record number on page
*/
function LastRecordNumber(count)
{
	var params = dbtw_params;
	var output = "";
	
	// find the record number
	var rns = params.match(/RN=(\d+)/);
	var rn = parseInt(rns[1]);	
	
	// MR is records at a time
	var mrs = params.match(/MR=(\d+)/);
	var mr = parseInt(mrs[1]);	
	
	// count < mr = one page of results only
	if (count < mr)
	{
        output = (rn + count).toString();
	}
	else
	{
	    // (rn + mr) >= count means last page
	    if ((rn + mr) >= count)
	    {
	        output = count.toString();
	    }
	    else
	    {
	        output = (rn + mr).toString();
	    }
	}
	return output;
}

/*********************************
CHANGEFORM
Functions to switch forms while in WebPublisher
*********************************/

/*
Used in webforms to select other forms from a dropdown.
Option values contain actual form names, so option text is flexible.
*/
function dbtw_form_change_onvalue(select_object, action, params)
{
		params = params.unescapeHTML();
    var new_form = encodeURIComponent(select_object.options[select_object.selectedIndex].value);
    var i = new_form.indexOf("+");
    while ( i >= 0 )
    {
       new_form = new_form.substring( 0, i ) +
                   "%2B" +
                   new_form.substring( i+1, new_form.length );
       i = new_form.indexOf("+");
    }

    var form_key = "RF=";
    var n1 = params.indexOf( form_key );
    var n2 = n1 + form_key.length;
    var n3 = params.indexOf( "&", n2 );
    var n4 = params.length;
    var form_change_url = action + "?AC=CHANGE_REPORT" +
                           params.substring( 0, n2 ) +
                           new_form +
                           params.substring( n3, n4 );
    window.location.href = form_change_url;
}
   
   
/*
Used in web reports to change forms generically without a select object.
*/   
function dbtw_report_change(report_name, action, params)
{
	 params = params.unescapeHTML();
   var new_form = encodeURIComponent(report_name);
   var i = new_form.indexOf( "+" );
   while ( i >= 0 )
   {
	   new_form = new_form.substring( 0, i ) +
	               "%2B" +
	               new_form.substring( i+1, new_form.length );
	   i = new_form.indexOf( "+" );
	}

   var form_key = "RF=";
   var n1 = params.indexOf( form_key );
   var n2 = n1 + form_key.length;
   var n3 = params.indexOf( "&", n2 );
   var n4 = params.length;
   var form_change_url = action + "?AC=CHANGE_REPORT" +
                           params.substring( 0, n2 ) +
                           new_form +
                           params.substring( n3, n4 );
	window.location.href = form_change_url;
}

/*
Used in web full displays to change forms generically without a select object.
*/ 
function dbtw_display_change(display_name, action, params)
{
	 params = params.unescapeHTML();
   var new_form = encodeURIComponent(display_name);
   var i = new_form.indexOf( "+" );
   while ( i >= 0 )
   {
	   new_form = new_form.substring( 0, i ) +
	               "%2B" +
	               new_form.substring( i+1, new_form.length );
	   i = new_form.indexOf( "+" );
	}

   var form_key = "DF=";
   var n1 = params.indexOf( form_key );
   var n2 = n1 + form_key.length;
   var n3 = params.indexOf( "&", n2 );
   var n4 = params.length;
   var form_change_url = action + "?AC=CHANGE_DISPLAY" +
                           params.substring( 0, n2 ) +
                           new_form +
                           params.substring( n3, n4 );
	window.location.href = form_change_url;
}


/****************************
SEARCHKLEEN
****************************/

/*
SearchKleen() takes the Inmagic search variable and strips field information out
as well as extraneous punctuation, parantheses, etc.
*/
function SearchKleen()
{
 
  var searchvar = document.getElementById("InmagicSearchVariable").innerHTML;
  var kleen = "";
  
  // Start kleen value with FIND or FINDALL taken from searchvar
  //kleen += searchvar.substring(0, searchvar.indexOf("("))+" ";
  
  var reSearchTerms = /\sct\s.*?\)|=.*?\)/g;
  var reBoolean = /\)\s*\n?.*?\(/g; //works with IE and Mozilla
  var strMatch = searchvar.match(reSearchTerms); //array of search terms
  var strMatch2 = searchvar.match(reBoolean); //array of Boolean operators
  var snipMatch;
  var snipMatch2;
  
  if (strMatch != null)
  {
    for (var i=0;i<strMatch.length;i++)
    {
      if (strMatch[i].indexOf(" ct ") != -1)
      {
        snipMatch = strMatch[i].substring(strMatch[i].indexOf(" ct ")+4, strMatch[i].indexOf(")"));
      }
      else if (strMatch[i].indexOf("=") != -1)
      {
      	snipMatch = strMatch[i].substring(strMatch[i].indexOf("=")+1, strMatch[i].indexOf(")"));
      }
      kleen += snipMatch;

      if (strMatch2 != null && strMatch2[i])
      {
        snipMatch2 = strMatch2[i].substring(strMatch2[i].indexOf(" ) ")+3, strMatch2[i].indexOf(" (")); 
        kleen += " "+snipMatch2+" ";
      }
    }
  }
  
  document.getElementById("FriendlySearch").innerHTML = kleen;
}


/***********************
URLTAMER
***********************/

/*
Shortens a single or multiple URL strings to maximum number of characters.
*/

function URLTamer(url, maxlen)
{
  var mid;
  var takeaway;
  var strfirsthalf;
  var strbefore;
  var strafter;
  var strfinal = "";
  var ellipsis = "...";
  var splitchar = "|split|";
  var arrurl = new Array();
  var i;
  

  // split url string if splitchar is found
  arrurl = url.split(splitchar);
  
  // loop through the array, building hyperlink for each member
  for (i=0; i<arrurl.length; i++)
  {
  	if (arrurl[i].length > maxlen)
	{	
		mid = Math.round(arrurl[i].length / 2);
		takeaway = Math.round((arrurl[i].length - maxlen) / 2);
		takeaway += ellipsis.length / 2;
		takeaway = Math.round(takeaway);
				
		strbefore = arrurl[i].substring(0, mid);
		strbefore = strbefore.substring(0, strbefore.length + 1 - takeaway);
						
		strafter = arrurl[i].substring(mid, arrurl[i].length + 1);
		strafter = strafter.substring(takeaway, strafter.length + 1);
				
		strfinal += "<a target=\"_blank\" href=\"" + arrurl[i] + "\">"
				+ strbefore + ellipsis + strafter
				+ "</a><br />";
	}
	else
	{
		strfinal += "<a target=\"_blank\" href=\"" + arrurl[i] + "\">"
				+ arrurl[i]
				+ "</a><br />";
	}
  }
  
  return strfinal;
}

function TrimMid(val, len, ellipsis)
{
	var output = "";
	
	var mid = Math.round(val.length / 2);
	var takeaway = Math.round((val.length - len) / 2);
	if (ellipsis)
	{
		takeaway += ellipsis.length / 2;	
	}
	takeaway = Math.round(takeaway);
			
	var strbefore = val.substring(0, mid);
	strbefore = strbefore.substring(0, strbefore.length + 1 - takeaway);
					
	var strafter = val.substring(mid, val.length + 1);
	strafter = strafter.substring(takeaway, strafter.length + 1);
			
	output = strbefore + ellipsis + strafter;
	
	return output;	
}


/*******************************************************************************
REWIND
Functions to return to search page without hard-coding urls into results pages,
for both 'new search' and 'revise search'
*******************************************************************************/

/*
Rewind() relocates to the original search page when in WebPublisher results.
*/
function Rewind(mode)
{
	if (mode == "fullrecord")
	{
		back_to_block();		
	}
	else if (mode == "remember")
	{
		var rewindUrl = GetQueryParamByKey("BU", dbtw_params);
		rewindUrl = decodeURIComponent(rewindUrl);
		//console.log(rewindUrl);
		if (rewindUrl)
		{		
			if (rewindUrl.indexOf("?") != -1)	
			{
				rewindUrl = rewindUrl.substr(0, rewindUrl.indexOf("?")); //snip query string from end	
			}
			window.location.href = rewindUrl + "?remember=true";
		}
		else
		{
			alert("Cannot rewind: search page URL cannot be found");
		}
	}
	else if (mode == null)
	{
		var rewindUrl = GetQueryParamByKey("BU", dbtw_params);
		rewindUrl = decodeURIComponent(rewindUrl);
		if (rewindUrl)
		{		
			if (rewindUrl.indexOf("?") != -1)	
			{
				rewindUrl = rewindUrl.substr(0, rewindUrl.indexOf("?")); //snip query string from end	
			}
			window.location.href = rewindUrl;
		}
		else
		{
			alert("Cannot rewind: search page URL cannot be found");
		}
	}
}


/********************
SEE ALSO
Functions to create see-also links from WebPublisher content
********************/

/*
SeeAlso() creates see-also links from field content; avoids triple trick and '--' problem in html comments.
Multiple entries okay.
Separator text must be: |split|.
Does not allow carriage returns.
*/

function SeeAlso(FieldContent, FieldName, Separator)
{
	var SplitChar = "|split|";
	var FieldValues = [];
	var i = 0;
	var Str = '';
	var Path = window.location.pathname;
	
	FieldValues = FieldContent.split(SplitChar);
	for (i=0;i<FieldValues.length;i++)
	{
		if (Str.length > 0)
		{
			Str += Separator;	
		}
		Str += '<a href=\"';
		Str += Path;
		Str += CreateSeeAlsoQuery(FieldValues[i], FieldName);
		Str += '\">';
		Str += FieldValues[i];
		Str += '</a>';
	}
	document.write(Str);
}

function CreateSeeAlsoQuery(value, field)
{
	var SeeAlsoParams = dbtw_params.unescapeHTML();
	var Query =  "?AC=SEE_ALSO&QF0=" + field + "&QI0==" + encodeURIComponent("\"" + value + "\"") + SeeAlsoParams;
	return Query;
}

/************************
LINK FINDER
Functions to activate URLs as hyperlinks within text blocks.
************************/

/*
FindLinks() finds URLS within a block of text, and wraps them in anchor tags to activate
them as hyperlinks.
SourceID: ID of element that contains text with URLs to activate.
TargetID: ID of element to place text with activated URLs
maxLength: max no. of URL chars to show in the anchor text attribute (null = unlimited)
*/

function FindLinks(SourceID, TargetID, maxLength)
{
	
	var source = document.getElementById(SourceID);
	var target = document.getElementById(TargetID);
	
	if (source && target)
	{
	    var regex = /(http|https|ftp)\:\/\/([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&%\$\-]+)*@)?((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+(\.[a-zA-Z]{2,4})?)(\:[0-9]+)?(\/[^\/\s]*)*([^\.\,\s])/g;
	    var txt;
	    if (source.innerHTML)
	    {
		    txt = source.innerHTML;
	    }
	    else if (source.value)
	    {
		    txt = source.value;
	    }
    	
	    var foundurl = txt.match(regex);
    	  
	    if (foundurl != null)
	    {
		    var snipA = "";
		    var snipZ = "";
		    var i = 0;
    		
		    for (i=0;i<foundurl.length;i++)
		    {
		      snipA = txt.substr(0, txt.indexOf(foundurl[i], snipA.length));
		      snipZ = txt.substr((snipA.length + foundurl[i].length), txt.length);
		      snipA = snipA + CreateUrlLink(foundurl[i], maxLength);
		      txt = snipA + snipZ;
		    }
    		
	  	    target.innerHTML = txt;
	    }
	}
}

function CreateUrlLink(myUrl, maxLength)
{
	var regex = /\w*\:\/\//; // find [protocol://]
	var urltext = myUrl;
	var foundprotocol = myUrl.match(regex);
	
	if (foundprotocol == null)
	{
		myUrl = "http://" + myUrl;	
	}
	
	if (maxLength != null)
	{
		urltext = TrimMid(urltext, maxLength, "...");		
	}
	
	var myLink = "";
	myLink += "<a href='";
	myLink += myUrl;
	myLink += "'>";
	myLink += urltext;
	myLink += "</a>";
	
	return myLink;
}

/***********************
 BUILD REPORT CHOICES
***********************/

function BuildReportChoices(targetID, reportsToAdd)
{
	var reports = document.getElementById(targetID);
    if (reports)
    {
        var mRF = dbtw_params.match(/RF=([^&]+)/);
        var RF = mRF[1];
        
        for (var i = 0; i < reportsToAdd.length; i++)
        {
            var val = reportsToAdd[i].substr(0, reportsToAdd[i].indexOf("|"));
            var txt = reportsToAdd[i].substr(reportsToAdd[i].indexOf("|")+1);
            var opt = new Option(txt, val);
            if (val == RF)
            {
                opt.selected = true;
            }
            reports.options[reports.options.length] = opt;   
        }
    }
}