/***********************************************************************
 * JavaScript Document
 * Authors: Johnny Newberry & Ilene Jones
 * ©2007-2008 AAA ®All Rights Reserved
 ***********************************************************************
 * common.js
 * $Revision: 74 $
 * $Date: 10/07/09 12:33p $
 * $Author: Jlafrate $
 ***********************************************************************/
/* @desc AAA wrapper */
var AAA;
if (!AAA) AAA = {};
/* @desc AAA Widget wrapper */
if (!AAA.Widget) AAA.Widget = {};

//Let's tell javascript it has a contains function
//so we don't have to write the indexOf stuff for each item
//we want to check...it's a very useful function!
//
// Keep in mind, IE does not allow for Object.prototype ... as annoying as that is.
//
String.prototype.contains = function(t) {
	return this.indexOf(t) >= 0 ? true : false;
}
String.prototype.trim = function(){
	return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))
}
String.prototype.startsWith = function(str) {
	return (this.match("^"+str)==str)
}
String.prototype.endsWith = function(str) {
	return (this.match(str+"$")==str)
}

/************************************************************
 * A VERY slim version of the onload event listener.
 * to use: window.onDomReady(function(){alert("dom ready")});
 ************************************************************/

/* Dynamically Load CSS or Javascript files into the header */
function dynaLoad(filename, filetype){
	/* check to see if the file has already been loaded */
//	var headerTags = document.getElementsByTagName(”head”)[0];
//	for( i = 0; i <= headerTags.length; i++ ) {
//		if(headerTags[i]) {
//		}
//	}
	/* load the file */
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref);
}
//Function to show or hide an element based on its current state.
//Function will also change the background image arrow to an open/closed
//state if that element is passed in, else it will do nothing.
//Called from: Air Results
//Called from: Air Results, Air Results - Multi Dest
function eleShowHide(divToOpen, changeArrow){

	var divEle = document.getElementById(divToOpen);

	if (divEle.style.display == 'none' || divEle.style.display == ''){
		divEle.style.display = 'block';
		if(changeArrow != '' || changeArrow != null){
			changeArrow.className = 'itinDetailLinkOpen';
		}
	}else{
		divEle.style.display = 'none';
		if(changeArrow != '' || changeArrow != null){
			changeArrow.className = 'itinDetailLinkClosed';
		}
	}
}

//Function that can take either an div element or a span element
//and open or close it based.  Function loops the div elements array
//of the document and loops it looking for elements that contain that contain
//the substring SubDetail.  If ele contains substring then calls eleShowHide to
//to have the state set to block.  May at some point make this a generic call.
//Called from: Air Results, Air Results - Multi Dest
function expandSection(){

	var divEle = document.getElementsByTagName('div');
	var spanEle = document.getElementsByTagName('span');

		for(var i=0;i<divEle.length;i++){
			if (divEle[i].id.contains("SubDetail")){
				divEle[i].style.display = 'block';
			}
		}

		for(var i=0;i<spanEle.length;i++){
			if (spanEle[i].id.contains("ItineraryControl")){
				spanEle[i].className = 'itinDetailLinkOpen';
			}
		}
}


/****************************************************************************************
	Author: Ilene Jones
	©2008 AAA ®All Rights Reserved

	toggle the show/hide on my trips

This will work with any ID's, but expected myTrips elements for below should be:
	showAirCheck		showAirCheckSpacer		showAirShow		showAirShowSpacer		showAirAdd
	showHotelCheck	showHotelCheckSpacer	showHotelShow	showHotelShowSpacer	showHotelAdd
	showCarCheck		showCarCheckSpacer		showCarShow		showCarShowSpacer		showCarAdd

	sightseeing,
	destinationInfo,
	searchMemberDiscounts,

	loggedIn,
	welcomeBackMsg,
	viewAllTrips

	@params
		element: DOM element id
		bToggle: boolean (true/false)

****************************************/
function toggleShowHide(element, bToggle) {
	var obj = document.getElementById(element);
	if(typeof(obj) != 'undefined' && typeof(bToggle) != 'undefined'){
		// sometimes bToggle is sent as a string instead of an actual boolean.  Translate.
		if(typeof(bToggle) == 'string' && bToggle.toLowerCase() == 'true') { bToggle = true; }
		if(typeof(bToggle) == 'string' && bToggle.toLowerCase() == 'false') { bToggle = false; }
		// The actual work of toggling
		if(bToggle) {
			obj.style.display = 'block';
		} else {
			obj.style.display = 'none';
		}
	}
}

/********************************************************************
	Even if both elements are turned off, this will turn the first one
	off (effectively doing nothing) and turn the 2nd element on

	@param element1 off
	@param element2 on
 ********************************************************************/
function toggleDivDisplay(element1, element2) {
	var obj1 = document.getElementById(element1);
	var obj2 = document.getElementById(element2);
	if ((obj1 != null) && (obj2 != null) && (typeof obj1 != 'undefined') && (typeof obj2 != 'undefined')){
		obj1.style.display = 'none';
		obj2.style.display = 'block';
	}
}


/********************************************************************
	Show and Hide elements - used in Car Module.
 ********************************************************************/
function show(id){
	if (document.getElementById){
		obj = document.getElementById(id);
		obj.style.display = "";
	}
}
function hide(id){
	if (document.getElementById){
		obj = document.getElementById(id);
		obj.style.display = "none";
	}
}


/********************************************************************
	Even if both elements are turned off, this will turn the first one
	off (effectively doing nothing) and turn the 2nd element on
	and gives the 2nd element focus

	@param element1 off
	@param element2 on and receives focus
 ********************************************************************/
function toggleDivDisplayWithFocus(element1, element2) {
	toggleDivDisplay(element1, element2);
	var obj2 = document.getElementById(element2);
	if (typeof obj2 != 'undefined'){
		obj2.focus();
	}
}

/********************************************************************
	This function will add or remove a class from an element, allowing
	you to change display on the fly using the DOM.

@param element DOM element
@param bToggleOn class name to add to DOM element
@param bToggleOff class name to remove from the DOM element

Because the parameters are part of an array, all are expected.
Pass an empty string to null a parameter.
ie: toggleClassName('myElement','','visible');
********************************************************************/
function toggleClassName(element, bToggleOn, bToggleOff) {
	var obj = document.getElementById(element);
	toggleObjClassName(obj,bToggleOn,bToggleOff);
}
/* same as above, but expects an object, not an element name */
function toggleObjClassName(obj, bToggleOn, bToggleOff) {
	if ((typeof obj != 'undefined') && (typeof bToggleOn != 'undefined' || typeof bToggleOff != 'undefined')){
		removeClassName(obj,bToggleOff);
		addClassName(obj,bToggleOn);
	}
}

