// $Id: tools.js,v 1.19 2009/09/29 20:57:15 dharris Exp $

// adjust the window location to prefix + where, but only if where has
// something in it
function doJumpTo(where, prefix) {
  var theval = where.options[where.selectedIndex].value;
  if (theval.length > 0)
    window.location.href = prefix + theval;
}

// this function checks a bill number entry text area after it changes (used on
// alert wizard).  If a list is selected, deselect that since the contents of the
// list are changing and the list shouldn't be related any more.
function billNumberEntryChanged(field) {
  if (document.alertTaskflowForm && document.alertTaskflowForm.myblists) {
    document.alertTaskflowForm.myblists.selectedIndex = 0; // bills edited, reset selected list
  }
  var normbills = validateBillNumbers(field.value);
  if (normbills == null)
    return false;
  field.value = normbills;
  return true;
}

// This function accepts one to many incoming bill numbers,
// normalizes them, and then checks to make sure they're valid
// It returns null if there is a problemo or the normalized
// bills if everything is hunky-dorey
function validateBillNumbers(incoming) {
  var splitre = new RegExp("[ ,\n\r\t.;]+");
  var thenumbers = "0123456789";
  // split the value and validate each one
  var valre = new RegExp(
      "^(HR|HRES|HCONRES|HJRES|TD|SRES|SCONRES|SJRES|S|DSAPPS|DS|DSJRES|DSCONRES|DSRES|DHAPPS|DHR|DHJRES|DHCONRES|DHRES)[0-9]{1,4}(\\-[0-9]{1,4})?$", "i");

  // the first pass using splitre will be used to normalize the bills
  var thebills = incoming.toUpperCase().split(splitre);
  var thenewvalue = "";
  for (n = 0; n < thebills.length; n++) {
    if (n > 0) {
      // get the last char of the previous element
      lastcharprev = thebills[n - 1].substr(thebills[n-1].length - 1);
      if (thenumbers.indexOf(lastcharprev) > -1) {
        thenewvalue = thenewvalue + " ";
      }
    }
    thenewvalue = thenewvalue + thebills[n];
  }

  // the second pass validates the normalized bill numbers
  thebills = thenewvalue.split(splitre);
  thenewvalue = "";
  for (n = 0; n < thebills.length; n++) {
    if (thebills[n] == "")
      continue;
    if (!valre.test(thebills[n])) {
      alert("Error: >" + thebills[n] + "< is not a valid bill number.");
      return null;
    }
    thenewvalue = (thenewvalue.length == 0 ? thebills[n] :
        thenewvalue + " " + thebills[n]); 
  }
  return thenewvalue;
}

/**
 * Author: Mark Kennedy
 *  Removes leading and trailing whitespace from a string
 */
function trimString( s ) {
  // Check to ensure that something was passed in
  if( s ) {
    s = s.replace( /^\s*/, "" );
    s = s.replace( /\s*$/, "" );
    return s;
  } else {
    return '';
  }
}

// URL decode the provided string
function URLDecode(psEncodeString)
{
  // Create a regular expression to search all +s in the string
  var lsRegExp = /\+/g;
  // Return the decoded string
  return unescape(String(psEncodeString).replace(lsRegExp, " "));
}

//remembermyhome
function remembermyhome(page) {
  alert('You have selected this page as your starting page.');
  document.location = this.document.contextUri + "/remembermyhome.do?page="+page;
}

/*function popUpDebug(message){
  alert(message);
}*/

function popDnDebug(message){
  alert(message);
}

function popUpDebug(message){
    document.write('<div style="border: 1px solid rgb(73, 116, 42); ');
    document.write('background: rgb(164, 185, 148) none repeat scroll 0%; ');
    document.write('position: absolute; ');
    document.write('-moz-background-clip: initial; ');
    document.write('-moz-background-origin: initial; ');
    document.write('-moz-background-inline-policy: initial; ');
    document.write('width: 148px; top: 42px; left: 364px; ');
    document.write('z-index: 52; ');
    document.write('visibility: visible;" ');
    document.write('id="debug1" ');
    document.write('tabindex="1">'+message+'</div>');
}

