var W3CDOM = (document.createElement && document.getElementsByTagName);
var buggyBastard = (navigator.userAgent.indexOf('MSIE') != -1 &&
    navigator.userAgent.indexOf('Mac') != -1)

if (W3CDOM)
{
    var tempDIV = document.createElement('div');
    tempDIV.className = 'overlibdiv';
}

window.onload = initOrchid;
window.onunload = exitOrchid;

function initOrchid()
{
if (!W3CDOM) return;
    initMouseovers(document.getElementsByTagName('img'));
    initNav();

    var login_timeout = "";
    var logout_warning_interval = "";

    if( login_timeout && logout_warning_interval )
    {
        warn_after = ( login_timeout - logout_warning_interval ) * 1000;
        setTimeout("startTimer("+warn_after+")", 0); 
    }
    setNavHeight();
    var newFontSize = readCookie('fontsize');
    if (newFontSize)
        changeFont(newFontSize);
    if (self.init)
    {
        init(); 
    }
    if (self.preloadImages)
    {
        preloadImages();
    }
}

function exitOrchid()
{
    if( mos_popupshown ) 
    { 
        mos_popup.close(); 
        mos_popupshown = false; 
    }
    if( typeof xit == 'function' ) 
    { 
        xit(); 
    }
}

function initNav()
{
    var x = document.getElementsByTagName('div');
    for (var i=0;i<x.length;i++)
    {
        if (x[i].className == 'nav')
        {
            var y = x[i].getElementsByTagName('li');
            for (var j=0;j<y.length;j++)
            {
                var tmp = y[j].firstChild;
                if( tmp )
                {
                    while (tmp && tmp.nodeType != 1)
                    {
                        tmp = tmp.nextSibling;
                    }
                    if( tmp )
                    {
                        tmp.onmouseover = foldOut;
                    }
                }
                var tmp2 = y[j].lastChild;
                if( tmp2 )
                {
                    while (tmp2 && tmp2.nodeType != 1)
                    {
                        tmp2 = tmp2.previousSibling;
                    }
                    if( tmp2 )
                    {
                        tmp2.onmouseout = checkFoldIn;
                    }
                }
            }
        }
    }
}



var currentFold; // contains foldout that's currently opened
var closeMenu;

var fo_timeoutid = null; // crappy ppk foldouts need a semaphore

function startFoldoutTimer()
{	
    if( fo_timeoutid ) {
        clearTimeout( fo_timeoutid );
    }
    fo_timeoutid = setTimeout("foldIn()", 1000);
}

function clearFoldoutTimer()
{

    if( fo_timeoutid )
    {
        clearTimeout( fo_timeoutid );
    }
    fo_timeoutid = null;
}

function navMouseOut(e) {
  //inside = false;
  startFoldoutTimer();
}

function navMouseOver(e) {
  inside = true;
}

function collapseMenu(e) {
   if(!e) var e = window.event;
   var tg = (window.event) ? e.srcElement : e.target;
   if(tg) {
     if(!inside && tg.parentNode.parentNode.nodeName != 'UL' && tg.parentNode.parentNode.nodeName != 'LI'){
	     foldIn();
    }
  }
}

function foldIn()
{
    if (currentFold)
    {
        currentFold.className = '';
        currentFold.parentNode.style.zIndex = '0';
    }
    currentFold = null;
    }

function foldOut(e)
{
        if (!e) var e = window.event;
        var tg = (window.event) ? e.srcElement : e.target;
        while (tg.nodeName != 'LI' && tg.nodeName != 'BODY')
                tg = tg.parentNode;
        if (tg.nodeName != 'LI') return;
        if (currentFold)
            foldIn();
        var x = tg.getElementsByTagName('div');
        if (x.length != 1) return;
        x[0].className = 'foldOut';
        tg.style.zIndex = '100';
        currentFold = x[0];
} 

function checkFoldIn(e)
{
        if (!e) var e = window.event;
        var tg = (window.event) ? e.srcElement : e.target;
        if (tg.nodeName != 'DIV') return;
        var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
        while (reltg != tg && reltg.nodeName != 'BODY')
            reltg= reltg.parentNode;
        if (reltg == tg) return;
        foldIn();
}