/**************************************************************************
 * Enable/Disable Button - Used in Driving Directions & Air
 *
 *        @desc: enable and disable a button's functionality, requiring a
 *							 user to wait for a page reload, or other action before
 *							 continuing.
 * 			@params: button object
 * @assumptions: There is only one button being enabled/disabled at a time
 **************************************************************************/
function enableButton(button){
    mybtn.disabled=false;
}
function disableButton(button){
    window.mybtn=button;
    mybtn.disabled=true;
}

/********************************************************************
	These two functions were grabbed from the Spry framework.  They
	are the power behind the add/remove class names.

@params
	ele: DOM element
	className: class name to add to the DOM element

	each calls directly to Spry.Widet.Utils.function
********************************************************************/
function addClassName(ele, className)
{
	return Spry.Widget.Utils.addClassName(ele, className);
};

function removeClassName(ele, className)
{
	return Spry.Widget.Utils.removeClassName(ele, className);
};

function hasClassName(ele, className)
{
	return Spry.Widget.Utils.hasClassName(ele, className);
};
/********************************************************************
 getposOffset - Get the absolute position offset of the element
@params
	what: DOM element
	offsettype: default = left
********************************************************************/

function getposOffset(what, offsettype){
	var totaloffset=(offsettype=="left") ? what.offsetLeft : what.offsetTop;
	var parentEl=what.offsetParent;
	while (parentEl!=null){
		totaloffset=(offsettype=="left") ? totaloffset+parentEl.offsetLeft
										 : totaloffset+parentEl.offsetTop;
		parentEl=parentEl.offsetParent;
	}
	return totaloffset;
}

/************************************************************************
 *  @params: popUpName = "popUp";
 * 					 keyValueArray = [[key,value],[key,value]];
 *    @desc: sets the YUI parameters for a specific popup which has already
 *           been created and rendered, and re-renders the popup.
 *
 * @example: setPopUp("popUp", { key: value,key: value });
 *
 * @assumptions:
 *				YAHOO Libraries are already loaded and available
 *				YAHOO.popup exists already
 * @pre-req:
 *				/jsincludes/yahoo-dom-event.js
 *				/jsincludes/container-min.js
 ************************************************************************/

function setPopUp(popUpName,optionsObj) {
	// We expect the popup to be defined by this point
	if(!optionsObj || typeof(YAHOO.popup) == 'undefined' ||
		typeof(YAHOO.popup.container[popUpName]) == 'undefined')
			return 0;
	for (var optionName in optionsObj)
	{
		if(typeof(optionsObj[optionName]) != 'undefined')
			YAHOO.popup.container[popUpName].cfg.setProperty(optionName,optionsObj[optionName]);
	}
	YAHOO.popup.container[popUpName].render();

}
/************************************************************************
 *  @params: URL = "http://national.aaa.com"
 *    @desc: sets the iFrame to a specific needed URL on the fly
 *
 * @example: popUp("http://national.aaa.com");
 *
 * @assumptions:
 *				YAHOO Libraries are already loaded and available
 *				using YAHOO.popup.container.popUp as object name for iFrame popup
 *        YAHOO popup object created and available on the page
 * @pre-req:
 *				/jsincludes/yahoo-dom-event.js
 *				/jsincludes/container-min.js
 ************************************************************************/

function popUp(strURL) {
	YAHOO.util.Dom.get('iFrameBody').src = strURL;
	YAHOO.popup.container.popUp.show();
}

/************************************************************************
 *  @params: select Object
 *    @desc: getSelectedValue of a select obj
 ************************************************************************/
function getSelectedValue( selectObj ) {
    var i=0;
    for ( i=0; i<selectObj.options.length; i++ ) {
        var option = selectObj.options[i];
        if ( option.selected ) {
            return option.value ;
        }
    }
    return false ;
}

 /**************************************************************************
	* @desc: this is the script that drives the  Zapatec calendar
  **************************************************************************/
function createCalendarPopup(inputFieldValue, buttonValue, dateCheckFunction )
{
    var inputFieldObj = document.getElementById(inputFieldValue);
    AAA.Widget.addEventListener( inputFieldObj, 'blur', function() { fixMMDDYYYY( inputFieldObj ) }, false );
    initBlankPrompt( inputFieldObj, "mm/dd/yyyy" );
	var cal = Zapatec.Calendar.setup({
		weekNumbers : false,
		step : 1,
		electric : false,
		inputField : inputFieldValue,
		button : buttonValue,
		eventName: "focus",
		closeEventName: "blur",
		ifFormat : "%m/%d/%Y",
		daFormat : "%m/%d/%Y",
		noHelp : true,
		disableFdowChange : true,
		captureKeystrokes : false,
		align : "bR",
		noCloseButton : true,
		disableYearNav : true,
		disableFunc : dateCheckFunction,
        onSelect: function( arg1, dateStr ) {
                     //alert( 'arg1=' + arg1==window.calendar.params.inputField );
                     window.calendar.params.inputField.value = dateStr ;
                     AAA.Widget.adjustDate(window.calendar.params.inputField );
                     window.calendar.hide();
                     gotoNextField( window.calendar.params.inputField );
                  }
	});
	// add these listeners again after creating the calendar so that we are sure that these
	// listeners get called.  (needed for chrome and safari)
    AAA.Widget.addEventListener( inputFieldObj, 'blur', function() { fixMMDDYYYY( inputFieldObj ) }, false );
    initBlankPrompt( inputFieldObj, "mm/dd/yyyy" );
	return cal;
}


 /**************************************************************************
	@desc: this is the script that drives the  Zapatec calendar
	@param inputFieldValue  The input field id for this calendar
	@param buttonValue the button associated with the input field
	@param onUpdateValue the function you would like to run after an update of the calendar
  **************************************************************************/
