/* prints a page */
function doPrint() {
       window.print();
}
/* History -1 */
function back() {
       javascript:history.go(-1);
}

function correctPNG() // correctly handle PNG transparency in Win IE 5.5 or higher.
{
       for(var i=0; i<document.images.length ; i++)
       {
              var img = document.images[i]
                var imgName = img.src.toUpperCase()
                if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
                {
                   var imgID = ( img.id) ? "id='" + img.id + "' " : ""
                   var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                   var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                   var imgStyle = "display:inline-block;" + img.style.cssText
                   if (img.align == "left") imgStyle = "float:left;" + imgStyle
                   if (img.align == "right") imgStyle = "float:right;" + imgStyle
                   if (img.parentElement.href ) imgStyle = "cursor:hand;" + imgStyle
                   var strNewHTML = "<span " + imgID + imgClass + imgTitle
                   + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
                   + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                   + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
                   img.outerHTML = strNewHTML
                   i = i-1
                }
         }
}

if(window.attachEvent){
    window.attachEvent("onload", correctPNG);
}


/////////////////////////////////////////
//------START----------------------------
//Generates a pop up
//***************************************
//Created 12/5/05
//By Ragarwal
//trigger  -  textbox  -  genPopup('CMS Template URL','cabincatwindow','resizable=yes','width','height')
//***************************************
//TODO make the noeneter JS fuction firefox compatable
//***************************************

popWindow = new Object();

popWindow.closed = true;

function genPopup(url,target,extraProp,pWidth,pHeight){
       if (!popWindow.closed) {popWindow.close();}
       popWindow = window.open(url,target,'toolbar=no,width='+pWidth+',height='+pHeight+',left=30,top=30,'+extraProp+',status=yes');
         popWindow.focus();
}

function openPopup(url) {
  genPopup(url, '', 'resizable=yes', 700, 400);
}


//------FINISH----------------------------
//Generates a pop up
/////////////////////////////////////////

//////////////////////////////////////////////
//------START----------------------------
//general on load scripts
//***************************************

//the onloads array holds the functions to be called when the page loads. Each pagelet is responsible for
//loading this array with the functions it needs to run when the page body loads

var onloads = new Array();

function bodyOnLoad() {
  for ( var i = 0 ; i < onloads.length ; i++ ){
    onloads[i]();
  }
  updateContainerDimensions();
}

function updateContainerDimensions() {
  var leftContent = document.getElementById('contentcenter');
  var rightContent = document.getElementById('contentright');


//alert("computed height: " + computedStyle(rightContent).height + " set height: " + rightContent.style.height);

  if (leftContent != null && rightContent != null) {
    var leftContentHeight = parseInt(computedStyle(leftContent).height.replace(/px/,""));
//alert("margin-top: " + computedStyle(rightContent).marginTop + " height: " + computedStyle(rightContent).height);
    var rightContentHeight = parseInt(computedStyle(rightContent).height.replace(/px/,"")) + 25;

    if (leftContentHeight < rightContentHeight) {
      leftContent.style.height = (document.getElementById('frame').offsetHeight - document.getElementById('contentheader').offsetHeight) + 'px';
    }
  }
}


//------FINISH----------------------------
///general on load scripts
/////////////////////////////////////////

//////////////////////////////////////////////
/// booking related pages
///***************************************


/* Submits the default form */
function switchBookingAction(target)
{
       if (target!=null) {
          document.forms[0].dispatch.value=target;
          }
       alert('pause');
   document.forms[0].submit();
}

//////////////////////////////////////////////
/// form submition
//***************************************
//Created 01/12/05
//By W Antjoule
//////////////////////////////////////////////
//formId = The name of the form to be submitted
//target = the value of the page dispatch to be set to
//formAction = the value the form action will be set to
//
//

function formSubmit(formId,target,formAction)
{
//alert(document.forms[formId].action);
//alert(document.forms[formId].dispatch.value);
//Check if target is passed
       if (target!=null) {
          document.forms[formId].dispatch.value=target;
       }
//Check if formAction is passed
       if(formAction!=null){
              var x=document.getElementsByName(formId);
              document.forms[formId].action=formAction;
       }
//submit the form
//alert(document.forms[formId].action);
//alert(document.forms[formId].dispatch.value);
       document.forms[formId].submit();
}

/////////////////////////////////////////////////

/* sets paging hidden fileds and submits */
function cruiseSearchPaging(formId,  startingRowNumber)
{
          //sets startingRowNumber for paging ;
       document.forms[formId].startingRowNumber.value=startingRowNumber;
       formSubmit(formId,"cruiseSearch");
}

function pricingQualify(context, packageId, itineraryCode, priceProgramCode) {
       //Hack for now. I will remove this shortly - Dan
       var prefix = '';
    if (context == 'agent/booking'){
           prefix = '../../';
    } else {
           prefix = '../';
    }
    window.location = prefix + context + '/pricingQualify.html?packageId=' + escape(packageId) + '&itineraryCode='       + escape(itineraryCode) + '&priceProgramCode=' + escape(priceProgramCode);
}