// ...................................................... rolloverOn
// Turn on image rollover -- switch to "on" image.
// 
function rolloverOn(img)
{
    if( img.src.match( /gif$/ ) )
    {
        img.src = ( "http://orchidsuites.net/orchid/images/" + img.name + "-on.gif" );
    }
    else if( img.src.match( /jpg$/ ) )
    {
        img.src = ( "http://orchidsuites.net/orchid/images/" + img.name + "-on.jpg" );
    }
    else if( img.src.match( /png$/ ) )
    {
        img.src = ( "http://orchidsuites.net/orchid/images/" + img.name + "-on.png" );
    }
}

// ...................................................... rolloverOff
// Turn OFF image rollover -- switch to "off" image.
// 
function rolloverOff(img)
{
    if( img.src.match( /gif$/ ) )
    {
        img.src = ( "http://orchidsuites.net/orchid/images/" + img.name + ".gif" );
    }
    else if( img.src.match( /jpg$/ ) )
    {
        img.src = ( "http://orchidsuites.net/orchid/images/" + img.name + ".jpg" );
    }
    else if( img.src.match( /png$/ ) )
    {
        img.src = ( "http://orchidsuites.net/orchid/images/" + img.name + ".png" );
    }
}

// ...................................................... getElementByName
// Return an element, given the form and the element name.
// 
function getElementByName( formname, elementname )
{ 
    var elements = eval( "document." + formname + ".elements" );
    for( var i = 0; i < elements.length; i++ )
    {
        if( elements[i].name == elementname )
        {
            return elements[i];
        }
    }
    return null;
}

var mouseOvers = new Array();
var mouseOuts = new Array();

function initMouseovers(x)
{
    for (var i=0;i<x.length;i++)
    {
        if (x[i].getAttribute('behav') == 'mouseover')
        {
            x[i].onmouseover = mouseGoesOver;
            x[i].onmouseout = mouseGoesOut;
            var suffix = x[i].src.substring(x[i].src.lastIndexOf('.'));
            mouseOuts[i] = new Image();
            mouseOuts[i].src = x[i].src;
            mouseOvers[i] = new Image();
            mouseOvers[i].src = x[i].src.substring(0,x[i].src.lastIndexOf('.')) + "-on" + suffix;
            x[i].number = i;
        }
    }
}

function mouseGoesOver()
{
    this.src = mouseOvers[this.number].src;
    this.status = 'mo';
}

function mouseGoesOut()
{
    if (!this.status) return;
    this.src = mouseOuts[this.number].src;
    this.status = '';
}

function changeFont(size)
{
    document.body.style.fontSize = size;
    setNavHeight();
}

/* Manage cookies */

