/*
  online-jscript.js
  Author:      John Cavan
  Description: Support methods and objects for client-side activities stripped down for online sales
  CreateDate:  15 Sep 2003
  $Id: online-jscript.js,v 1.18 2005/08/18 13:52:01 dan Exp $
*/

var tsCalHdl;
var tsWinHdl = new Array();
var tsDurHdl;
var tsErrorDialogHdl;
var isDesktop = false;

if( CommonPath == undefined )
{
  var CommonPath = "../Common";
}

/*
  *****************************************************
  ComboBox methods
  *****************************************************
*/

function tsSelectField( key )
{
  document.getElementById( key + "::text" ).select();
}

function tsValueFromText( key )
{
  var popup = document.getElementById( key + "::select" );
	var textfield = document.getElementById( key + "::text" );

	var idx;

	for(idx=0; idx < popup.options.length; idx++)
  {
		if( popup.options[idx].text == textfield.value )
    {
			popup.selectedIndex = idx;
			return;
		}
	}

	popup.selectedIndex = -1;
}

function tsCompleteTyping( key )
{
	if (event.keyCode < 0x2f && event.keyCode != 32)
  {
		return;
  }

	var textfield = document.getElementById( key + "::text" );
  var text = textfield.value;
	var popup = document.getElementById( key + "::select" );

	var options = popup.options;
	var i;
	var utext = text.toUpperCase();

	for( i=0; i < options.length; i++ )
  {
		var newtxt = options[i].text;
		var uopt = newtxt.toUpperCase();
		if( uopt != utext && uopt.indexOf( utext ) == 0 )
    {
			var txtrange = textfield.createTextRange();
			textfield.value = text + newtxt.substr(text.length);
			txtrange.moveStart( "character", text.length );
			txtrange.select();
			tsValueFromText( key );
			break;
		}
	}
}

function tsTestValue( key )
{
	var textfield = document.getElementById( key + "::text" );
  var text = textfield.value;
	var popup = document.getElementById( key + "::select" );

	var options = popup.options;
	var i;
	var utext = text.toUpperCase();

	for( i=0; i < options.length; i++ )
  {
		var newtxt = options[i].text;
		var uopt = newtxt.toUpperCase();
		if( uopt == utext )
    {
      textfield.value = newtxt;
			break;
		}
	}
}

function tsTextKeyDown( key )
{
  var popup = document.getElementById( key + "::select" );

	// Down Arrow
	if( window.event.keyCode == 40)
  {
		if( popup.selectedIndex < popup.options.length - 1 )
    {
			popup.selectedIndex += 1;
    }
		tsSetFromPopup( key );
	}

	// Up Arrow
	if( window.event.keyCode == 38 )
  {
		if( popup.selectedIndex > 0 )
    {
			popup.selectedIndex -= 1;
    }
		else if( popup.selectedIndex == -1 )
    {
			popup.selectedIndex = popup.options.length - 1;
    }
		tsSetFromPopup( key );
	}
}

function tsSetFromPopup( key )
{
  var popup = document.getElementById( key + "::select" );
  var textfield = document.getElementById( key + "::text" );

  var idx = popup.selectedIndex;

	if( idx != null && idx >= 0 )
  {
		textfield.value = popup.options[idx].text;
	}

	if( popup.needsblur == 1 )
  {
		textfield.focus();
		textfield.select();
	}

}

function tsShiftToText( key )
{
  var popup = document.getElementById( key + "::select" );
  var textfield = document.getElementById( key + "::text" );

  if( popup.isClicked == 1 )
  {
    popup.isClicked = 0;
		if( popup.needsblur == 1 )
    {
  		textfield.focus();
	  	textfield.select();
	  }
  }
  else
  {
    popup.isClicked = 1;
  }
}

function tsPopupFocus( key )
{
  var popup = document.getElementById( key + "::select" );
	popup.needsblur = 1;
}

function tsPopupBlur( key )
{
  var popup = document.getElementById( key + "::select" );
	popup.needsblur = 0;
  popup.isClicked = 0;
}

/*
  *****************************************************
  Chooser methods
  *****************************************************
*/