function compareSailing(formId,  target, e) {
       if ( document.forms[formId].compareCount.value <= 1 ) {
              alert(e);
       } else {
              formSubmit(formId,target,'cruiseSearchCompare.html');
       }
}

/*
Show/Hide inclusive packages layer
assumes 3 elements that are related. A target, a show target element and a hide target element.
The show invocation hides the show element and shows the target.
The hide invocation shows the show element and hides the target.
indicator         : indicates whether the show or hide the target element. 0 = hide, 1 = show
elementTarget : the target element
element2Show  : the element that controls display of target
elementHide   : the element that controls hiding the target
*/

function showHideLayer(indicator,elementTarget,elementShow,elementHide){

       if (indicator == 0){
              document.getElementById(elementTarget).style.display='none';
              document.getElementById(elementShow).style.display='block';
              document.getElementById(elementHide).style.display='none';
       } else {
              document.getElementById(elementTarget).style.display='block';
              document.getElementById(elementShow).style.display='none';
              document.getElementById(elementHide).style.display='block';
       }
}

////////////////
//quick search date range dropdown load scripts
//***************************************
function getQuarter(currentMonth) {
                      //MATH POWER
             quarter = Math.ceil(currentMonth*3/11);
             return quarter;
}

////////////////
//Cruise Search Compare arrange
///////////////

function incrementCount(chkBox, p, e)
{
       //compare count
       var c  = parseFloat(document.cruiseSearchCompare.compareCount.value)
       //compare list
       var l  = document.cruiseSearchCompare.compareSailings.value
       //error message
       var e  = '<fmt:message key="popupmsg.cruisesearch.compare"/>'

       var reg = p;


       //checkbox is being checked
       if (chkBox.checked)
              {
                     //check for 3 packages selected for compare
                     if (c==3)
                     //uncheck if allready 3 are checked
                     {chkBox.checked = false;}
                     //this is the first package id added, add 1 to compareCount
                     else if (c==0)
                                   {
                                          l=l+p
                                          document.cruiseSearchCompare.compareSailings.value=l ;
                                          c=c+1
                                          document.cruiseSearchCompare.compareCount.value=c ;
                                   }
                     //this is not the first so add commar, add 1 to compareCount
                     else        {
                                          l=l+','+p
                                          document.cruiseSearchCompare.compareSailings.value=l ;
                                          c=c+1
                                          document.cruiseSearchCompare.compareCount.value=c ;
                                   }
              }
       //checkbox is being unchecked, remove 1 to compareCount
       else
              {
              c=c-1
              if(c>=2){
                     l = l.replace(","+reg,"");
                     l = l.replace(reg,"");
              }
              else{
                     l = l.replace(reg,"");
                     l = l.replace(",","");
              }

              document.cruiseSearchCompare.compareCount.value=c ;
              document.cruiseSearchCompare.compareSailings.value=l ;
              }
}

/////////////////////////////////////////
//------START----------------------------
//TOTAL GUEST NUMBER VALIDATION
//***************************************
//Used for validating the number of guest that are selected on the pricing qualifier.
//***************************************

var SavedValue = 0;

function guestAmountCalcSave(oSelect)
{
       SavedValue = parseInt(oSelect.options[oSelect.selectedIndex].value);
}

function guestAmountCalcUp(oSelect,e1,e2)
{
    var oSelect1 = oSelect.form.guestQuantityAdult;
    var oSelect2 = oSelect.form.guestQuantityChildren;

    var nValue1 = parseInt(oSelect1.options[oSelect1.selectedIndex].value);
    var nValue2 = parseInt(oSelect2.options[oSelect2.selectedIndex].value);
    window.status = nValue1 + "|" + nValue2 + "|" + (nValue1 + nValue2);

    if ((nValue1 + nValue2) > 8)
    {
        alert(e1 + ( nValue1 + nValue2 ) + e2);
        SetSelect(oSelect, SavedValue);
    }
}

function SetSelect(oSelect, SavedValue)
{
    for (i = 0 ; i < oSelect.options.length ; i++)
    {
        if (oSelect.options[i].value == SavedValue)
        {
            oSelect.selectedIndex = i;
        }
    }
}

//--------END----------------------------
//TOTAL GUEST NUMBER VALIDATION
/////////////////////////////////////////


/////////////////////////////////////////
//------START----------------------------
//highlight and unhighlight the user promocode
//***************************************
//Created 12/15/05
//By W Antjoule
//trigger  -  checkbox -
//***************************************

var tempValue="";
function highlightText(value)
{
       if (value !=null && trim(value)!="")
       {
              value=value.toUpperCase();
              tempValue=value;
              if (document.getElementsByTagName)
              {
// Get table cells in document
                     var cells = document.getElementsByTagName('tr');
                     var numCells = cells.length;

// Loop through elements returned
                     for (var i = 0; i < numCells; ++i)
                     {
// If cell should be changed (matching class)...
                            var clsName = cells[i].className;
                            var cls = String.toUpperCase(clsName);
                            var clsIndex =(cls.indexOf(tempValue));
                            if (clsIndex==0)
                            {
// ...alter the colour value
                                   cells[i].style.backgroundColor = '#FF66FF';
                            }
                     }
              }
       }

}