function createCookie(name,value,days)
{
    if (days)
    {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name)
{
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++)
    {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name)
{
    createCookie(name,"",-1);
}

// ...................................................... save
// Save the value of a form element
// 
var savedvals = new Array();
function save( element )
{ 
    savedvals[ element.name ] = element.value;
}
// ...................................................... restore
// Restore the value of a form element
// 
function restore( element )
{ 
    element.value = savedvals[ element.name ];
}
// ...................................................... saveMain
// Save all values in the main form.
// 
function saveMain( )
{ 
    if( document.main && document.main.elements )
    {
        var elements = document.main.elements;
        if( elements.length )
        {
            for( var i = 0; i < elements.length; i++ )
            {
                savedvals[ elements[i].name ] = elements[i].value;
            }
        }
    }
}
// ...................................................... unsortRolloverOn
// Rollover the unsort icon.
// 
var saved_sortimage_index;
var saved_sortimage_src;
var saved_unsortimage_index;
var saved_unsortimage_src;
function unsortRolloverOn()
{ 
    for( var i = 0; document.images && i < document.images.length; i++ )
    {
        if(  "sort-down" == document.images[i].name
          || "sort-up" == document.images[i].name
          )
        {
            saved_sortimage_index = i;
            saved_sortimage_src = document.images[i].src;
            document.images[i].src = "http://orchidsuites.net/orchid/images/" + "sort-none.gif";
            break;
        }
        else
        {
            saved_sortimage_index = 0;
            saved_sortimage_src = '';
        }
    }
}
// ...................................................... unsortRolloverOff
// UN-Rollover the unsort icon.
// 
function unsortRolloverOff()
{ 
    if( saved_sortimage_index && saved_sortimage_src )
    {
        document.images[saved_sortimage_index].src = saved_sortimage_src;
        saved_sortimage_index = 0;
        saved_sortimage_src = '';
    }
}
// ...................................................... sortRolloverOn
// Rollover some sort icon.
// 
function sortRolloverOn( img )
{ 
    saved_sortimage_index = 0;
    saved_sortimage_src = '';
    saved_unsortimage_index = 0;
    saved_unsortimage_src = '';
    for( var i = 0; document.images && i < document.images.length; i++ )
    {
        if(  "sort-down" == document.images[i].name
          || "sort-up" == document.images[i].name
          )
        {
            if( ! saved_sortimage_index )
            {
                saved_sortimage_index = i;
                saved_sortimage_src = document.images[i].src;
                document.images[i].src = "http://orchidsuites.net/orchid/images/" + "sort-none.gif";
            }
        }
        else if( "nounsort" == document.images[i].name )
        {
            if( ! saved_unsortimage_index )
            {
                saved_unsortimage_index = i;
                saved_unsortimage_src = document.images[i].src;
                document.images[i].src = "http://orchidsuites.net/orchid/images/" + "unsort.gif";
            }
        }
    }
}
// ...................................................... sortRolloverOff
// UN-Rollover some sort icon.
// 
function sortRolloverOff()
{ 
    if( saved_sortimage_index && saved_sortimage_src )
    {
        document.images[saved_sortimage_index].src = saved_sortimage_src;
        saved_sortimage_index = 0;
        saved_sortimage_src = '';
    }
    if( saved_unsortimage_index && saved_sortimage_src )
    {
        document.images[saved_unsortimage_index].src = saved_unsortimage_src;
        saved_unsortimage_index = 0;
        saved_unsortimage_src = '';
    }
}
var alertShown = false;
// ...................................................... badvalue
// The element value was bad, so tell user and restore
// old value
// ppkpatch: 
// This function is called from everywhere, but it should work with both old Admin and new Public scripts.
// showAlertNew() is new W3C DOM validation script, only in Public pages.
// if it is present in the page, call it, and also send an HTML element.
// If it's not present, send only text info.
// To be solved eventually
//
function badValue( element, info )
{ 
    restore( element );
    if (self.showAlertNew)
        showAlertNew( element,info );
    else
        showAlert(info);
}

// ...................................................... showAlert
// Display an alert if one hasn't been displayed for
// this particular call to checkForm().
//
function showAlert( text )
{
    if( ! alertShown )
    {
         alert( text );
        alertShown = true;
    }
}  

// ...................................................... confirmTimeout
// The session is about to time out, so open a popup
// to inform the user.
// 
function confirmTimeout()
{
    var ratio = "1.1";
    var h = 150;
    if( ratio )
    {
        h = Math.abs(ratio * h);
    }
    
    showPopup( 'ConfirmTimeout', '0', h, 500  );
}
// ...................................................... startTimer
// Start timer to count down milliseconds until user
// should be informed that session is about to expire.
// 
function startTimer( timeLeft )
{
    setTimeout( "confirmTimeout()", timeLeft );
}
// ...................................................... trim
// Trims whitespace off each side of a string.
// 
function trim( s )
{
    if( s )
    {
        s = s.replace( /^\s+/, "" );
        s = s.replace( /\s+$/, "" );
    }
    return s;
}

// ...................................................... getDateDifference
// Get the difference between two dates
//
function getDateDifference( date1, date2 )
{  
    //split date in year, month, day

    dateSplitter1 = date1.split("/");  
    dateSplitter2 = date2.split("/");         
    var newdate1 =new Date(dateSplitter1[2], dateSplitter1[0]-1, dateSplitter1[1]);
    var newdate2 = new Date(dateSplitter2[2], dateSplitter2[0]-1, dateSplitter2[1]);
    
    //Set 1 day in milliseconds

    var one_day=1000*60*60*24



    //Calculate difference btw the two dates, and convert to days

    return Math.ceil((newdate1.getTime()-newdate2.getTime())/(one_day));
}

// ...................................................... dateChanged
// Checks formatting for changed date text input.
// Also guesses what the year should be.  If difference
// between current year and entered year is > 85,
// 100 is added to the year.  In other words, the
// date is assumed to be in the future.
// 
function dateChanged( element, monthyear )
{   var value = trim( element.value );
    if( value )
    {
        if( monthyear )
        {
            var thedate = value.split( "/" );
            if( 2 == thedate.length )
            {
                value = thedate[0] + "/01/" + thedate[1];
            }
            else if( 3 == thedate.length )
            {
                value = thedate[0] + "/01/" + thedate[2];
            }
            else
            {
                badValue( element, "Sorry, '" + element.value + "' is not a valid date.  Please enter a date in mm/yyyy format." );
                return;
            }
        }
        var today = new Date();
        var currentyear = today.getFullYear();
        var ts = Date.parse( value );
        var dt = new Date(ts);
        var m = dt.getMonth() + 1;
        var d = dt.getDate();
        var y = dt.getFullYear();
        if( isNaN(m) || isNaN(d) || isNaN(y) )
        {
            if( monthyear )
            {
                badValue( element, "Sorry, '" + element.value + "' is not a valid date.  Please enter a date in mm/yyyy format." );
            }
            else
            {
                badValue( element, "Sorry, '" + element.value + "' is not a valid date.  Please enter a date in mm/dd/yyyy format." );
            }
        }
        else
        {
            if( currentyear - y > 85 )
            {
                y = y + 100;
            }
            if( monthyear )
            {
                element.value = m + "/" + y;
            }
            else
            {
                element.value = m + "/" + d + "/" + y;
            }
        }
    }
}
// ...................................................... wordChanged
// Checks to make sure the input is a single word.
// 
function wordChanged( element )
{   var value = trim( element.value );
    if( value )
    {
        if( value.match( /^.*\s.*$/ ) )
        {
            badValue( element, "Sorry, '" + element.value + "' contains a whitespace character.  It may not contain any spaces." );
            alertShown = false;
            return;
        }
    }
}
// ...................................................... amountChanged
// Checks formatting for changed currency input (US style)
// 
function amountChanged( element )
{   var value = trim( element.value );
    if( value )
    {
        if( !value.match( /^\d+(\.\d\d)?$/ ) )
        {
            badValue( element, "Sorry, '" + element.value + "' is not a valid amount.  Please enter a whole number, such as 78, or a decimal value, such as 27.45" );
            alertShown = false;
            return;
        }
    }
}
// ...................................................... integerChanged
// Checks to make sure the input is an integer.
// 
function integerChanged( element )
{   var value = trim( element.value );
    if( value )
    {
        if( !value.match( /^\d+$/ ) )
        {
            badValue( element, "Sorry, '" + element.value + "' is not a valid number.  Please enter a positive integer." );
            alertShown = false;
            return;
        }
    }
}
// ...................................................... checkRange
// Checks value of a bounded integer.
// 
function checkRange( element, min, max )
{   var value = trim( element.value );
    if( value )
    {
        if( !value.match( /^\d+$/ ) )
        {
            badValue( element, "Sorry, '" + element.value + "' is not a valid number.  Please enter a positive integer." );
            alertShown = false;
            return;
        }
        else if( ( min && value < min ) || ( max && value > max ) )
        {
            badValue( element, "Sorry, " + element.value + " is not a number from " + min + " to " + max + ".  Please enter another number." );
            alertShown = false;
            return;
        }
    }
}
// ...................................................... phoneChanged
// Checks formatting for changed phone number text input.
// 
function phoneChanged( element )
{   var val = trim( element.value );
    var phone_format = "";
    if( val.length > 0 && phone_format == "us" )
    {
        if( val.match( /^1/ ) )
        {
            val = val.substr( 1 );
        }
        val = val.replace( /\D/g, "" )
        if( val.length < 10 )
        {
            badValue( element, "The phone number is garbled or not long enough!" );
            alertShown = false;
            return;
        }
        else if( val.length > 10 )
        {
            badValue( element, "The phone number is garbled or too long!" );
            alertShown = false;
            return;
        }
        var acode = val.substring(0, 3);
        var exchange = val.substring(3,6);
        var number = val.substring(6,10);
        val = acode + "-" + exchange + "-" + number;
    }
    element.value = val;
}
// ...................................................... emailChanged
// Checks formatting for changed email text input.
// 
function emailChanged( element )
{   var val = trim( element.value );
    if( val.length > 0 )
    {
        parts = val.split( "@" );
        if( 2 != parts.length || parts[0].match( /^.*\s.*$/ ) )
        {
            badValue( element, "That doesn't look like a valid email address." );
            alertShown = false;
            return;
        }
        domainparts = parts[1].split( "." );
        if ( domainparts.length < 2 )
        {
            badValue( element, "That doesn't look like a valid email address." );
            alertShown = false;
            return;
        }
        else
        {
            for( var i=0; i < domainparts.length; i++ )
            {
                if( i + 1 == domainparts.length )
                {
                    if( ! domainparts[i].match( /^[A-Za-z]{2,10}$/ ) )
                    {
                        badValue( element, "That doesn't look like a valid email address." );
                        alertShown = false;
                        return;
                    }
                }
                else
                {
                    // Had to spell out letters and numerals because
                    // a hyphen was included and it seemed to break the
                    // use of character ranges.
                    if( ! domainparts[i].match( /^[0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-]+$/ ) )
                    {
                        badValue( element, "That doesn't look like a valid email address." );
                        alertShown = false;
                        return;
                    }
                }
            }
        }
    }
    return true;
}

// ...................................................... codeChanged
// Checks to make sure the input is a single word, capitalized
// and alphanumeric.
function codeChanged( element )
{   var val = trim( element.value );
    if( val.length > 0 )
    {
        if( val.match( /[^0-9A-Z\\_#%-]/ ) )
        {
            badValue( element, "Sorry, '" + element.name + "' must contain only numbers or uppercase letters" );       
            alertShown = false;
            return;
        }
    }
    element.value = val;
}




///  ***********************************************************   from orchid-js



// ...................................................... showPopup
// Display a popup.
// 
var mos_popupshown = false;
var mos_popup;
function showPopup( display, id, h, w )
{
    if( ! h ) h = 400;
    if( ! w ) w = 500;
   
    var ratio = "1.1";
    if( ratio )
    {
        h = Math.abs(ratio * h);
    }
    if( mos_popupshown )
    {
        mos_popup.resizeTo( w, h );
    }
    mos_popup = window.open( "/ht/display/"+display+"/i/" + id + "/displaytype/popup", "mos_popup", "height="+h+",width="+w+",resizable,scrollbars");
    mos_popup.focus();
}


function sizeText(amount)
{
    var fontSize = (document.body.style.fontSize) ? parseFloat(document.body.style.fontSize) : 0.75;
    var newFontSize = fontSize + (amount/10) + 'em';
    changeFont(newFontSize);
    createCookie('fontsize',newFontSize,30);
    return false;    
}


function setNavHeight()
{
    if (!W3CDOM) return;
    var compare = new Array('nav2','main','extra');
    for (var i=0;i<compare.length;i++)
    {
        if (document.getElementById(compare[i]))
            document.getElementById(compare[i]).style.height = 'auto';

    }
    if (document.getElementById('nav2') &&
        document.getElementById('nav2').parentNode.className != 'normal') 
    {
        var maxHeight = 0;
        for (var i=0;i<compare.length;i++)
        {
            if (document.getElementById(compare[i]))
            {
                var newHeight = document.getElementById(compare[i]).offsetHeight;
                if (newHeight > maxHeight) maxHeight = newHeight;
            }
        }
        for (var i=0;i<compare.length;i++)
        {
            if (document.getElementById(compare[i]))
                document.getElementById(compare[i]).style.height = maxHeight + 'px';
        }
    }
}