function tsChooserClick( fromElem, toElem, hiddenElem, addItem )
{
  var fromBox = document.getElementById( fromElem );
  var toBox = document.getElementById( toElem );
  var hiddenLoc = fromBox.form;

  // move the nodes
  for( var x = fromBox.options.length - 1; x >= 0; x-- )
  {
    if( fromBox.options(x).selected )
    {
      var tmpNode = fromBox.removeChild( fromBox.options(x) );
      toBox.appendChild( tmpNode );
      tmpNode.selected = false;

      if( addItem )
      {
        // create a new hidden element
        var tmpElem = document.createElement( "<input type='hidden' name='" + hiddenElem + "' value='" + tmpNode.value + "'>" );
        hiddenLoc.appendChild( tmpElem );
      }
      else
      {
        // get the elements and find the one that should be removed
        var elems = document.getElementsByName( hiddenElem );
        for( var y = 0; y < elems.length; y++ )
        {
          if( elems[y].value == tmpNode.value )
          {
            elems[y].parentElement.removeChild( elems[y] );
          }
        }
      }
    }
  }
}

/*
  *****************************************************
  Date Range methods
  *****************************************************
*/

function tsSetTimeValue( IDidx, elemName )
{

  var hrSel = document.getElementById( "hours::" + elemName + "::" + IDidx );
  var minSel = document.getElementById( "minutes::" + elemName + "::" + IDidx );
  var timeField = document.getElementById( elemName + "::" + IDidx );

  hrs = hrSel.options[ hrSel.selectedIndex ].value;
  mins = minSel.options[ minSel.selectedIndex ].value;

  if( hrs == "" || mins == "" )
  {
    // insufficient to set new
    timeField.value = "";
    return;
  }

  timeField.value = hrs + ":" + mins + ":00";

}

/*
  *****************************************************
  Tab Panel methods
  *****************************************************
*/

// called when the page unloads
function PageUnload()
{
  try
  {
    LocalPageUnload();
  }
  catch( e )
  {
    // ignore, the page doesn't have it
  }
}

// provides for a standard alert mechanism
function SystemAlert( altMsg )
{
  alert( altMsg );
}

// returns the result of a confirm message
function ConfirmMessage( inMsg )
{
  return confirm( inMsg );
}

// use to enable/disable the selected node state
function tsToggleNodeState( inCheck )
{
  document.getElementById( "Disable::" + inCheck.name ).disabled = inCheck.checked;
}

// used by delete boxes to disable form elements related to it
function TSdisableChildren( inCheck )
{

  try
  {
    if( !tsLocalDisable( inCheck ) )
    {
      inCheck.checked = false;
      return;
    }
  }
  catch( e )
  {
    // ignore
  }

  // get any other elements matching "Disable::" + checkname
  var elemCol = document.getElementsByName( "Disable::" + inCheck.name );
  for( var x = 0; x < elemCol.length; x++ )
  {
    elemCol[x].disabled = inCheck.checked;
  }

  try
  {
    tsLocalEndDisable( inCheck );
  }
  catch( e )
  {
    // ignore
  }
}

// returns the real value of a form element
function GetRealValue( frmElement )
{
  if( frmElement.selectedIndex == undefined )
  {
    return frmElement.value;
  }
  else
  {
    // select list
    return frmElement.options[ frmElement.selectedIndex ].value;
  }
}

// sets a form element value
function SetRealValue( frmElement, inVal )
{
  if( frmElement.selectedIndex == undefined )
  {
    frmElement.value = inVal;
  }
  else
  {
    // select list
    for( var x = 0; x < frmElement.options.length; x++ )
    {
      if( frmElement.options[x].value == inVal )
      {
        frmElement.selectedIndex = x;
        break;
      }
    }
  }
}

// toggle the display mode of an HTML object
function tsToggleDisplay( idArr )
{
  for( var x = 0; x < idArr.length; x++ )
  {
    try
    {
      var toggleObj = document.getElementById( idArr[x] );
      if( toggleObj.style.display == 'none' )
      {
        toggleObj.style.display = 'inline';
      }
      else
      {
        toggleObj.style.display = 'none';
      }
    }
    catch( e )
    {
      // ignore, not found or not supported
    }
  }
}

/*
 *
 * Widget Prep Functions
 *
 */

