/**
 * @file
 * Core class.
 *
 * @author Shannon M. Rause <shannon.rause@creativeflavor.com>
 * @version $Revision: 1.8 $
 * @version $Name:  $
 * @version $Id: Core.js,v 1.8 2006/09/17 17:12:16 smr Exp $
 *
 * Copyright 2005-2006 Creative Flavor, Inc. All rights reserved.
 * 
 * Please see the LICENSE file for specific licensing information.
 * If you did not receive this file or are unable to locate it, 
 * please contact licensing@creativeflavor.com.
 */

/**
 * Core class.
 *
 * @public
 */
function Core()
{
} // Core


// error codes (must match Error.php!
Core.errorDbDuplicate   = 'duplicate';
Core.errorDbItemInUse   = 'in use';
Core.errorInvParam      = 'invalid param';

Core._userAjaxCommandCb = null;
Core._windowCloseTimer = null;


/**
 * Sends an ajax request.
 *
 * @param data    Data to pass request as POST data.
 * @param cb      User function to call when response is received.
 * @param cbData  Callback data.
 *
 * @public
 */
Core.ajaxSendXml = function(data,
                            cb,
                            cbData)
{
   var ajax = new Ajax();
   ajax.sendXml('/ajax.php',
                data,
                cb,
                cbData);
} // ajaxSendXml


/**
 * Simple function that takes a command name and an array
 * of parameters, builds a request and then calls the callback
 * (hopefully) upon completion.
 *
 * @param cmd     Name of command to execute.
 * @param params  Array of key/value pairs.
 * @param cb      Callback to run opon completion.
 * @param cbData  Optional data that will be passed to the callback 
 *                   unmodified.
 */
Core.ajaxSendCommand = function(cmd,
                                params,
                                cb,
                                cbData)
{
   var ajax = new Ajax();
   var data = {
      'cmd'       : cmd,
      'userData'  : cbData
   }

   params['cmd'] = cmd;
   Core._userAjaxCommandCb = cb;
   Core.ajaxSendXml(params,
                    Core._ajaxCommandCallback,
                    data);
} // ajaxSendCommand


/**
 * Displays an error message.
 *
 * @param msg  Error message to display.
 *
 * @public
 */
Core.displayError = function(msg)
{
   var div = document.getElementById('errorBlock');
   Utils.removeChildren(div);
   div.appendChild(document.createTextNode(msg));
   div.style.display = 'block';
} // displayError


/**
 * Displays a message.
 *
 * @param msg  Message to display.
 *
 * @public
 */
Core.displayMessage = function(msg)
{
   var div = document.getElementById('messageBlock');
   Utils.removeChildren(div);
   div.appendChild(document.createTextNode(msg));
   div.style.display = 'block';
} // displayMessage


/**
 * Enables/disables access controls as necessary.
 *
 * @param rb   Radio button that was clicked.
 *
 * @public
 */
Core.enableAccessControls = function(rb)
{
   var enable = true;

   if (document.adminForm.inherit[0].checked)
   {
      document.adminForm.allowAll[0].disabled = 'disabled';
      document.adminForm.allowAll[1].disabled = 'disabled';
      enable = false;
   } // if
   else
   {
      document.adminForm.allowAll[0].disabled = '';
      document.adminForm.allowAll[1].disabled = '';

      if (document.adminForm.allowAll[0].checked)
      {
         enable = false;
      } // if
   } // else

   if (enable)
   {
      document.adminForm['groups[]'].disabled = '';
      document.adminForm.ips.disabled = '';
      document.adminForm['users[]'].disabled = '';
   } // if
   else
   {
      document.adminForm['groups[]'].disabled = 'disabled';
      document.adminForm.ips.disabled = 'disabled';
      document.adminForm['users[]'].disabled = 'disabled';
   } // else
} // enableAccessControls


/**
 * Handles a pager page change event.
 *
 * @param select        The selct DOM object.
 * @param itemsPerPage  Number of items per page.
 *
 * @public
 */
Core.onChangePagerPage = function(select,
                                  itemsPerPage)
{
   // setup limit/offset.
   var limit = '_limit/' + itemsPerPage + '/';

   if (select.value > 1)
   {
      var offset = '_offset/' + ((select.value - 1) * itemsPerPage) + '/';
   } // if
   else
   {
      var offset = '';
   } // else


   // find and delete current limit and offset..
   var path = '';
   var arr = document.location.pathname.split('/');
   var i = 0;

   while (i < arr.length)
   {
      if ((arr[i] == '_limit') ||
          (arr[i] == '_offset'))
      {
         // skip key and the value.
         i++;
      } // if
      else if (arr[i])
      {
         path += '/' + arr[i];
      } // else

      i++;
   } // while

   document.location.pathname = path + '/' + limit + offset;
} // onChangePagerPage