function createCalendarPopupWithOnUpdate(inputFieldValue, buttonValue, onUpdateValue)
{
	Zapatec.Calendar.setup({
		onUpdate: onUpdateValue,
		weekNumbers : false,
		step : 1,
		electric : false,
		inputField : inputFieldValue,
		button : buttonValue,
		ifFormat : "%m/%d/%Y",
		daFormat : "%m/%d/%Y",
		noHelp : true,
		disableFdowChange : true,
		captureKeystrokes : false,
		align : "bR",
		noCloseButton : true,
		disableYearNav : true,
		dateStatusFunc : function (date) {
			var flag = true;
			flag = ((new Date().getTime() - Date.DAY) > date.getTime());
			if (flag) return flag;
			flag = (date.getTime() > (new Date().getTime() + (Date.DAY * 331)));
			return flag;
		}
	});
}

function createDOBCalendarPopup(inputFieldValue, buttonValue)
{
	var curdate = new Date();
	var year = curdate.getYear() + 1900;
	var month = curdate.getMonth() + 1;
	if (month < 10) {month = '0' + month;}
	var maxDate = year + '.' + month;

	Zapatec.Calendar.setup({
	weekNumbers : false,
	step : 1,
	electric : false,
	inputField : inputFieldValue,
	button : buttonValue,
	ifFormat : "%m/%d/%Y",
	daFormat : "%m/%d/%Y",
	noHelp : true,
	disableFdowChange : true,
	captureKeystrokes : false,
	align : "bR",
	noCloseButton : true,
	disableYearNav : false,
	range  : [1900.01, maxDate]
	});
}

/******************************************************************/
/* Create the AAA object and attach the calendar to it            */
/* This has the simple function of taking in the two input fields */
/* and making the 1st field update the 2nd one on blur.           */
/* @param fromField - field we're checking on blur on             */
/* @param toField - field we're updating if it's not a date       */
/******************************************************************/
AAA.Widget.CalendarPair = function(fromField, toField, opts)
{
    var	fromFieldObj ;
    if ( fromField.tagName ) {
	    fromFieldObj = fromField ;
	}
	else {
		fromFieldObj = document.getElementById(fromField);
     	createCalendarPopup( fromField, fromField,
  	        ((opts && opts.allowSameDayBooking) ? this.beforeToday : this.beforeTomorrow) );
	}

	var toFieldObj ;
	if ( toField.tagName ) {
		toFieldObj = toField ;
	}
	else {
		toFieldObj = document.getElementById(toField);
        createCalendarPopup( toField, toField,
   	         ((opts && opts.allowSameDayReturn) ? this.beforeFromDate : this.beforeOrOnFromDate ) );
	}


	fromFieldObj.toField = toFieldObj ;
	toFieldObj.fromField = fromFieldObj ;

	fromFieldObj.dateFmt = "%m/%d/%Y";
	fromFieldObj.daysToAdd = 1;
	fromFieldObj.noAdjustment = false;
	fromFieldObj.allowSameDayBooking = false; // "from" date can't be today
	fromFieldObj.allowSameDayReturn = false;  // "to" date can't be the same as "from" date

	var handler = function(e) { return AAA.Widget.adjustDate(eventSource(e)); };
	AAA.Widget.addEventListener(fromFieldObj, 'blur', handler, false);
	AAA.Widget.addEventListener(fromFieldObj, 'update', handler, false);
	AAA.Widget.addEventListener(fromFieldObj, 'change', handler, false);
	this.setOptions(fromFieldObj, opts);
};

// return true if the passed date is before today (or more than 331 days after today)
AAA.Widget.CalendarPair.prototype.beforeToday = function ( date ) {
		var flag = true;
		flag = ((new Date().getTime() - Date.DAY) > date.getTime());
		if (flag) return flag;
		flag = (date.getTime() > (new Date().getTime() + (Date.DAY * 331)));
		return flag;
}

// return true if the passed date is before tomorrow (or more than 331 days after today)
AAA.Widget.CalendarPair.prototype.beforeTomorrow = function ( date ) {
		var flag = true;
		flag = ((new Date().getTime() ) > date.getTime());
		if (flag) return flag;
		flag = (date.getTime() > (new Date().getTime() + (Date.DAY * 331)));
		return flag;
}

AAA.Widget.CalendarPair.prototype.beforeFromDate = function ( date ) {
    debug( 'beforeFromDate' );
    if ( AAA.Widget.CalendarPair.prototype.beforeToday( date ) ) {
        return true ;
    }
    // return true if passed date is less than the fromFieldDate
    var fromDate = this.params.inputField.fromField.parsedDate ;
    if ( fromDate == null ) {
        return false ;
    }
    return ( Math.floor(date.getTime() / Date.DAY) < Math.floor(fromDate.getTime() / Date.DAY) );
}

AAA.Widget.CalendarPair.prototype.beforeOrOnFromDate = function ( date ) {
    debug( 'beforeOrOnFromDate' );
    if ( AAA.Widget.CalendarPair.prototype.beforeToday( date ) ) {
        return true ;
    }
    // return true if passed date is less than or equal to the fromFieldDate
    var fromDate = this.params.inputField.fromField.parsedDate ;
    if ( fromDate == null ) {
        return false ;
    }
    return  Math.floor(date.getTime() / Date.DAY) <= Math.floor(fromDate.getTime() / Date.DAY) ;
}




AAA.Widget.addEventListener = function(element, eventType, handler, capture) {
	try
	{
		if (element.addEventListener)
			element.addEventListener(eventType, handler, capture);
		else if (element.attachEvent)
			element.attachEvent("on" + eventType, handler);
	}
	catch (e) { }
}