/**
 * Opens a given resource in the main window,
 * leaving the pop-up open and having focus..
 */
function goMain(url) {
   var origWindow = window.opener;
   var targetURL = url;

   origWindow.location.href = targetURL;
   origWindow.focus();
   
}

/**
 * Displays alert dialog box to notify user
 * that links are not active in Alert samples.
 */
function alertSampleMessage() {
  alert("This link is for display purposes only. It works in the actual alert e-mails.");
}

/**
 * getWindowSize
 * Returns the height and width of the browser window
 * (this does NOT return the size of document)
 */
function getWindowSize()
{
	var pageWidth;
  var pageHeight;

  // this portion from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
  if( typeof( window.innerWidth ) == 'number' )
  {
    //Non-IE
    pageWidth = window.innerWidth;
    pageHeight = window.innerHeight;
  }
  else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
  {
    //IE 6+ in 'standards compliant mode'
    pageWidth = document.documentElement.clientWidth;
    pageHeight = document.documentElement.clientHeight;
  }
  else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
  {
    //IE 4 compatible
    pageWidth = document.body.clientWidth;
    pageHeight = document.body.clientHeight;
  }
	
	return { "width" : pageWidth, "height" : pageHeight };
}

/**
 * getElementPos
 * Returns the absolute position of an element.
 * from quirksmode.org. 
 */ 
function getElementPos(obj){
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
		while (obj = obj.offsetParent);
		return [curleft, curtop];
	}
}

/**
 * PopupWindow
 * Used to create a custom popup window.
 * currently used by LawTrack only.
 */  
function PopupWindow(url, config)
{
	this.win;
	this.config = config || {};	

	// set defaults
	this.config.name = this.config.name || 'popupWindow';
	if(this.config.resizable != true)
	{
		this.config.resizable = '';
	}

	if(this.config.scrollbars != true)
	{
		this.config.scrollbars = '';
	}

	this.config.width = this.config.width || 750;
	this.config.height = this.config.height || 400;
	
	if(url != null)
	{
  	this.show(url)
  }
}

function PopupWindow_show(url)
{
	var opts = 'width=' + this.config.width + ',height=' + this.config.height;
	
	opts += ',resizable=';
	if(this.config.resizable == true)
	{
		opts += 'yes';
	}
	else
	{
		opts += 'no';
	}
	
	opts += ',scrollbars=';
	if(this.config.scrollbars == true)
	{
		opts += 'yes';
	}
	else
	{
		opts += 'no';
	}
	
	this.win = window.open(url, this.config.name,opts);
	this.win.focus();
}

PopupWindow.prototype.show = PopupWindow_show;

/**
 * PromptTextbox
 * from: http://webservices.blog.gustavus.edu/2008/06/23/text-input-example-text-with-jquery/
 * adapted and translated to prototype.js 
 */
//

var PromptTextField = {}

PromptTextField.switchText = function(fieldId)
{
	var f = $(fieldId);
	if ($F(fieldId) == f.getAttribute('title'))
	{
		f.value = '';
		f.removeClassName('prompt-text-field');	
	}
	else if ($F(fieldId).strip() == '')
	{
		f.value = f.getAttribute('title');
		f.addClassName('prompt-text-field');
	}
	else if($F(fieldId).strip() != '') // if something other than user changes field's value, like another form field that populates the text field
	{
		f.removeClassName('prompt-text-field');
	}
}

PromptTextField.onFormSubmit = function(fieldId)
{
		if($F(fieldId) == $(fieldId).getAttribute('title'))
		{
			$(fieldId).value = '';
		}
}

PromptTextField.init = function(formId,fieldId)
{
	var f = $(fieldId);
	if($F(fieldId).strip() == '')
	{
		f.value = f.getAttribute('title');
	} 
	if(f.value == f.getAttribute('title'))
	{
		f.addClassName('prompt-text-field');		
	} 

	var func = function()
	{
		PromptTextField.switchText(fieldId);
	}
	f.observe('focus',func);
	f.observe('blur',func);
	
	var onFormSubmit = function()
	{
		PromptTextField.onFormSubmit(fieldId);
	}
	
	$(formId).observe('submit',onFormSubmit);
}