function unhighlightText(){
if (document.getElementsByTagName)
{
       // Get table cells in document
//alert("tempValue"+tempValue);
       if (tempValue !=null && trim(tempValue)!="")
       {
              var cells = document.getElementsByTagName('tr');
              var numCells = cells.length;
// Loop through elements returned
                     for (var i = 0; i < numCells; ++i)
                     {
                            var clsName = cells[i].className;
                            var cls = String.toUpperCase(clsName);
                            var clsIndex =(cls.indexOf(tempValue));
                            if (clsIndex==0)

                            {
                                   cells[i].style.backgroundColor = '';
                            }
                     }
              }
       }
}

//--------END----------------------------
//highlight and unhighlight the user promocode
/////////////////////////////////////////



/////////////////////////////////////////
//------START----------------------------
//BOOKING CATERGORY PROMO COBINATION VALIDATION
//***************************************
//Created 12/15/05
//By W Antjoule
//trigger  -  Checkbox  -  onClick="checkAll(this,'**cabinCategory**')"
//***************************************
//TO DO
//if a category is selected and then unselected then the catergory changing error message appears.
//***************************************

function bookingPromoComboCatVal( cbs,cb,cabinCat,pc,isGroup )
{
//CV-()-
       var sm = cabinCat +','+ pc;
       var total = 0;
       var maxi = document.bookingForm.combinablePromoCodes.length;
       var usm = 0;
       if (document.bookingForm.upgradeSelected !=null){
              usm = document.bookingForm.upgradeSelected.length;
       }
       var usmName =document.bookingForm.upgradeSelected;
       var maxPromo =1;

       if(cbs==null){
              return false;
       }
              if (cbs.checked) {
                     if(document.bookingForm.pricedCabinCategoryCode.value==cabinCat){
                            for (var idx = 0; idx < maxi; idx++){
                                   if (eval("document.bookingForm.combinablePromoCodes[" + idx + "].checked") == true) {
                                          total += 1;
                                   }
                            }
                            if(total>maxPromo){
                                   document.bookingForm.berthedCabinCategoryCode.value='';
                            }
                     } else {
                            total = 0;
                            maxi = document.bookingForm.combinablePromoCodes.length;
                            if(document.bookingForm.pricedCabinCategoryCode.value.length>0){
                                   document.bookingForm.berthedCabinCategoryCode.value='';
                            }
                     }

                     bookingPromoComboCatValUpgrade(sm,usm,usmName,maxi,cb,cbs);
                     document.bookingForm.pricedCabinCategoryCode.value=cabinCat;e=cabinCat;

                     document.bookingForm.groupCodeSameAsPromoCode.value=isGroup
              }
              else{
                     for (var idx = 0; idx < maxi; idx++){
                     cb[idx].checked = false ;
                     }

                     for(var idx = 0; idx < maxi; idx++) {
                            var btnObj = eval('document.bookingForm.btn'+'['+idx+']');
                            if(btnObj != null && btnObj != 'undefined') {
                                   btnObj.disabled = true;
                            }
                     }

                     if(document.getElementById(sm)!=null) {
                            document.getElementById(sm).disabled = true;
                     }
                     document.bookingForm.pricedCabinCategoryCode.value='';
                     document.bookingForm.berthedCabinCategoryCode.value='';
                     document.bookingForm.groupCodeSameAsPromoCode.value='';
                     for (var idx = 0; idx < usm; idx++){
                            usmName[idx].disabled = true ;
                            if(usmName[idx].options) {
                                   usmName[idx].selectedIndex = 0;
                            }
                     }
              }
}

function bookingPromoComboCatValUpgrade(sm,usm,usmName,maxi,cb,cbs)
{
       var btnId = 'btn_'+sm.substring(0,sm.indexOf(','));
       for (var idx = 0; idx < maxi; idx++){
              cb[idx].checked = false ;
       }
       cbs.checked = true;

       for (var idx = 0; idx < usm; idx++) {
              usmName[idx].disabled = true ;
              if(usmName[idx].options) {
                     usmName[idx].selectedIndex = 0;
              }
       }

       for(var idx = 0; idx < maxi; idx++) {
              var btnObj = eval('document.bookingForm.btn'+'['+idx+']');
              if(btnObj != null && btnObj != 'undefined') {
                     btnObj.disabled = true;
              }
       }
       document.getElementById(btnId).disabled = false;

       if(document.getElementById(sm)!=null) {
              document.getElementById(sm).disabled = false;
              document.bookingForm.berthedCabinCategoryCode.value='';
       }
}

//--------END----------------------------
//BOOKING CATERGORY PROMO COBINATION VALIDATION
/////////////////////////////////////////



/////////////////////////////////////////
//------START----------------------------
//BOOKING CATERGORY SET BERTHED FIELD
//***************************************
//Created 1/5/06
//By W Antjoule
//trigger  -  onloads.push(bookingcategorySelectionload);
//***************************************
//TO DO
//***************************************