function eventSource( e ) {
    return e.srcElement? e.srcElement : e.target;
}
/****************************************************************/
/* This is where the real work happens.  This checks the dates, */
/* does the validations and returns the needed values to the    */
/* form fields                                                  */
/****************************************************************/
AAA.Widget.adjustDate = function(srcEl) {
    //if (window.event) e = window.event;
    debug( 'adjustDate ' + srcEl );

	// There are some cases where we will create the object but never use it
	// in those cases, just return (Air One Way)
	if(srcEl.noAdjustment) {
		return;
	}

	srcEl.parsedDate = Date.parseDate(srcEl.value || srcEl.innerHTML,
								   srcEl.dateFmt);
	if( !srcEl.parsedDate ) {
        debug( 'noFromDate... so do not adjust' );
		return;
	}

    debug( 'parsedDate is ' + srcEl.parsedDate );

	// Get the to field value and the from field values to work with.
	var toFieldValue = srcEl.toField.value || srcEl.toField.innerHTML;
	var toFieldDate = Date.parseDate(toFieldValue, srcEl.dateFmt);

	var minToFieldDate = Date.parseDate(srcEl.value || srcEl.innerHTML,
	   srcEl.dateFmt);
	if ( !srcEl.allowSameDayReturn ) {
	    minToFieldDate.setDate( minToFieldDate.getDate() + 1 );
	}
    //alert( 'minToFieldDate2 is ' + minToFieldDate + 'toFieldDate is ' + toFieldDate + '<=' + (toFieldDate<minToFieldDate));

	if( toFieldValue == srcEl.defaultText || toFieldDate < minToFieldDate ) {
		debug( 'adjusting date' );
		clearBlankPrompt( srcEl.toField );
		// adjust the TO date to be after the FROM date by daysToAdd days.
		var newFieldDate = Date.parseDate(srcEl.value || srcEl.innerHTML, srcEl.dateFmt);
		newFieldDate.setDate( srcEl.parsedDate.getDate() + parseInt(srcEl.daysToAdd) );
		var newToValue = newFieldDate.print(srcEl.dateFmt);
		srcEl.toField.value = newToValue ;
		srcEl.toField.parsedDate = newFieldDate ;
		// This throws a NO_MODIFICATION_ALLOWED DOM Exception in Safari
		if(Zapatec.is_webkit) {
			try {
		        srcEl.toField.innerHTML = newFieldDate.print(srcEl.dateFmt);
			}
			catch (e) { }
        }
        // for multi-dest air reservations, chain adjusting other destinations.
        AAA.Widget.adjustDate( srcEl.toField );
	}
	debug( 'leaving adjustDate' );
}

AAA.Widget.CalendarPair.prototype.setOptions = function(obj, optionsObj, ignoreUndefinedProps)
{
	if (!optionsObj)
		return;
	for (var optionName in optionsObj)
	{
		if (ignoreUndefinedProps && optionsObj[optionName] == undefined)
			continue;
		obj[optionName] = optionsObj[optionName];
	}
};


/* SHOULD be used by TravelInfo, TravelGuides & Hotel  */
/* Clears the value of the input field passed in   */
/* It includes a fix for firefox*/
function clearInput(currentTextBox, otherTextBox)
{
    var textCurr = document.getElementById(currentTextBox);
    var textOther = document.getElementById(otherTextBox);

    if(textCurr.value != '' && textOther.value != ''){
    	textOther.value = ''
    }

    var textCurr = document.getElementById(currentTextBox);
    var textOther = document.getElementById(otherTextBox);

    if(textCurr.value != '' && textOther.value != ''){
    	textOther.value = ''
    }
}

/* Being used by TravelInfo, TravelGuides & Hotel  */
/* disables or enables advanced search options     */
/* element is expected to be the javascript variable for your collapsible panel */
function disableAdvSearchPanel(element)
{
	/* expects advancedSearchOptions or AdvancedSearchOptions */
	window[element].close();
	window[element].disable();
}

/* Being used by TravelInfo, TravelGuides & Hotel  */
/* disables or enables advanced search options     */
/* element is expected to be the javascript variable for your collapsible panel */
function enableAdvSearchPanel(element)
{
	/* expects advancedSearchOptions or AdvancedSearchOptions */
	window[element].enable();
	window[element].open();
}

/***************************************************************************
 * @desc           Clicks the passed in button when enter is pressed
 * @param e
 * @param buttonId ID of the button to click
 ***************************************************************************/
function clickOnEnter( e, buttonId )
{
        var key = 0 ;
        var letter;

        if (window.event && window.event.keyCode )
          key = window.event.keyCode;
        else if (e)
          key = e.which;

        if ( key == 13 ) {
           var button = document.getElementById( buttonId );
           button.focus();
           button.click();
           return false ;
        }
        return true;
}


function gotoNextField( currentInputField ) {

  debug( 'currentInputField.form=' + currentInputField.form);
  var nextField = getNextField( currentInputField );
  debug( 'nextField.id=' + nextField.id );
  
  
  //next field could be a jsf field such as javax.faces.ViewState. Added try/catch on focus.
  try{
	  nextField.focus();
	}catch (err){}

  function getNextField( inputField ) {
       var index = getIndex( inputField );
       var nextIndex = (index+1) % inputField.form.length ;
       return inputField.form[ nextIndex ];
  }
  function getIndex(inputField) {
    var i = 0;
    while (i < inputField.form.length ) {
       if (inputField.form[i] == inputField) {
           return i;
       }
       i++;
    }
    return -1;
  }
}

/***************************************************************************
 * @desc           Removes all children from the object passed in
 * @param obj
 ***************************************************************************/
function removeAllChildren( obj ) {
      while ( obj.hasChildNodes() ) {
            var child = obj.firstChild ;
           obj.removeChild( child );
      }
      obj.innerHTML = '';
}


function boldTextInChildDivs( parentNode, typedText ) {
    typedText = typedText.replace( new RegExp( "&", "gi" ), "&amp;" );
    var children = parentNode.childNodes ;
    for ( var i=0; i<children.length; i++ ) {
        var child = children[i] ;
        if ( child.nodeName == 'div' || child.nodeName == 'DIV' ) {
            boldText( child, typedText );
        }
    }
}




function boldText( obj, searchText ) {
      if ( !searchText || !searchText.length || searchText.length == 0 ) {
           return ;
      }
      var newHtml = '';
      var text = '' + obj.innerHTML;
      if ( text.length == 0 ) {
        return ;
      }

      // remove previously added <b> and </b>
      var regExp = new RegExp( "</?b>", "gi" );
      var text = text.replace( regExp, "" );

      var upText = text.toUpperCase() ;
      var upSearchText = searchText.toUpperCase();

      removeAllChildren( obj );

      var prevPos = 0;
      var matchPos = 0;
      while ( matchPos >= 0 ) {
        matchPos = upText.indexOf( upSearchText, prevPos ) ;
        if ( matchPos >= 0 ) {
            var preText = text.substring( prevPos, matchPos ) ;
            newHtml += preText ;

            var boldedText = text.substring( matchPos, matchPos + searchText.length );
            newHtml += '<b>' + boldedText + '</b>' ;
            prevPos = matchPos + searchText.length ;
        }
      }

      if ( prevPos < text.length ) {
          var finalText = text.substring( prevPos );
          newHtml += finalText ;
      }
      obj.innerHTML = newHtml ;
}

/****************************************************************
	Fixes the close button by moving the box 1 px right
 ****************************************************************/
