// ------------------------------------------------------------------------------------------------
//
// File:                RescueDB.js
//
// Description :        Javascript for the Rescue DB Applications.
//
// Author(s):           Michael G. Laris
//
// ------------------------------------------------------------------------------------------------
// Copyright (c) 2008, Summit Research, Inc. All Rights Reserved
// ------------------------------------------------------------------------------------------------
// This document contains unpublished, confidential and proprietary information
// of Summit Research.  No disclosure or use of any portion of these materials
// may be made without the express written consent of Summit Research.
// ------------------------------------------------------------------------------------------------

var Console       = null;
var VisImageIndex = null;

//
// Build an array of tab names and initial state used in maintaining the tabs.
//
var tabStateString;
var tabNames;
var tabState;

// ------------------------------------------------------------------------------------------------
//
// Function Name:       debug
//
// Description:         Open a window for debugging messages.
//
// Parameters:          None.
//
// Returns:             None.
//
// Comments:            Note that we purposely do not call close().  By leaving the
//                      document open we are able to append to it later.
//
// ------------------------------------------------------------------------------------------------

function debug(msg)
{
   //
   // Open a window the first time we are called, or after an existing
   // console window has been closed.
   //
   if ((Console == null) || (Console.closed)) {
      Console = window.open ("", "console", "width=600,height=300,resizable");
      Console.document.open ("text/plain");
   }

   Console.focus();                 // Make the window visible
   Console.document.writeln(msg);   // Output the message to it
}

// ------------------------------------------------------------------------------------------------
//
// Function Name:       initImageStack
//
// Description:         Initialize the array of image indexex to the correct size and initial
//                      value when the body of the HTML page is loaded.
//
// Parameters:          Number of images stack on the page.
//
// Returns:             None.
//
// Comments:            None.
//
// ------------------------------------------------------------------------------------------------

function initImageStack(count)
{
   var index;

   VisImageIndex = new Array(count);

   for (index=0; index<count; index++) {
      VisImageIndex[index] = 0;
   }

}

// ------------------------------------------------------------------------------------------------
//
// Function Name:       showNext
//
// Description:         Show the next highest z-index image.  This entails hiding the currently
//                      visible image and showing the next highest z-index image, and looping
//                      at the high-end.
//
// Parameters:          Number of images in the stack.
//
// Returns:             None.
//
// Comments:            None.
//
// ------------------------------------------------------------------------------------------------

function showNext(max, index)
{
   var cimage = document.getElementById("image-" +  index + "-" + VisImageIndex[index]);
   var nimage = document.getElementById("image-" +  index + "-" + (VisImageIndex[index]+1)%max);

   if (cimage != null) cimage.style.display = "none";
   if (nimage != null) nimage.style.display = "";

   VisImageIndex[index] = (VisImageIndex[index] + 1) % max;

}

// ------------------------------------------------------------------------------------------------
//
// Function Name:       setCommand
//
// Description:         Set the value of the COMMAND parameter on a form when a SUBMIT button is
//                      pressed.
//
// Parameters:          ID of the form to alter;
//                      Value of the command.
//
// Returns:             None.
//
// Comments:            None.
//
// ------------------------------------------------------------------------------------------------

function setCommand (formId, cmdValue)
{
   var form = document.getElementById(formId);

   form.action += "?COMMAND=" + cmdValue;

}

// ------------------------------------------------------------------------------------------------
//
// Function Name:       showPrev
//
// Description:         Show the next lowest z-index image.  This entails hiding the currently
//                      visible image and showing the next lowest z-index image, and looping
//                      at the low-end.
//
// Parameters:          Number of images in the stack.
//
// Returns:             None.
//
// Comments:            None.
//
// ------------------------------------------------------------------------------------------------

function showPrev(max, index)
{
   var cimage = document.getElementById("image-" +  index + "-" + VisImageIndex[index]);
   var nimage = document.getElementById("image-" +  index + "-" + (VisImageIndex[index]-1+max)%max);

   if (cimage != null) cimage.style.display = "none";
   if (nimage != null) nimage.style.display = "";

   VisImageIndex[index] = (VisImageIndex[index] - 1 + max) % max;

}

// ------------------------------------------------------------------------------------------------
//
// Function Name:       verifyComment
//
// Description:         Verify that the comment is not empty.
//
// Parameters:          None.
//
// Returns:             None.
//
// Comments:            Invoked by the "oKeyUpk" method for the TEXTBOX control.
//
// ------------------------------------------------------------------------------------------------

function verifyComment()
{
   var comment      = document.getElementById("comment");
   var updateButton = document.getElementById("adminUpdateBtn");
   var trimmed;

   //
   // Get the value of the textarea and then trim the leading and trailing whitespace.
   // if the resulting string is not an empty string, then removes the contents of the
   // "commentReq" span.
   //
   var trimmed = comment.value.replace(/^\s+|\s+$/g, '');
   if (trimmed != '') {
      updateButton.disabled = false;
   } else {
      updateButton.disabled = true;
   }

}     /* verifyMessage() */