/**
 * Opens a window.
 *
 * @param url        URL to display in window.
 * @param title      Title of window.
 * @param width      Width of window.
 * @param height	   Height of window.
 * @param scrollbars 1 to have scrollbars, 0 for none.
 *
 * @return Newly created Window.
 *
 * @public
 */
Core.openWindow = function(url,
                           title,
                           width,
                           height,
                           scrollbars)
{
   var x = (640 - width) / 2;
   var y = (480 - height) / 2;

   if (screen)
   {
      y = (screen.availHeight - height) / 2;
      x = (screen.availWidth - width) / 2;
   } // if

   if (screen.availWidth > 1800)
   {
      x = ((screen.availWidth / 2) - width) / 2;
   } // if

   params = 'width='    + width  + ',' +
            'height='   + height + ',' +
            'screenX='  + x      + ',' +
            'screenY='  + y      + ',' +
            'top='      + y      + ',' +
            'left='     + x      + ',' +
            'dependent=yes,'  +
            'directories=no,' +
            'location=no,'    +
            'menubar=no,'     +
            'status=no,'      +
            'toolbar=no';

   if (scrollbars)
   {
      params += ',scrollbars=yes';
   } // if
   else
   {
      params += ',scrollbars=no';
   } // else

   newWin = window.open(url,
                        title,
                        params);

   return (newWin);
} // openWindow


/**
 * Opens a window with an image url.
 * Note that window will be automatically closed on a blur event.
 * Also note that window will be 50px wider/taller than given width/height
 * to prevent IE scrollbars.
 *
 * @param imgUrl  Image URL to display in window.
 * @param title   Title of window.
 * @param width   Width of window.
 * @param height	Height of window.
 *
 * @return Newly created Window.
 *
 * @public
 */
Core.openWindowImg = function(imgUrl,
                              title,
                              width,
                              height)
{
   newWin = Core.openWindow('',
                            title,
                            width + 50,
                            height + 50);
   newWin.document.write('<html><head><script src="/scripts/core/Core.js" language="javascript" type="text/javascript"></script></head><body onblur="Core.startWindowCloseTimer(5);" onfocus="Core.stopWindowCloseTimer();"><img src="' + imgUrl + '" /></body></html>');
   newWin.document.close();

   return (newWin);
} // openWindowImg


/**
 * This sets a 15 second timer after which the current window will be closed.
 * stopWindowCloseTimer() can be called to stop it.
 *
 * @param secs Number of seconds for timer.
 *
 * @public
 */
Core.startWindowCloseTimer = function(secs)
{
   Core._windowCloseTimer = window.setTimeout('window.close()',
                                              secs * 1000)
} // startWindowCloseTimer


/**
 * Stops the timer created w/ startWindowCloseTimer().
 *
 * @public
 */
Core.stopWindowCloseTimer = function()
{
   if (Core._windowCloseTimer)
   {
      window.clearTimeout(Core._windowCloseTimer);
      Core._windowCloseTimer = null;
   } // if
} // stopWindowCloseTimer


/**
 * This updates the debug response div with the given text for the purposes of
 * displaying an AJAX response.
 *
 * @param text Text to display.
 *
 * @public
 */
Core.updateResponse = function(text)
{
   if (text)
   {
      var div = document.getElementById('coreDebugResponse');

      if (div)
      {
         Utils.removeChildren(div);
            
         var h1 = document.createElement('h1');
         div.appendChild(h1);

         h1.appendChild(document.createTextNode('AJAX Response'));

         var p = document.createElement('p');
         var temp = text.split('\n');

         for (i in temp)
         {
            p.appendChild(document.createTextNode(temp[i]));
            p.appendChild(document.createElement('br'));
         } // for

         div.appendChild(p);
      } // if
   } // if
} // updateResponse


/**
 * Callback from Core.ajaxSendCommand().
 *
 * @param obj     Returned object.
 * @param data    Callback data.
 * @param status  HTTP status of response (i.e. 200).
 * @param reason  Status text of response (i.e. OK).
 *
 * @private
 */
Core._ajaxCommandCallback = function(obj,
                                     data,
                                     status,
                                     reason)
{
   if ((Core._userAjaxCommandCb) &&
       (data.cmd))
   {
      if ((obj) &&
          (obj[data.cmd]))
      {
         Core._userAjaxCommandCb(obj[data.cmd],
                                 data.userData,
                                 status,
                                 reason);
      } // if
      else
      {
         Core._userAjaxCommandCb(null,
                                 data.userData,
                                 status,
                                 reason);
      } // else
   } // if
} // _ajaxCommandCallback