function fixIECloseButton(element) {
	// IE6 close button is being a pain.  Force the z-index on the close button.
	if(typeof(element) != "object") {
		element = document.getElementById(element);
	}
	element.style.left = parseInt(element.offsetLeft+1)+"px";
}

/****************************************************************
	Gets the total height of the children of an object passed.
	@param element object
 ****************************************************************/
function getElementChildrenTotalHeight(element)
{
	if(!element) return;
	var elementName = element;
	if(typeof(element) != 'object')
		element = document.getElementById(element);
	var childrenHeight = 0;
	var child = element.firstChild;
	while (child)
	{
		if (child.nodeType == 1 /* Node.ELEMENT_NODE */) {
			childrenHeight = childrenHeight + child.scrollHeight;
			//alert('Next Child: '+child.nodeName+' height: '+child.scrollHeight);
		}
		child = child.nextSibling;
	}
	return childrenHeight;
};
/****************************************************************
 * @desc  Used to turn on or off the standard LRP and waiting
 *		images/divs
 * @param elem
 * 		default object or string to set the parameters to
 ****************************************************************/
AAA.Widget.WaitStatus = function(elem)
{
	this.init(elem);
};

AAA.Widget.WaitStatus.prototype.init = function(elem)
{
	// Set the defaults as we know them
	// use waiting.setOptions to override
	this.element = document.getElementById(elem);
	// Used for LRP
	this.bodyContainer = document.body; //document.getElementsByTagName('div')[0];
	this.lrpOverlay = 'lrpOverlay';
	this.lrp = 'lrp';
	this.lrpTopMargin = '200px'; /* keep the LRP above the fold */
	// Used for Spinner
	this.mainContainer = 'mainContent';
	this.spinnerOverlay = 'spinnerOverlay';
	this.spinner = '_viewRoot:status';
	this.activeSpinner = {};
}
/***************************************************************************
	Throw a warning to the console:
 ***************************************************************************
	if ("console" in window)
	  console.warn('DEPRECATED function call to '+ arguments.callee
	  +'\nCalled by:\n'+ arguments.callee.caller );
****/
/***************************************************************************
 * @desc  showLrp
 ***************************************************************************/
AAA.Widget.WaitStatus.prototype.showLrp = function()
{
	if(typeof(this.bodyContainer) == 'undefined' || typeof(this.lrpOverlay) == 'undefined' || typeof(this.lrp) == 'undefined') {
		if ("console" in window)
		  console.warn('Unexpected variables passed:\nbodyContainer: '+this.bodyContainer+'\nlrpOverlay: '+this.lrpOverlay+'\nlrp: '+this.lrp );
		return;
	}
	window.document.body.scroll = 'no';
	document.body.style.overflow = 'hidden';	
	
	this.spinnerType = 'lrp';
	this.showAjaxSpinner(this.bodyContainer, this.lrpOverlay, this.lrp );
	show(this.lrp);
	this.spinnerType = 'undefined';

	// This should cover the whole body, not just the section.
	var overlay = document.getElementById(this.lrpOverlay);

	if(overlay){
		if (document.documentElement){
			theTop = document.documentElement.scrollTop;
		} else if (document.body) {
			theTop = document.body.scrollTop;
		}
		overlay.style.left = 0 + 'px' ;			
		overlay.style.top = theTop + 'px' ;		
	}
	overlay.style.width=document.body.scrollWidth+'px';
	overlay.style.height=document.body.scrollHeight+'px';
}

AAA.Widget.WaitStatus.prototype.hideLrp = function()
{
	this.spinnerType = 'lrp';
	this.hideAjaxSpinner(this.bodyContainer, this.lrpOverlay, this.lrp);
	this.spinnerType = 'undefined';

	window.document.body.scroll = 'auto';
	document.body.style.overflow = 'auto';
}
/**
 * @desc Shows the ajax spinner with default settings
 */
AAA.Widget.WaitStatus.prototype.showDefaultSpinner = function()
{
	this.spinnerType = 'default';
	this.showAjaxSpinner(this.mainContainer, this.spinnerOverlay, this.spinner);
	this.spinnerType = 'undefined';
}
/***************************************************************************
 * @desc  Shows the ajax spinner using the passed in parameters to set up
 *		the overlay, element and spinner DOM elements.
 * @param elem (mainContent)
 * 		contentDiv that we are covering up / overlaying
 * @param overlay (spinnerOverlay)
 *		overlayDiv that we are using for the background color, size, etc.
 * @param spinner
 *		spinnerDiv which contains the spinner image
 ***************************************************************************/
AAA.Widget.WaitStatus.prototype.showAjaxSpinner = function(elem, overlay, spinner, e)
{
	// We use contentDiv to get the measurements of what we're overlaying
	var contentDiv = elem;
	if(typeof(contentDiv) != 'object') {
		contentDiv = document.getElementById(elem);
	}
	if(typeof(contentDiv) != 'object') {
		throw('contentDiv was passed '+contentDiv+' which is not a div id\nThe LRP will not display.');
		return;
	}
	var childrenHeight = getElementChildrenTotalHeight(contentDiv);
	// We use overlayDiv to set the measurements for the smokey overlay box
	var overlayDiv = document.getElementById(overlay);
        if ( overlayDiv == null ) {
             alert( 'did not find element by id:' + overlay );
        }
	// This is our spinner/lrp and any content inside it.
	var spinnerDiv = document.getElementById(spinner);

	var sWidth = contentDiv.scrollWidth;
	var sHeight = contentDiv.scrollHeight;
	if(!sHeight) {
		var mainContainer = document.getElementById('mainContainer');
		sHeight = mainContainer.scrollHeight;
		sWidth = mainContainer.scrollWidth;
	}
	overlayDiv.style.height = contentDiv.scrollHeight+"px";
	overlayDiv.style.width = contentDiv.scrollWidth+"px";
	overlayDiv.style.left = getposOffset( contentDiv, "left" )  + "px";
	overlayDiv.style.top = getposOffset( contentDiv, "top" ) + "px";
	if( this.spinnerType == 'lrp' ) {
		spinnerDiv.style.top = this.lrpTopMargin
        	spinnerDiv.style.left = parseInt(sWidth/3)+"px";
	}

	addClassName(overlayDiv, 'showSpinner');
	removeClassName(overlayDiv, 'hidden');
	show(overlay);
	addClassName(contentDiv,'masked');
	removeClassName(spinnerDiv, 'hidden');
	show(spinner);

	this.activeSpinner = [ contentDiv, overlayDiv, spinnerDiv ];
}