function bookingCatUpgrade(BC){
//SET HIDDEN FIELD TO THE SELECTED VALUE
              document.bookingForm.berthedCabinCategoryCode.value=BC;
}

//--------END----------------------------
//BOOKING CATERGORY SET BERTHED FIELD
/////////////////////////////////////////



/////////////////////////////////////////
//------START----------------------------
//BOOKING CATERGORY - SUBMITING CATEGORY SELECTION - AGENT
//***************************************
//Created 1/5/06
//By W Antjoule
//trigger  -  onclick="javascript:bookingCabinSubmitAgent();"
//***************************************
//TO DO
//***************************************

function bookingCabinSubmitAgent(){

//CV-(Maxi)-the count of all Promocode checkboxs on a page
       var maxi =document.bookingForm.combinablePromoCodes.length;
//CV-(status)-set to 0
       var status = false;
//Check that their is a Promo checbox that has been selected
       for (var idx = 0; idx < maxi; idx++){
              if (eval("document.bookingForm.combinablePromoCodes[" + idx + "].checked") == true) {
                     status = true;
                     break;
              }
              else{
                     status = false;
              }
       }
//if status is true submit the booking form
       if(status==true) {
              document.bookingForm.submit();
       }
//else throw error to the browser
       else {
              alert('You must select a Promo Code.');
              return false;
       }
}

//--------END----------------------------
//BOOKING CATERGORY - SUBMITING CATEGORY SELECTION - AGENT
/////////////////////////////////////////


/////////////////////////////////////////
//------START----------------------------
//BOOKING CATERGORY - SUBMITING CATEGORY SELECTION - COMSUMER
//***************************************
//Created 1/5/06
//By W Antjoule
//trigger  -  onclick="javascript:bookingCabinSubmitConsumer("selectedCabin);"
//***************************************
//TO DO
//***************************************

function bookingCabinSubmitConsumer(SC){

//CV UM upgrade menu ID
       var UMI ='upgrade_'+SC
       document.bookingForm.pricedCabinCategoryCode.value=SC;

       if(document.getElementById(UMI)!=null) {
              document.bookingForm.berthedCabinCategoryCode.value = document.getElementById(UMI).value;
       }
       else {
       }
       document.bookingForm.submit();

}

//--------END----------------------------
//BOOKING CATERGORY - SUBMITING CATEGORY SELECTION - COMSUMER
/////////////////////////////////////////






/////////////////////////////////////////
//------START----------------------------
//BOOKING CATERGORY DESELECT OPTIONS ONLOAD
//***************************************
//Created 1/5/06
//By W Antjoule
//trigger  -  onloads.push(bookingcategorySelectionload);
//***************************************
//TO DO
//***************************************

function bookingcategorySelectionload(){

//CV-(csm)- that counts the number of upgrade select menus
    var csm = 0;
       if (document.bookingForm.upgradeSelected !=null){
              csm = document.bookingForm.upgradeSelected.length;
       }
//CV-(usm)- for the select menu
       var usm =        document.bookingForm.upgradeSelected;

//for each usm set the option to default(option 0), Then disable all usm's
       for (var idx = 0; idx < csm; idx++) {
              if(usm[idx].options) {
                     usm[idx].selectedIndex = 0;
              }
              usm[idx].disabled = true ;
       }
//SV-(Maxi)-the count of all Promocode checkboxs on a page
       var maxi = document.bookingForm.combinablePromoCodes.length;
//for set each checkbox to unchecked
       for (var idx = 0; idx < maxi; idx++){
              document.bookingForm.combinablePromoCodes[idx].checked = false ;
       }
}

//--------END----------------------------
//BOOKING CATERGORY DESELECT OPTIONS ONLOAD
/////////////////////////////////////////



/////////////////////////////////////////
//------START----------------------------
//Submit the current form when user hits enter key
//***************************************
//Created 12/20/05
//By EThomas
//trigger  -  Text  -  onKeyPress="return submitenter(this,event)"
//***************************************
//TO DO

function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
   myfield.form.submit();
   return false;
   }
else
   return true;
}

//--------END----------------------------
//BOOKING CATERGORY PROMO COBINATION VALIDATION
/////////////////////////////////////////



/////////////////////////////////////////
//------START----------------------------
//disallow a form to be submitted by hitting the enter key when in a textfield
//***************************************
//Created 12/20/05
//By W Antjoule
//trigger  -  textbox  -  onkeypress="return noenter()"
//***************************************
//TODO make the noeneter JS fuction firefox compatable
//***************************************

function noenter( event )
{
var intKeyCode = 0;
var blnAllow = true;
   if( document.all )
   {
       intKeyCode = event.keyCode;
    }
    else
    {
       intKeyCode = event.which;
    }

if( intKeyCode == 13 )
{
    blnAllow = false;
}
return blnAllow;
}

//--------END----------------------------
//disallow a form to be submitted by hitting the enter key when in a textfield
/////////////////////////////////////////