// calendar opener
var tsCalTargets = new Array();
var tsCalForm = "";
function tsOpenCalendar()
{
  // open this where the mouse is
  var x = 0;
  var y = 0;

  if( arguments.length != 6 )
  {
    return;
  }

  evt = arguments[0];
  tsCalTargets = arguments[1].split( "," );
  tsCalForm = arguments[2];
  inDate = arguments[3];
  inFormat = arguments[4];
  timeShow = arguments[5];

  x = evt.clientX;
  y = evt.clientY;

  var h = 350;
  var w = 350;

  if( timeShow != "" && timeShow == "false" )
  {
    var h = 300;
    var w = 300;
  }

  if( x + w + 10 > document.body.clientWidth )
  {
    x = document.body.clientWidth - w - 10;
  }

  if( y + h + 10 > document.body.clientHeight )
  {
    y = document.body.clientHeight - h - 10;
  }

  var url = CommonPath + "/Widgets/calendar.asp?tsFocusForm=" + encodeURIComponent( tsCalForm );

  if( inDate != "" )
  {
    url += "&tsWidgetDate=" + encodeURIComponent( inDate );
  }

  if( inFormat != "" )
  {
    url += "&tsDateFormat=" + encodeURIComponent( inFormat );
  }

  if( timeShow != "" )
  {
    url += "&tsShowTime=" + encodeURIComponent( timeShow );
  }

  openWidget( "calendar", url, { h: h, w: w, x: x, y: y } );
}

function tsApplyCalendar( formattedDate, plainDate )
{
  for( var x = 0; x < tsCalTargets.length; x++ )
  {
    document.getElementById( tsCalTargets[x] ).value = formattedDate;
    document.getElementById( "cal::" + tsCalTargets[x] ).setAttribute( "datestr", plainDate );
  }
}

// for duration primitives
var tsDurTargets = new Array();
var tsDurForm = "";
function tsOpenDuration()
{
  // open this where the mouse is
  var x = 0;
  var y = 0;

  evt = arguments[0];
  tsDurTargets = arguments[1].split( "," );
  tsDurForm = arguments[2];

  x = evt.clientX;
  y = evt.clientY;

  if( x + 165 > document.body.clientWidth )
  {
    x = document.body.clientWidth - 165;
  }

  if( y + 290 > document.body.clientHeight )
  {
    y = document.body.clientHeight - 290;
  }

  var url = CommonPath + "/Widgets/duration.asp?tsFocusForm=" + encodeURIComponent( tsDurForm );

  if( tsDurTargets.length == 1 )
  {
    if( document.getElementById( tsDurTargets[x] ) && document.getElementById( tsDurTargets[x] ).value != "" )
    {
      url += "&tsCurrentValue=" + encodeURIComponent( document.getElementById( tsDurTargets[x] ).value );
    }
  }

  openWidget( "duration", url, { h: 290, w: 160, x: x, y: y } );
}

function tsApplyDuration( duration )
{
  for( var x = 0; x < tsDurTargets.length; x++ )
  {
    document.getElementById( tsDurTargets[x] ).value = duration;
  }
}

// Widget functions
var tsConfirmFunction = null;
var openWidgets = new Array();
var widgetIdx = 0;

function AValert( msg )
{
  var url = CommonPath + "/Widgets/alert.asp?message=" + msg;
  openWidget( "alert", url, { h: 220, w: 300 } );
}

function AVconfirm( msg, func )
{
  tsConfirmFunction = func;
  var url = CommonPath + "/Widgets/confirm.asp?message=" + msg;
  openWidget( "confirm", url, { h: 220, w: 300 } );
}

function confirmWidget( val )
{
  closeWidget( "confirm" );
  tsConfirmFunction( val )
}