AAA.Widget.WaitStatus.prototype.hideActiveSpinner = function()
{
	if(this.activeSpinner.length > 0) {
		this.spinnerType = 'active';
		this.hideAjaxSpinner(this.activeSpinner);
		this.spinnerType = 'undefined';
	}
}

/***************************************************************************
 * @desc All the same params as showAjaxSpinner so we can remove
 *		 our class names dynamically.
 ***************************************************************************/
AAA.Widget.WaitStatus.prototype.hideDefaultSpinner = function()
{
	this.spinnerType = 'default';
	this.hideAjaxSpinner('mainContent','spinnerOverlay','_viewRoot:status');
	this.spinnerType = 'undefined';
}
/***************************************************************************
 * @desc All the same params as showAjaxSpinner so we can remove
 *		 our class names dynamically.
 * @param contentDiv (mainContent)
 * 		contentDiv that we are covering up / overlaying
 * @param overlay (spinnerOverlay)
 *		overlayDiv that we are using for the background color, size, etc.
 * @param spinner
 *		spinnerDiv which contains the spinner image
 ***************************************************************************/
AAA.Widget.WaitStatus.prototype.hideAjaxSpinner = function(contentDiv, overlayDiv, spinnerDiv)
{
	if(typeof(overlayDiv) == 'string') {
		overlayDiv = document.getElementById(overlayDiv);
	}
	overlayDiv.height = 0;
	overlayDiv.width = 0;
	if(hasClassName(overlayDiv, 'showSpinner')) {
		removeClassName(overlayDiv, 'showSpinner');
	}
	addClassName(overlayDiv,'hidden');

	if(typeof(spinnerDiv) == 'string') {
		spinnerDiv = document.getElementById(spinnerDiv);
	}
	addClassName(spinnerDiv,'hidden');

	if(typeof(contentDiv) == 'string') {
		contentDiv = document.getElementById(contentDiv);
	}
	if(hasClassName(contentDiv, 'yui-skin-sam'))
		removeClassName(contentDiv, 'yui-skin-sam');
	if(hasClassName(contentDiv, 'masked'))
		removeClassName(contentDiv, 'masked');
}

AAA.Widget.WaitStatus.addEventListener = function(element, eventType, handler, capture) {
	try
	{
		if (element.addEventListener)
			element.addEventListener(eventType, handler, capture);
		else if (element.attachEvent)
			element.attachEvent("on" + eventType, handler);
	}
	catch (e) { }
}
/***************************************************************************
 * @desc All the same params as showAjaxSpinner, and adds a listener to a button as well.
 * @param button
 * 		the button to assign the listener to
 * @param contentDiv
 * 		contentDiv that we are covering up / overlaying
 * @param overlay
 *		overlayDiv that we are using for the background color, size, etc.
 * @param spinner
 *		spinnerDiv which contains the spinner image
 ***************************************************************************/
AAA.Widget.WaitStatus.prototype.addAjaxButton = function(button, contentDiv, overlay, spinner) {

	if(typeof(button) == 'string') {
		button = document.getElementById(button);
	}
	self = this;
	handler = function(e) { return self.showAjaxSpinner(button, contentDiv, overlay, spinner, e); };
	capture = false;

	AAA.Widget.WaitStatus.addEventListener(element, 'click', handler, capture);
}
/**
 * @desc  Define the LRP functions as functions of AAA.Widget.WaitStatus
 */

// Pausing and waiting for the page to load before
// setting up the status.

function initWaiting() {
	document.waitingStatus = new AAA.Widget.WaitStatus('lrp');
};
function showLrp() {
	document.waitingStatus.showLrp();
}
function hideLrp() {
	document.waitingStatus.hideLrp();
}
function showDefaultSpinner() {
	document.waitingStatus.showDefaultSpinner();
}
function showAjaxSpinner(elem, overlay, spinner) {
	document.waitingStatus.showAjaxSpinner(elem, overlay, spinner);
}
function hideDefaultSpinner() {
	document.waitingStatus.hideDefaultSpinner();
}
function hideAjaxSpinner(elem, overlay, spinner) {
	document.waitingStatus.hideAjaxSpinner(elem, overlay, spinner);
}
if (typeof(YAHOO) == 'object') {
	YAHOO.util.Event.addListener(window, "load", initWaiting);
} else {
	setTimeout("YAHOO.util.Event.addListener(window, 'load', initWaiting);",300);
}


/**
 * @desc  Takes a URL query string and parses it for specific parameters
 * @param queryString Querystring without the leading ?
 */
var QueryString = {};
QueryString = function(qs){
	this.params = {};
	// remove the ? from the query string
	if(qs == null) {
		qs = window.location.search.substring(1, window.location.search.length);
	}
	if(qs.length == 0) return;

	var pairs = qs.split('&');
	for (var i = 0; i < pairs.length; i++) {
		var pair = pairs[i].split('=');
		var name = decodeURIComponent(pair[0]);
		var value = (pair.length==2) ? decodeURIComponent(pair[1]) : name;

		this.params[name] = value;
	}
}
/**
 * @desc  		  Returns the value based on the key, or default
 * @param key 	  The name of the parameter to return the value of
 * @param default The default parameter if value is null
 */
QueryString.prototype.get = function(key, _default) {
	var value = this.params[key];
	return (value != null) ? value : _default;
}

/**
 * @desc  		  Returns the value based on the key, or default
 * @param key 	  Check to see if query string contains key
 */
QueryString.prototype.contains = function(key) {
	var value = this.params[key];
	return (value != null);
}

function unhidePopup(id) {
	ele = document.getElementById(id);
	if(hasClassName(ele,"hidden")) {
		removeClassName(id, "hidden");
	}
}

// PopUpCreator
/************************************************************************
 *  @desc    Assumes Yahoo is instantiated already, creates YAHOO popup.
 *  @params  contentPanel = div id of the popup;
 *
 * @example  page11 = PopUpCreator("pagel1"{ height: "100px", width: "100px", header: "Flight Detail for:"});
 *           <button onclick="javascript:page11.show();">Show Flight Details</button>
 * @assumptions
 *				YAHOO Libraries are already loaded and available
 * @pre-req
 *				/jsincludes/yahoo-dom-event.js
 *				/jsincludes/container-min.js
 * @Notes  Firebug causes an NSI exception on the page.
 *         Error text: Component returned failure code: 0x80470002 (NS_BASE_STREAM_CLOSED) [nsIScriptableInputStream.available]
 *		   Validation: http://tech.groups.yahoo.com/group/ydn-javascript/message/17047
 *
 ************************************************************************/