/////////////////////////////////////////
//------START----------------------------
//Crusie search details - enable state for US residence
//***************************************
//Created 1/19/2006
//By William Antjoule
//trigger  -  HREF  -
//***************************************
//TODO
//***************************************
function cruiseSearchPriceEnableState(SMV) {

       var CC = 'DIRMIA01'
       if (SMV==CC){
              document.bookingForm.residencyState.disabled = false;
       }
       else{
              document.bookingForm.residencyState.selectedIndex = 0;
              document.bookingForm.residencyState.disabled = true;
       }
}

//--------END----------------------------
//Function related to Hide/Show details
/////////////////////////////////////////


/*
 * Added these functions here because agent pages are using them too.
 *
 * TODO move these functions to appropriate file.
 */
function changeSrc(imageObject, imgName) {
  imageObject.src = imageObject.src.substring(0, imageObject.src.lastIndexOf("/") + 1) + imgName;
}

/*
 * Renamed changeSrc to swapImage
 */
function swapImage(imageObject, imgName) {
  imageObject.src = imageObject.src.substring(0, imageObject.src.lastIndexOf("/") + 1) + imgName;
}

/*
 * Switch Cabin....
 */
function doSwitchCabin(cabin)
{
       window.location="cabinSwitch.html?activeCabin="+cabin;
}


/*
 * TODO GENERALIZE FORM SUBMIT...BASED ON ELEMENT ID
 */
function doSubmit()
{
       window.document.aform.submit();
}

function swapDiv(divName) {
       if (document.getElementById(divName).style.display == "none") {
              document.getElementById(divName).style.display = "block";
       } else {
              document.getElementById(divName).style.display = "none";
       }
}

/*
 */
/////////////////////////////////////////
//------START----------------------------
// getWebAppContext()
//
// Generic function to return the web context from parsing the URL.  This
// function will no longer work if we change the context to /
//***************************************
//Created 2/14/2006
//By Matt Wolinski
//***************************************
//TODO
//***************************************
function getWebAppContext() {
    // parse the context from the URL.
    var loc = location.pathname;
    loc = loc.substring(1);
    var context = loc.substring(0,loc.indexOf("/"));
    return context;
}
//--------END----------------------------
/////////////////////////////////////////

 function clearAllRadio(aform)
 {
     for(var i=0;i<=window.document.aform.elements.length;i++ )
     {
        var aRadioObj = window.document.aform.elements[i];

        if (aRadioObj.type == 'radio' &&   aRadioObj.checked)
        {
            aRadioObj.checked=false;
        }
     }
 }

 function setDateToCheckBox(box)
 {

  if (box.value != 0)
  {


               var lead_pound = box.value.indexOf("#");
               var checkBoxId = box.value.substring(0,lead_pound);
               //alert("CheckBox Id: "+checkBoxId);

               var checkBox = document.getElementById(checkBoxId);
               checkBox.value = box.value;
               //alert(checkBox.value);
        }
 }

/////////////////////////////////////////////////////////////////
// General purpose functions

/*
 * Updates value of hidden element named 'dispatch'.
 * Form that contains that element is identified by its
 * position on page. It is assumed to be first on page.
 *
 *   - target value to be assign to dispatch
 */
function set(target) {
  document.forms[0].dispatch.value=target;
}

/*
 * Removes preceding and trailing whites spaces from string.
 *
 *   - str  string to be operated on
 */