function openWidget( hdl, url )
{
  var widget, shadow;
  if( openWidgets[ hdl ] == undefined )
  {
    widget = document.createElement( "iframe" );
    shadow = document.createElement( "div" );
    widget.id = "Widget::" + hdl;
    widget.className = "widget";
    widget.scrolling = "no";
    shadow.id = "Shadow::" + hdl;
    shadow.className = "drop";
    openWidgets[ hdl ] = true;
  }
  else
  {
    widget = document.getElementById( "Widget::" + hdl );
    shadow = document.getElementById( "Shadow::" + hdl );
  }

  widget.src = url;
  var args = new Array();
  if( arguments.length == 3 )
  {
    args = arguments[2];
  }

  var ht = "300px";
  var hdiv = 150;
  if( args[ "h" ] != undefined )
  {
    ht = args[ "h" ] + "px";
    hdiv = Math.round( args[ "h" ] / 2 );
  }

  var wt = "300px";
  var wdiv = 150;
  if( args[ "w" ] != undefined )
  {
    wt = args[ "w" ] + "px";
    wdiv = Math.round( args[ "w" ] / 2 );
  }

  widget.style.height = ht;
  widget.style.width = wt;
  shadow.style.height = ht;
  shadow.style.width = wt;

  // center this on the window for now
  var left = 0;
  var top = 0;

  if( args[ "x" ] == undefined )
  {
    left = document.body.clientWidth / 2 - wdiv + document.body.scrollLeft;
  }
  else
  {
    left = args[ "x" ];
  }

  if( args[ "y" ] == undefined )
  {
    top = document.body.clientHeight / 2 - hdiv + document.body.scrollTop;
  }
  else
  {
    top = args[ "y" ];
  }

  widget.style.left = left;
  widget.style.top = top;

  shadow.style.left = left + 10;
  shadow.style.top = top + 10;

  document.getElementsByTagName( "body" )[0].appendChild( shadow );
  document.getElementsByTagName( "body" )[0].appendChild( widget );
  shadow.style.zIndex = widgetIdx++;
  widget.style.zIndex = widgetIdx++;

  shadow.style.display = "inline";
  widget.style.display = "inline";

  shadow.style.position = "absolute";
  widget.style.position = "absolute";
}

function closeWidget( hdl, inMsg )
{
  document.getElementsByTagName( "body" )[0].removeChild( document.getElementById( "Widget::" + hdl ) );
  document.getElementsByTagName( "body" )[0].removeChild( document.getElementById( "Shadow::" + hdl ) );
  delete openWidgets[ hdl ];

  window.focus();

  if( inMsg != null && inMsg != "" )
  {
    AValert( inMsg );
  }
}

function resizeWidget( hdl, ht, wd )
{
  var widget = document.getElementById( "Widget::" + hdl );
  var shadow = document.getElementById( "Shadow::" + hdl );
  widget.style.height = ht;
  shadow.style.height = ht;
  widget.style.width = wd;
  shadow.style.width = wd;
  lf = document.body.clientWidth / 2 - ( Math.round( wd / 2 ) ) + document.body.scrollLeft;
  tp = document.body.clientHeight / 2 - ( Math.round( ht / 2 ) ) + document.body.scrollTop;
  widget.style.left = lf;
  shadow.style.left = lf + 10;
  widget.style.top = tp;
  shadow.style.top = tp + 10;
}

function applyWidget( hdl, inMsg, frmIdx )
{
  closeWidget( hdl, inMsg );

  var formTarget = 0;
  if( frmIdx != null )
  {
    formTarget = frmIdx;
  }

  var notifyElem = document.createElement( "INPUT" );
  notifyElem.type = "hidden";
  notifyElem.name = "tsAttachNotify";
  notifyElem.value = "1";
  document.forms[ formTarget ].appendChild( notifyElem );

  document.forms[ formTarget ].submit();
}


/*
 *  Widget drag functions
 */

var widgetdragger = null;
var shadowdragger = null;

var widgetdragX = 0;
var widgetdragY = 0;
var widgetstartX = 0;
var widgetstartY = 0;

function startWidgetDrag( hdl, mouseX, mouseY )
{
  widgetdragger = document.getElementById( 'Widget::' + hdl );
  shadowdragger = document.getElementById( 'Shadow::' + hdl );

  if( shadowdragger )
    shadowdragger.style.zIndex = widgetIdx++;

  widgetdragger.style.zIndex = widgetIdx++;

  widgetdragX = parseInt( widgetdragger.style.left );
  widgetdragY = parseInt( widgetdragger.style.top );
  widgetstartX = mouseX;
  widgetstartY = mouseY;
}