// ------------------------------------------------------------------------------------------------
//
// Function Name:       addEvent
//
// Description:         Adds an event listener to an object.
//
// Parameters:          o : (REQUIRED) Object that will receive the listener
//                      e : (REQUIRED) Event name without the "on" prefix (click, mouseover, ...)
//                      f : (REQUIRED) Function that will be called when the event occurs.  The
//                                     event object will be sent as argument to this function
//                                     Besides the normal properties, it will ALWAYS have:
//
//                                     target: object that generated the event
//                                     key: keeps the character key code on keyboard events
//                                     stopPropagation: method to avoid the event propagation
//                                     preventDefault: method to avoid the default action
//
//                                     the preventDefault method can be emulated by returning
//                                     "false" in the function
//                      s : (OPTIONAL) Scope (who the "this" inside the callback will refer to)
//                                     that will be used when the function get invoked, the default
//                                     value is the object on the first argument
//
// Returns:             void
//
// Comments:            http://jsfromhell.com  Author: Carlos R. L. Rodrigues
//
// ------------------------------------------------------------------------------------------------

addEvent = function(o, e, f, s){
    var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
    r[r.length] = [f, s || o], o[e] = function(e){
        try{
            (e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
            e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
            e.target || (e.target = e.srcElement || null);
            e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
        }catch(f){}
        for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
        return e = null, !!d;
    }
};

// ------------------------------------------------------------------------------------------------
//
// Function Name:       enterAsTab
//
// Description:         The function will add the tabulation through the enter key for all the
//                      inputs, except <select>'s (enter is used to select an option) and
//                      <textarea>'s (enter is used to break lines).  When the last element is
//                      reached the default behaviour is to get back to the first element.
//
// Parameters:          f: HTMLFormElement
//                      a: (OPTIONAL) Jump always, even on <selec> and <textarea> (Boolean = false]):
//
// Returns:             void
//
// Comments:            http://jsfromhell.com  Author: Jonas Raoni Soares Silva
//
// ------------------------------------------------------------------------------------------------

enterAsTab = function(f, a){
    addEvent(f, "keypress", function(e){
        var l, i, f, j, o = e.target;
        if(e.key == 13 && (a || !/textarea|select/i.test(o.type))){
            try {
               for(i = l = (f = o.form.elements).length; f[--i] != o;);
               for(j = i; (j = (j + 1) % l) != i && (!f[j].type || f[j].disabled || f[j].readOnly || f[j].type.toLowerCase() == "hidden"););
               e.preventDefault(), j != i && f[j].focus();
            } catch(e) {
            }
        }
    });
};

// ------------------------------------------------------------------------------------------------
//
// Function Name:       toggleTab
//
// Description:         Open the given tab by name, and close all of the other tabs in the page.
//
// Parameters:          tabName : Name of the tab to open
//
// Returns:             None.
//
// Comments:            Invoked by the "onclick" method for the RANGE checkbox.
//
// ------------------------------------------------------------------------------------------------

function toggleTAB( tabName )
{
   var tabID    = document.getElementById( tabName );
   var tabTitle = tabID.getAttribute('title');

   //
   // Walk the list of divisions and change any DIV with the class ON or SHOW and
   // change the class to be OFF or HIDE.  This makes all tabs off and all divisions
   // of the tab-set hidden.
   //
   var elsDIV   = document.getElementsByTagName('DIV');

   for (var z=0; z<elsDIV.length; z++) {
      elsDIV[z].className = elsDIV[z].className.replace ('show', 'hide');
      elsDIV[z].className = elsDIV[z].className.replace ('on',   'off' );
   }

   //
   // Set the desired tab to be on, using the tab name passed into the function.  Use
   // the TITLE field of the tab as the name of the division, and set it to SHOW.
   //
   tabID.className = 'on';
   document.getElementById( tabTitle ).className = "show";

}

// ------------------------------------------------------------------------------------------------
//
// Function Name:       toggleTab
//
// Description:         Open the given tab by name, and close all of the other tabs in the page.
//
// Parameters:          tabName : Name of the tab to open
//
// Returns:             None.
//
// Comments:            Invoked by the "onclick" method for the RANGE checkbox.
//
// ------------------------------------------------------------------------------------------------

function initTABState ()
{
   tabNames = tabStateString.split( ";" );
   tabState = new Array();
   for (var z=0; z<tabNames.length; z++) {
     var tempArray = tabNames[z].split( "=" );
     tabNames[z] = tempArray[0];
     tabState[z] = tempArray[1];
   }

}