function trim(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

/*
 * Calculates total distance between element and top of the page.
 */
function offsetTop(obj) {
  var offsetDistance = 0;

  while (obj.offsetParent != null && computedStyle(obj).position == 'static') {
    offsetDistance += obj.offsetTop;
    obj = obj.offsetParent;
  }

  return offsetDistance;
}

/*
 * Calculates total distance between element and left side of the page.
 */
function offsetLeft(obj) {
  var offsetDistance = 0;


    // if containing element is statically positioned then loading message
  // element will be incorrectly positioned relative to next containing
  // element that is not statically position


  while (obj.offsetParent != null && computedStyle(obj).position == 'static') {
    offsetDistance += obj.offsetLeft;
    obj = obj.offsetParent;
  }

  return offsetDistance;
}

/*
 * Returns CSSStyleDeclaration object for an element.
 *
 *   - elmnt  object whose styles to return
 */
function computedStyle(elmnt) {
  var computedStyle = null;

  if (document.defaultView && document.defaultView.getComputedStyle) {
    computedStyle = document.defaultView.getComputedStyle(elmnt, "");
  } else if (elmnt.currentStyle) {
    computedStyle = elmnt.currentStyle;
  } else {
    computedStyle = element.style;
  }

  return computedStyle;
}

/*
 * E-mail validation function. Taken from
 * http://www.quirksmode.org/js/mailcheck.html
 *
 * Note. This function will not detect all of the e-mail addresses
 *       1) address that have user name in quotes with strange characters
 *          ex: "J. P. 's-Gravezande, a.k.a. The Hacker!"@server.com
 *       2) address with IP address instead of domain name
 *          ex: me@[187.223.45.119]
 *          some of the mail servers won't even recognize this address
 *       Historically a domain name may not begin with a number, but in
 *       practice this rule is disregarded. So address like this is accepted
 *       ex: someone@123.com
 */
function validateEmail(email) {
  var filter  = /^[\w\.\-]+@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return filter.test(email);
}

/*
 * Retrieves element using its id attribute.
 *
 *   - elmnt either reference to element or its id
 */
function getElement(elmnt) {
  return (elmnt != null && (typeof elmnt) == 'string') ? document.getElementById(elmnt): elmnt;
}

/////////////////////////////////////////////////////////////////
// In page pop-up functions

// collection of messages on page
var messages = new Object();

/*
 * Creates or retrieves already existing message based on passed id.
 * If message doesn't exist then creates one, retreives message text
 * from CMS and displays it on page.
 *
 *   - id  corresponds to a tool tip message stored in CMS
 *   - toolTipIcon  reference to element that made this call
 */
function displayToolTip(id, toolTipIcon) {
  if (messages[id] == null) {
    var messageId = 'messageText' + id;
    messages[id] = new Message(messageId, 350);

    // register message 'div' with the ajax engine
    ajaxElements.push(messageId);

    registerElementsWithAjax();

    // register the url with the ajax engine
    registerAjaxEngine('lookupDetails','../content.html');

    sendAjaxRequest('lookupDetails', 'content', messageId, 'contentCode=' + id);
  }
  messages[id].show(toolTipIcon);
}

/*
 * Hides opened message.
 *
 *   - id  corresponds to a tool tip message stored in CMS
 *   - toolTipIcon  reference to element that made this call
 */
function hideMessage(id, toolTipIcon) {
  if (messages[id] != null) {
    messages[id].hide();
    if (document.all) {
      backgroundFrame.style.display = 'none';
    }
  }
}

/*
 * Message container responsible for creating, displaying and hiding
 * of a message pop-up.
 *
 *   - messageId  unique message id that identifies message on page
 *   - width  message width
 */
function Message(messageId, width) {
  this.messageElement = document.createElement('DIV');
  this.messageText = this.messageElement.cloneNode(false);
  this.messageText.id = messageId;
  this.messageElement.appendChild(this.messageText);
  this.messageElement.style.position = 'absolute';
  this.messageElement.style.zIndex = '1001';
  this.messageElement.style.width = width + 'px';
  this.messageElement.style.display = 'block';
  this.messageElement.style.backgroundColor = '#FEE29E';
  this.messageElement.style.border = '1px solid #000';
  this.messageElement.style.padding = '5px 7px';

  // insert element into DOM tree as first child of BODY node
  document.body.insertBefore(this.messageElement, document.body.firstChild);
}

Message.prototype.show = function Message_show(toolTipIcon) {
  displayElement(toolTipIcon, this.messageElement);
}

Message.prototype.hide = function Message_hide() {
  this.messageElement.style.display = 'none';
}

/*
 * Hides currently displayed content element, if any, and displays
 * requested content element. Elements are identified by some string
 * that is followed by number. Index numbers should start from 1 and
 * indeces should be sequential.
 *
 * If there is only one element then contentIdPrefix becomes element
 * identifier. In this case index parameter can be null OR have
 * two values 'show' or 'hide'. This allows user to explicitely
 * specify operation to be performed.
 *
 *   - contentIdPrefix  id of elements that belong to same group should start
 *                      with this string
 *   - index  after prefix comes number that identifies element in group
 *            This parameter has dual usage
 */
function displayContent(contentIdPrefix, index) {
  var counter = 1;
  var currentElmnt = getElement(contentIdPrefix);

  if (index != null && index != 'show' && index != 'hide') {
    while ((currentElmnt = document.getElementById(contentIdPrefix + counter)) != null) {
      currentElmnt.className = (counter != index) ? currentElmnt.className + ' no_display': currentElmnt.className.replace(/no_display/g, '');
      counter++;
    }
  } else if (currentElmnt.className.match('no_display') != null && (index == null || index == 'show')
             || index == 'show') {
    currentElmnt.className = currentElmnt.className.replace(/no[_]display/g, '');
  } else {
    currentElmnt.className += ' no_display';
  }
}

/*
 * Displays element on page and positions it relative to reference element.
 * Element can be position either in center of the page or relative to
 * reference element. If position is determined relative to reference
 * then elements will have same x-axis and for y-axis height of reference
 * element is added.
 *
 * It is also possible to make element modal.
 *
 * Note. Hidden element's CSS position and z-index will be set to 'absolute' and '3'
 *
 *   - hiddenElmnt  elemnt that is being manipulated
 *   - arguments[...]
 *       There are three more possible arguments. They can be specified in any order:
 *       Note. Arguments 1 & 2 are mutually exclusive. You need to specify either one.
 *       1) refElementId  identifier for element relative to which hidden element
 *                        is displayed
 *       2) center  switch indicating if element should be displayed in center
 *                  of the page. Accepted value 'center'
 *       3) modal  switch indicating if page functionality will be disabled when
 *                 hiddenElement is displayed. Accepted value 'modal'
 */
function displayElement(hiddenElmnt) {
  hiddenElmnt = getElement(hiddenElmnt);
  var refElmnt = null;
  var centerPosition = false;
  var modalElement = false;

  for (var i = 1; i < arguments.length; i++) {
    if (arguments[i] == 'center') {
      centerPosition = true;
    } else if (arguments[i] == 'modal') {
      modalElement = true;
    } else {
      refElmnt = getElement(arguments[i]);
    }
  }

  // setting visibility to "hidden" here and changing it at the end to "visible"
  // displays element to user after it was positioned. Otherwise users will see
  // element move into final position from its base position
  hiddenElmnt.style.visibility = 'hidden';
  hiddenElmnt.className = hiddenElmnt.className.replace(/no[_]display/, '');
  hiddenElmnt.style.position = 'absolute';
  hiddenElmnt.style.zIndex = '3';

  positionElement(hiddenElmnt, refElmnt, centerPosition);

  if (document.all) {
    displayBackgroundFrame(refElmnt, hiddenElmnt.offsetWidth, hiddenElmnt.offsetHeight, centerPosition);
  }

  if (modalElement) {
    disablePageFunctionality();
  }

  hiddenElmnt.style.visibility = 'visible';
}

// reference to 'iframe' element used when rendering popup divs in IE5.5+. This frame
// placed between div and a 'select' or any other window object will allow div
// to be displayed over window elements in IE
var backgroundFrame = null;

function displayBackgroundFrame(refElmnt, width, height, centerPosition) {
  if (backgroundFrame == null) {
    backgroundFrame = document.createElement('iframe');

    // insert element into DOM tree right as first child of BODY node
    document.body.insertBefore(backgroundFrame, document.body.firstChild);

    backgroundFrame.src = 'javascript:void(0)';
    backgroundFrame.frameborder = '0';
    backgroundFrame.scrolling = 'no';
    backgroundFrame.style.position = 'absolute';
    backgroundFrame.style.zIndex = '2';
  }

  backgroundFrame.style.display = 'block';

  positionElement(backgroundFrame, refElmnt, centerPosition);

  backgroundFrame.style.width = width + 'px';
  backgroundFrame.style.height = height + 'px';
}

/*
 * Positions element either in center of the page or relative to an some
 * element.
 *
 *   - elmnt  element on page to be positioned
 *   - refElmnt  element relative to which elmnt will be positioned
 *   - centerPosition  flag indicating if element should be centered in middle of the page
 */
function positionElement(elmnt, refElmnt, centerPosition) {
  if (centerPosition != true) {
    elmnt.style.top = (offsetTop(refElmnt) + refElmnt.offsetHeight) + 'px';
    elmnt.style.left = offsetLeft(refElmnt) + 'px';
  } else if (document.all) {
    elmnt.style.top = ((document.documentElement.clientHeight / 2 + document.documentElement.scrollTop) - elmnt.offsetHeight / 2) + 'px';
    elmnt.style.left = (getElement('frame').offsetWidth / 2 - elmnt.offsetWidth / 2) + 'px';
  } else {
    elmnt.style.top = ((window.innerHeight / 2 + window.scrollY) - elmnt.offsetHeight / 2) + 'px';
    elmnt.style.left = (getElement('frame').offsetWidth / 2 - elmnt.offsetWidth / 2) + 'px';
  }
}

/*
 * Hides element on page.
 *
 *  - elmntId identifier of element to be hidden
 *  - modal  switch indicating if page functionality will be disabled when
 *           hiddenElement is displayed. Accepted value 'modal'
 */
function hideElement(elmntId, modal) {
  getElement(elmntId).className += ' no_display';

  hideBackgroundFrame();

  if (modal) {
    enablePageFunctionality();
  }
}

function hideBackgroundFrame() {
  if (backgroundFrame != null) {
    backgroundFrame.style.display = 'none';
  }
}

// List of elements on page that were disabled because
// in IE they are rendered as window based objects
var disabledElements = new Array();

/*
 * Removes user access to the page or its parts.
 *
 *  - opacity  transparency level. By default set to 50.
 *             0 is opaque and 100 fully transparent
 *  - refElmntId  element to cover. If not specified then
 *                whole page
 */
function disablePageFunctionality(opacity, refElmntId) {
  var blockingElmnt = getElement("pageBlockingElmnt");
  var refElmnt = getElement(refElmntId);

  if (blockingElmnt == null) {
    blockingElmnt = document.createElement("DIV");
    blockingElmnt.id = "pageBlockingElmnt";

// TODO at the moment CSS for background is being specified
// here we will need to move it into separate class.
// Like this:
/*
.disablingBackground {
  position: fixed;
  opacity: .5;
  filter: alpha(opacity=50);
  top: 0;
  left: 0;
  z-index: 100;
  width: 100%;
  height: 100%;
  background-color: #f8f8f8;
}
    blockingElmnt.className = "disablingBackground";
*/
    blockingElmnt.style.position = 'fixed';

    opacity = (opacity == null) ? '50': opacity;
    blockingElmnt.style.opacity= '.' + opacity;
    blockingElmnt.style.filter = 'alpha(opacity=' + opacity + ')';
    blockingElmnt.style.top = '0';
    blockingElmnt.style.left = '0';
    blockingElmnt.style.zIndex = '1';
    blockingElmnt.style.width = '100%';
    blockingElmnt.style.height = '100%';
    blockingElmnt.style.backgroundColor = '#fcfbf6';

    if (refElmnt != null) {
      refElmnt.appendChild(blockingElmnt);
    } else {
      // insert element into DOM tree right as first child of BODY node
      document.body.appendChild(blockingElmnt);
    }
  } else {
    blockingElmnt.style.display = "block";
  }

  // IE needs special treatment
  if (document.all) {
    if (disabledElements.length == 0) {
      var selectTags = (refElmntId != null) ? refElmnt.getElementsByTagName("SELECT"): document.getElementsByTagName("SELECT");

      // disabling all dropdowns on page because in IE they will
      // shine through DIV used for blocking current page
      for (var i = 0; i < selectTags.length; i++) {
        // if SELECT is already disabled then we don't want to touch it
        if (selectTags[i].disabled == false) {
          selectTags[i].disabled = true;
          disabledElements.push(selectTags[i]);
        }
      }
    }

    blockingElmnt.style.position = "absolute";
    blockingElmnt.style.height = document.documentElement.scrollHeight + "px";
  }

  if (refElmnt != null) {
    blockingElmnt.style.position = 'absolute';
    blockingElmnt.style.left = offsetLeft(refElmnt) + 'px';
    blockingElmnt.style.top = offsetTop(refElmnt) + 'px';
    blockingElmnt.style.width = refElmnt.offsetWidth + 'px';
    blockingElmnt.style.height = refElmnt.offsetHeight + 'px';
  }
}

/*
 * Gives user access to page.
 */
function enablePageFunctionality() {
  getElement("pageBlockingElmnt").style.display = 'none';

  for (var i = 0; i < disabledElements.length; i++) {
    disabledElements[i].disabled = false;
  }
}

/////////////////////////////////////////////////////////////////
// Tab functions

/*
 * Updates tabs according to user selection.
 *
 * Note. it is assumed CSS class for selected tab starts with 'a_tab'
 * and ends with '_ovr'.
 */
function swtichtabs(elmnt) {
  var anchors = elmnt.parentNode.getElementsByTagName('a');

  for(i = 0; i < anchors.length; ++i) {
    anchors[i].className = anchors[i].className.replace(/_ovr/, ''); // set all tabs to non-active state
    anchors[i].onmouseup = function() { // set only the tab that was clicked on to the active state
      var pattern = /(a_tab\w*)/;
      this.className = this.className.replace(pattern, '$1_ovr');
    }
  }
}

/////////////////////////////////////////
//------START----------------------------
// Email Validation()
//
// Generic function to validate a email address clientside
//***************************************
//Created 2/14/2006
//By William Antjoule
//***************************************
//TODO
//***************************************


var testresults;
function checkemail(EVFormName,EVFieldName){
       var str=document.forms[EVFormName].elements[EVFieldName].value
       var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
       if (filter.test(str))
       testresults=true
              else{
              alert("Please input a valid email address!")
              testresults=false
              document.forms[EVFormName].elements[EVFieldName].focus();
       }
       return (testresults)
}


function checkbae(EVFormName,EVFieldName){
       if (document.layers||document.getElementById||document.all)
              return checkemail(EVFormName,EVFieldName)
       else
              return true
}

// Function to subit a form
function formSubmitByID(formObj, target) {
       if(formObj != null) {
              formObj.dispatch.value=target;
              formObj.submit();
       }
}

function inArray(arr, testObject) {
       for (i = 0; i < arr.length; i++) {
              if (arr[i] == testObject) {
                     return true;
              }
       }
       return false;
}


/////////////////////////////////////////
//------START----------------------------
// Booking Payment Page
//
// Functions to add DHTML functionality to payment page
//***************************************
//Created 8/17/2006
//By DJ Raven[Eban Thomas]
//***************************************
//TODO
//***************************************

function setAddressState(isBillingEqualMailing)
{
       var addressDiv = document.getElementById("address_div");

       if (isBillingEqualMailing != 'false')
       {
              addressDiv.style.display = 'none';
       }
       else
       {
              addressDiv.style.display = '';
       }
}

/////////////////////////////////////////
//***************************************
//Add on 8/26/2006 by Matt Wolinski
//***************************************
// This method will ignore the enter key when the user is
// within the selected html form element.  You can use it to stop a
// user from accidentally submitting a form before completing it.
//
// Usage:  add onkeypress below to the html form element
// onkeypress="return handleEnter(this, event)"
/////////////////////////////////////////
function handleEnter (field, event) {
       var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
       if (keyCode == 13) {
              return false;
       }
       return true;
}
/////////////////////////////////////////