function stopWidgetDrag()
{
  widgetdragger = null;
  shadowdragger = null;
}

function moveWidget( offsetX, offsetY )
{
  if( ( widgetdragX + offsetX < 0 ) || ( widgetdragY + offsetY ) < 0 )
  {
    return;
  }

  if( widgetdragger != null )
  {
    try
    {
      widgetdragger.style.left = ( widgetdragX + offsetX ) + "px";
      widgetdragger.style.top  = ( widgetdragY + offsetY ) + "px";

      if( shadowdragger )
      {
        shadowdragger.style.left = ( widgetdragX + offsetX + 10 ) + "px";
        shadowdragger.style.top  = ( widgetdragY + offsetY + 10 ) + "px";
      }
    }
    catch( e )
    {
    }
  }
}

//

function tsSetMailLink( elem )
{
  link = document.getElementById( "mail::" + elem.id );
  img = document.getElementById( "mailimg::" + elem.id );
  if( elem.value == "" )
  {
    link.onclick = returnFalse;
    link.href = "mailto:";
    link.className = "nocursor";
    img.className = "iconno";
  }
  else
  {
    link.href = "mailto:" + elem.value;
    link.onclick = returnTrue;
    link.className = "";
    img.className = "iconup";
  }
}

function returnTrue()
{
  return true;
}

function returnFalse()
{
  return false;
}

function tsToggleIconClass( elem, css )
{
  if( elem.className != "iconno" )
  {
    elem.className = css;
  }
}

// disables submit buttons automatically when inserts/updates called
function disableSubmitButton( elem )
{
  elem.disabled = true;
  elem.form.elements[ 'doWorkReal::' + elem.name ].name = elem.name;
  elem.form.submit();
}

/*
 * Page Timers for on offer stuff, etc.
 */

var tsTimeStart = 0; // time remaining in seconds
var expMsgFlag = false;

/**
 *
 */
function tsSeedTimer()
{
  if( document.getElementById ) // IE5, NS6
  {
    tsTimerDisplayHandle = document.getElementById( "tsTimerDisplay" );
    tsOfferExpiredHandle = document.getElementById( "tsOfferExpired" );
    buyBtnHandle = document.getElementById( "buyBtn" );
  }
  else if( document.all ) // IE4
  {
    tsTimerDisplayHandle = document.all[ "tsTimerDisplay" ];
    tsOfferExpiredHandle = document.all[ "tsOfferExpired" ];
    buyBtnHandle = document.all[ "buyBtn" ];
  }
  else if ( document.layers ) // NS4
  {
    tsTimerDisplayHandle = document.layers[ "tsTimerDisplay" ];
    tsOfferExpiredHandle = document.layers[ "tsOfferExpired" ];
    buyBtnHandle = document.layers[ "buyBtn" ];
  }

  if( tsTimeStart < 0 || tsTimerDisplayHandle == null )
  {
    var expiredText = "Expired!";
    var expiredMessage = "The offer on some of your admissions has expired. These were automatically removed from your order.\n\nTo view your updated order, click on 'Shopping Cart'.";

    tsTimerDisplayHandle.innerHTML = "";
    tsOfferExpiredHandle.innerHTML = expiredText;

    if( buyBtnHandle )
    {
      buyBtnHandle.disabled = true; // disable Buy button on Billing Info page
    }

    // display alert and prompt once
    if( expMsgFlag == false )
    {
      alert( expiredMessage );
      expMsgFlag = true;
    }
  }

  if( !expMsgFlag )
  {
    if( document.getElementById || document.all )
    {
      tsTimerDisplayHandle.innerHTML = tsTimeStr( tsTimeStart );
    }
    else if( document.layers )
    {
      text = '<p class="offerTimeout">' + tsTimeStr( tsTimeStart ) + '</p>';
  		tsTimerDisplayHandle.document.open();
  		tsTimerDisplayHandle.document.write( text );
  		tsTimerDisplayHandle.document.close();
    }
    tsTimeStart--;
    setTimeout( "tsSeedTimer()", 1000 );
  }
  else
  {
    document.location = "shoppingCart.asp";
  }
}

/**
 *
 */