var PopUpCreator;
if(!PopUpCreator) PopUpCreator = {};
/**
 * @desc PopUpCreator constructor
 * @param element  The element (div id) used to attach the YUI popup to the DOM
 * @param opts     The options passed into the constructor.  See init for options.
 */

PopUpCreator = function(element, opts){
	this.init(element);
	this.setOptions(this.setting, opts);
	this.setPrivateOptions();
}
/**
 * @desc Initialization of the PopUpCreator
 * @param element  The element (div id) used to attach the YUI popup to the DOM
 */
PopUpCreator.prototype.init = function(element) {
	this.setting = {};
	this.setting.width = "500px";
	this.setting.height = "300px";
	this.setting.close = true;
	this.setting.visible = false;
	this.setting.scrollbar = true;
	this.setting.fixedcenter = false;
	this.setting.draggable = true;
	this.setting.iframe = true;
	this.setting.context = element;
	this.setting.showdelay = '200'; /* yui default */
	this.setting.hidedelay = '500'; /* yui default */
	this.setting.autodismissdelay = '5000'; /* yui default */
	this.element = element
	this.elementName = element.id;
	this.offsetLeft = 20;
	this.offsetTop = 20;
	this.popupType = "panel";
	this.popup = element;
	this.sleepms = 5000;
	this.mainContent = "mainContent";
	this.maskSelects = false;
}
/**
 * @desc Sets private options, and removes them from the structure which will be passed to YUI
 */
PopUpCreator.prototype.setPrivateOptions = function () {
	settings = this.setting;
	if(this.setting.popupType) {
		this.popupType = this.setting.popupType;
		delete this.setting['popupType'];
	}
	if(typeof(settings.header) != 'undefined') {
		this.headerText = this.setting.header;
		delete this.setting['header'];
	}
	if(typeof(settings.offsetTop) != 'undefined') {
		this.offsetTop = this.setting.offsetTop;
		delete this.setting['offsetTop'];
	}
	if(typeof(settings.offsetLeft) != 'undefined') {
		this.offsetLeft = this.setting.offsetLeft;
		delete this.setting['offsetLeft'];
	}
	if(typeof(settings.sleepms) != 'undefined') {
		this.sleepms = this.setting.sleepms;
		delete this.setting['sleepms'];
	}
	if(typeof(settings.mainContent) != 'undefined') {
		this.mainContent = this.setting.mainContent;
		delete this.setting['mainContent'];
	}
	if(typeof(settings.maskSelects) != 'undefined') {
		this.maskSelects = this.setting.maskSelects;
		delete this.setting['maskSelects'];
	}
}
/**
 * @desc Creates the actual YUI popup
 */
PopUpCreator.prototype.attach = function(self) {
//	this &= self;
	settings = this.setting;
	 if (this.popupType == 'tooltip') {
		settings.text = this.element.innerHTML;
		this.element.innerHTML = '';
		this.popup = new YAHOO.widget.Tooltip(this.elementName, settings );
	} else {
		this.popup = new YAHOO.widget.Panel(this.elementName, settings );
		if(typeof(this.headerText) != 'undefined') {
			this.popup.setHeader(this.headerText);
		}
		this.popup.render();
	}
}

/**
 * @desc set options against a particular object, not necessarily this
 * @param obj 		  The object to add our options to, usually this.setting
 * @param optionsObj  The options we are setting to obj
 */
PopUpCreator.prototype.setOptions = function(obj, optionsObj, ignoreUndefinedProps)
{
	if (!optionsObj)
		return;
	for (var optionName in optionsObj)
	{
		if (ignoreUndefinedProps && optionsObj[optionName] == undefined)
			continue;
		obj[optionName] = optionsObj[optionName];
	}
};
PopUpCreator.prototype.getElement = function(ele)
{
	if (ele && typeof ele == "string")
		return document.getElementById(ele);
	return ele;
};

/**
 * @desc show the YAHOO popup object
 * @param element the caller object, ie diamonds.show(this);
*/
PopUpCreator.prototype.show = function (element) {
	container = document.getElementById(this.elementName+"_c");
	if(typeof(element) == 'string') {
		element = document.getElementById(element);
	}
	if(typeof(element) == 'object' && typeof(container) == 'object') {
		container.style.top = element.offsetTop + this.offsetTop+"px";
		container.style.left = element.offsetLeft + this.offsetLeft+"px";
	}
	if(this.maskSelects) {
		addClassName(this.mainContent,'masked');
	}
	this.popup.show();
}
/**
 * @desc hide the YAHOO popup object
 */
PopUpCreator.prototype.hide = function () {
	setTimeout(this.elementName+".hideNoTimer()",this.sleepms);
}
PopUpCreator.prototype.hideNoTimer = function () {
	if(this.maskSelects) {
		removeClassName(this.mainContent,'masked');
	}
	this.popup.hide();
}
/**
 * @desc get a handle to the YAHOO popup object
 */
PopUpCreator.prototype.getHandle = function() {
	this.popup;
}


/************************************************************
 * Select
 ************************************************************/
var SelectCreator;
if(!SelectCreator) SelectCreator = {};
/**
 * @desc PopUpCreator constructor
 * @param element  The element (div id) used to attach the YUI popup to the DOM
 * @param opts     The options passed into the constructor.  See init for options.
 */
SelectCreator = function(element, opts) {
	this.init(element);
	this.setOptions(this, opts);
	this.attachBehaviors();
}
SelectCreator.prototype.init = function(element) {
	this.element = document.getElementById(element);
	this.focusElement = null;
	this.hoverClass = "highlight";
	this.selectedClass = "highlight";
	this.showClass = "SelectOptionsShow";
	this.hideClass = "SelectOptionsHide";
	this.focusedClass = "SelectOptionFocused";
    this.multiLine = false;
	this.maxHeight = 0;
	this.inputField = "";
	this.input;
}
SelectCreator.prototype.setOptions = function(obj, optionsObj, ignoreUndefinedProps)
{
	if (!optionsObj)
		return;
	for (var optionName in optionsObj)
	{
		if (ignoreUndefinedProps && optionsObj[optionName] == undefined)
			continue;
		obj[optionName] = optionsObj[optionName];
	}
};

SelectCreator.prototype.preorderTraversal = function(root, func)
{
	var stopTraversal = false;
	if (root)
	{
		stopTraversal = func(root);
		if (root.hasChildNodes())
		{
			var child = root.firstChild;
			while (!stopTraversal && child)
			{
				stopTraversal = this.preorderTraversal(child, func);
				try { child = child.nextSibling; } catch (e) { child = null; }
			}
		}
	}
	return stopTraversal;
};
SelectCreator.prototype.getInput = function()
{
	if(this.multiLine)
		return;
	return this.getElementChildren(this.element)[0];
};
SelectCreator.prototype.getInputHidden = function()
{
	if(this.multiLine)
		return this.getElementChildren(this.element)[0];
	return this.getElementChildren(this.element)[1];
};

SelectCreator.prototype.getList = function()
{
	if(this.multiLine)
		return this.getElementChildren(this.element)[1];
	return this.getElementChildren(this.element)[2];
};
SelectCreator.prototype.getElementChildren = function(element)
{
	var children = [];
	var child = element.firstChild;
	while (child)
	{
		if (child.nodeType == 1 /* Node.ELEMENT_NODE */)
			children.push(child);
		child = child.nextSibling;
	}
	return children;
};

SelectCreator.prototype.attachBehaviors = function()
{
	var self = this;
	var list = this.getList();
	if(!this.multiLine) {
		addClassName(list, this.hideClass);
		var input = this.getInput();
		input.onclick = function() {
			list = self.getList();
			if(hasClassName(list, self.hideClass)) {
				addClassName(list, self.showClass);
				removeClassName(list, self.hideClass);
			} else if(hasClassName(list, self.showClass)) {
				addClassName(list, self.hideClass);
				removeClassName(list, self.showClass);
			}
		}
	} else {
		addClassName(list, this.showClass);
	}

	this.preorderTraversal(list, function(node) {
		if (node.nodeType == 1 /* NODE.ELEMENT_NODE */)
		{
			if (node.nodeName.toLowerCase() == "li")
			{
				var li = node;
				//li.onclick = function() { selectMe(this) };

				if (window.attachEvent)
				{
				  li.onmouseover = function() {	addClassName(   li, this.hoverClass) };
				  li.onmouseout  = function() { removeClassName(li, this.hoverClass) };
				}
			}
			else if (node.nodeName.toLowerCase() == "ul")
			{
				this.selectWrapper = node;
			}
		}
		return false;
	});
}
SelectCreator.prototype.onfocus = function() {
        this.selectWrapper.className += ' selectFocused';
};
SelectCreator.prototype.onblur = function() {
        this.selectWrapper.className = 'selectReplacement';
};
SelectCreator.prototype.onchange = function(obj) {
        var idx = obj.selectedIndex;
        this.setVal(obj,ul.childNodes[idx]);
};
SelectCreator.prototype.onkeypress = this.onchange;
SelectCreator.prototype.onclick = this.onchange;

SelectCreator.prototype.setVal = function(obj,val) {
	var inputH = this.getInputHidden();
	inputH.setAttribute('value', val);

	addClassName(obj, this.selectedClass);
	this.selectedObj = obj;

	if(!this.multiLine) {
		var input = this.getInput();
		if(typeof(input.innerHTML) != 'undefined') {
			input.innerHTML = obj.innerHTML;
		}
		input.value = obj.innerHTML;
		input.onclick();
	}
}
SelectCreator.prototype.getVal = function() {
	return this.selectedVal;
}

SelectCreator.prototype.clicked = function(obj) {
	if(oldObj = this.selectedObj) {
		removeClassName(oldObj, this.selectedClass);
	}
	var value = obj.getAttribute('value');
	this.setVal(obj,value);
}

function clearBlankPrompt( target ) {
    if (target.value == target.promptWhenBlank) {
        target.value = '';
    }
    removeClassName( target, "inactiveInput" );
    addClassName( target, "activeInput" );
}

function replaceBlankPrompt( target ) {
    if ( target.value == '' || target.value == target.promptWhenBlank ) {
        target.value = target.promptWhenBlank;
        removeClassName( target, "activeInput" );
        addClassName( target, "inactiveInput" );
    }
}

function initBlankPrompt( target, newPrompt ) {
  target.promptWhenBlank = newPrompt ;
  removeClassName( target, "inactiveInput" );
  addClassName( target, "activeInput" );
  replaceBlankPrompt( target );
  AAA.Widget.addEventListener( target, 'focus', function() { clearBlankPrompt( target ) }, false );
  AAA.Widget.addEventListener( target, 'blur', function() { replaceBlankPrompt( target ) }, false );
}

function validEmailAddressFormat( address ) {
    var firstAt = address.indexOf( '@' );
    var lastAt = address.lastIndexOf( '@' );
    var lastDot = address.lastIndexOf( '.' );
    var length = address.length ;
    return firstAt > 0 && firstAt == lastAt && firstAt < lastDot && lastDot < length-1;

}

function propString( obj ) {
   var s = "";
   for ( prop in obj ) {
      s = s + prop + "=" + obj[prop] + " ";
   }
   return s;
}

function propNames( obj ) {
   var s = "";
   for ( prop in obj ) {
      s = s + prop + " ";
   }
   return s;
}

function debug( msg ) {
	if ( ("console" in window) ) {
	     if ( console.debug ) {
	     	console.debug( msg );
	     }
         else if ( console.log ) {
	     	console.log( msg );
		}
	}
}

// for input fields that contain dates in m/d/y format, handle cases
// where users are not entering 2 digit month, 2 digit day, and 4 digit year
function fixMMDDYYYY( target ) {
    var input = target.value ;
    // split string on - or /
    var parts = input.split( /-|\// );
    if ( parts.length == 3 ) {
        var month = parts[0];
        var day = parts[1];
        var year = parts[2];
        if ( month.length == 1 ) {
            month = '0' + month ;
        }
        if ( day.length == 1 ) {
            day = '0' + day ;
        }
        if ( year.length <= 2 ) {
            year = parseInt( year.replace(/^[0]+/g,"") );
         	var curdate = new Date();
	        var curyear = curdate.getYear();
	        var century = Math.floor( curyear / 100 ) * 100;
	        var yearInCentury = curyear - century ;
	        if ( year < (yearInCentury + 10) ) {
	             year = century +  year ;
	        }
	        else {
	             year = century - 100 + year ;
	        }
        }
        target.value = month + '/' + day + '/' + year ;
    }
}