function tsTimeStr( seconds )
{
  hrs = new String( Math.floor( seconds / 3600 ) );
  leftover = seconds % 3600;
  mins = new String( Math.floor( leftover / 60 ) );
  secs = new String( leftover % 60 );

  hrs = hrs.length == 2 ? hrs : "0" + hrs;
  mins = mins.length == 2 ? mins : "0" + mins;
  secs = secs.length == 2 ? secs : "0" + secs;

  return hrs + ":" + mins + ":" + secs
}

/**
 *
 */
function displayOnOfferTimeout()
{
  if( document.getElementById( "tsTime" ) )
  {
    tsTimeStart = document.getElementById( "tsTime" ).innerHTML;
    var tsTimeStatus = tsTimeStr( tsTimeStart );
    tsSeedTimer();
  }
}

/**
 *
 */
function popHelp( url, w, h )
{
  w = (w) ? w : "320"; // set default if width not specified
  h = (h) ? h : "240"; // set default if height not specified

  var leftPos = 0;
  var topPos = 0;
  if (document.all || document.layers)
  {
    leftPos = ( screen.availWidth - w ) / 2;
    topPos = ( screen.availHeight - h ) / 2;
  }

  winArgs = "height=" + h + ",width=" + w + ',top=' + topPos + ',left=' + leftPos + ",alwaysRaised=1,scrollbars=1";
  winHdl = window.open( url, "onlinehelp", winArgs );
  winHdl.focus();
}

/**
 *
 */
function loadUrl( url )
{
  if( url )
  {
    if( confirm( "Are you sure?" ) )
    {
      document.location = url;
    }
  }
}

/**
 *
 */
function jumpTo( url )
{
  if( url )
  {
    document.location = url;
  }
}

/**
 *
 */
function checkout( elem )
{
  elem.form.elements[ "doWork::WSorder::insert" ].value = "Buy";
  elem.className = "btn_off";
  elem.disabled = true;
  elem.form.submit();
}

/**
 *
 */
function recalculate( elem )
{
  elem.form.action = "shoppingCart.asp";
  elem.form.submit();
}

/**
 *
 */
function addGiftCert( elem )
{
  elem.form.action = "shoppingCart.asp?AddGiftCert";
  elem.form.submit();
}

/**
 *
 */
function addDonation( elem )
{
  elem.form.action = "shoppingCart.asp?AddDonation";
  elem.form.submit();
}

/**
 *
 */
function logon( elem, nextPage )
{
  if( elem.form.elements[ "callback" ] && nextPage )
  {
    elem.form.elements[ "callback" ].value = nextPage;
  }

  elem.form.action = "doLogin.asp";
  elem.form.submit();
}

/**
 *
 */
function newUser( elem, nextPage )
{
  if( elem.form.elements[ "callback" ] && nextPage )
  {
    elem.form.elements[ "callback" ].value = nextPage;
  }

  elem.form.action = "createAccount.asp";
  elem.form.submit();
}

/**
 *
 */
function setDelItem( elem, page, id )
{
  if( elem && page && id )
  {
    elem.form.action = page;
    tsDel = document.getElementById( "tsDelete" )
    tsDel.name = id;
  }
}

/**
 *
 */
var tsAllowSubmit = true;
var submitCalled = false;

function SubmitForm( inURL )
{
  if( tsAllowSubmit )
  {
    if( !submitCalled )
    {
      var tmpData = inURL.split( "?", 2 );
      document.forms[0].action = tmpData[0];
      frmHdl = document.body.getElementsByTagName("form");

      // build hidden elements on the node
      if( tmpData.length == 2 )
      {
        var tmpElems = tmpData[1].split( "&" );
        for( var x = 0; x < tmpElems.length; x++ )
        {
          var chldData = tmpElems[x].split( "=", 2 );
          var chldElem = document.createElement( "INPUT" );
          chldElem.type = "hidden";
          chldElem.name = chldData[0];
          chldElem.value = chldData[1];
          frmHdl[0].appendChild( chldElem );
        }
      }

      // call a default method on the local form page
      try
      {
        LocalFormSubmit();
      }
      catch( e )
      {
        // ignore, the page doesn't have it
      }

      submitCalled = true;
    }

    document.forms[0].submit();
  }
}