/******************************************************************
 * File to hold values for window names used in the application.
 * 
 * All window names should have a prefix of either VIEW or EDIT as this
 * is used by the checkOpenWindow function to determine if a warning needs
 * to be displayed when an edit window is about to be repalced with another
 * page
 *
 * @author Roger Davies
 *
 * History:
 * 06-Dec-04  Roger Davies          Created
 * 17-Dec-04  Roger Davies          Focus window on cancel - change text for
 *                                  user profile
 * 17-Dec-04  Roger Davies          Added code to refocus the previous window
 *                                  in case of cancel on single window alert
 * 20-Dec-04  Roger Davies          Added support for form based warnings
 * 05-Jan-05  Roger Davies          Reuse window management cookies
 * 05-Jan-05  Roger Davies          Before we force the refocus after warning
 *                                  window, check that they have not already
 *                                  closed it.
 * 05-Jan-05  Roger Davies          Changed warning message
 * 06-Jan-05  Roger Davies          Changed warning message to add - before form
 *
 */

var WINDOWMANAGEMENT_CONST_CS_WIN_MAX = 16; // Maximum number of open windows

var WINDOWMANAGEMENT_CONST_WIN = "win"; // Prefix for window name cookie
var WINDOWMANAGEMENT_WINDOW_EDIT_MODE = WINDOWMANAGEMENT_CONST_WIN + "Edit"; // Must match value defined in com.oocl.frm.util.jsp.WindowNames
var WINDOWMANAGEMENT_WINDOW_VIEW_MODE = WINDOWMANAGEMENT_CONST_WIN + "View"; // Must match value defined in com.oocl.frm.util.jsp.WindowNames
var WINDOWMANAGEMENT_CONST_SETFOCUS = "[setFocus]"; // Window cookie suffix to indicate the focus needs to be set

var editMode;

/**
 * Keep setting the edit mode for this window while it is open
 */
function windowManagement_setEditMode() { 
  if ( editMode != "")
  {
    windowManagement_setExpiringCookie(
      WINDOWMANAGEMENT_CONST_WIN + window.name, editMode);
    setTimeout('windowManagement_setEditMode()',15000);
    setTimeout('windowManagement_checkSetFocus()',100);
  }
}

/**
 * Check if the window needs to be focused due to cancel on single window click
 */
function windowManagement_checkSetFocus()
{
  var cookieName = WINDOWMANAGEMENT_CONST_WIN + window.name;
  var windowCookie = windowManagement_getCookie(cookieName);
  if (windowCookie.indexOf(WINDOWMANAGEMENT_CONST_SETFOCUS) != -1 )
  {
    windowManagement_setExpiringCookie(
      cookieName, windowCookie.substring(0, windowCookie.length - 10));
    window.focus();
  }
  setTimeout('windowManagement_checkSetFocus()',100);
}

/**
 * Open page - called from body onload - sets cookies for page
 *
 * @param mode       The window mode - from com.oocl.frm.util.jsp.WindowNames
 * @param formName   The form name on the page
 */
function windowManagement_openPage(mode, formName)
{
 if ( mode != WINDOWMANAGEMENT_WINDOW_EDIT_MODE && mode != WINDOWMANAGEMENT_WINDOW_VIEW_MODE)
 {
  alert("Error incorrect mode on windowManagement_openPage(mode, formName) - it should be either " + WINDOWMANAGEMENT_WINDOW_EDIT_MODE + " or " + WINDOWMANAGEMENT_WINDOW_VIEW_MODE);
 }
 if ( formName == undefined )
 {
  alert("Error missing form name in windowManagement_openPage(mode, formName)");
 }
 editMode = mode + formName;
 windowManagement_setEditMode();
}

/** 
 * Close page - called from body unload - clears cookies for page
 */
function windowManagement_closePage()
{
  windowManagement_deleteCookie(WINDOWMANAGEMENT_CONST_WIN + window.name);
}

/**
 * Open window
 *
 * @param url        The URL to open in window
 * @param windowName The name of the window to open
 * @param windowType The open window options
 * 
 * @return The window opened or null if could not open due to user
 *         canceling request to avoid discard of existing data or the
 *         maximum open windows being reached.
 */
function windowManagement_openWindow(url, windowName, windowType)
{
  var cookieName = WINDOWMANAGEMENT_CONST_WIN + windowName;
  var windowCookie = windowManagement_getCookie(cookieName);
  var myNewWin;

  if (windowCookie.indexOf(WINDOWMANAGEMENT_WINDOW_EDIT_MODE) == 0 )
  {
    var editFormName = windowCookie.substring(WINDOWMANAGEMENT_WINDOW_EDIT_MODE.length);
    var warningMsg="";
    var message = windowManagement_getWarningMessage(windowName, editFormName);

    warningMsg+="The system detects you have an incomplete ";
    warningMsg+=message;
    warningMsg+=" form which will be overwritten if you proceed."
    warningMsg+="\nWhat would you like to do?";
    warningMsg+="\n\n- Click 'OK' to proceed to the new";
    warningMsg+= " form (all previously unsaved data would be lost).";
    warningMsg+="\n- Click 'Cancel' to resume with the existing form.";

    if ( ! confirm(warningMsg))
	  {
      // Let's check that they haven't closed the window
      windowCookie = windowManagement_getCookie(cookieName);
      if ( windowCookie != "" )
      {
        windowManagement_setExpiringCookie(
          cookieName, windowCookie + WINDOWMANAGEMENT_CONST_SETFOCUS);
      }
      return null;
	  } 
  }

  // If window not open we need to check the maximum open count
  if ( windowCookie == "" )
  {
    if ( windowManagement_checkWindowNum() == false )
    { 
      return null;
    }
  }
  //return window.open(url, windowName, windowType);
  myNewWin = window.open(url, windowName, windowType);
  if ((myNewWin != null
  &&   myNewWin != undefined)) {
       myNewWin.focus();	
  }	  
  
  return myNewWin;
}

/**
 * Check open window count does not exceed maximum
 *
 * @return true if maximum not reached, otherwise false
 */
function windowManagement_checkWindowNum() {
  var count=0;
  var index = 0;
  while((index = document.cookie.indexOf("=" + WINDOWMANAGEMENT_CONST_WIN, index)) != -1 )
  {
    count++;
    index++;
  }

  if (count < WINDOWMANAGEMENT_CONST_CS_WIN_MAX)
  {
    return true
  }
  else
  {
    alert("Maximum allowable opened windows has been reached. Please close unused " + WINDOWMANAGEMENT_CONST_CS_STR + " windows before proceeding further.")
    return false
  }       
}

/**
 * Delete cookie - required when a window is reused since the window name
 * is changed prior to the body being unloaded
 */
function windowManagement_deleteCookie(id)
{
  var todays_date = new Date();
  var expires_date = new Date(todays_date.getTime() - 365*24*60*60000); // 1 year from now	
  document.cookie = id + "=; expires=" + expires_date.toGMTString() ;
}

/**
 * Get cookie for name
 *
 * @param name The cookie name
 *
 * @return String The cookie value or empty string if not defined
 */
function windowManagement_getCookie(name)
{
 var allCookie, CookieVal, length,start,end;
 cookieVal="";
 name=name+"=";  //append equals to avoid false matches.
 allCookie=document.cookie;
 length=allCookie.length;
 if (length>0)
 {//no cookies - user is probably incinerating cookies.
   start=allCookie.indexOf(name,0)
   if (start!=-1)
   {//if string appeared - otherwise cookie wasn't set.
	   start+=name.length;
	   end=allCookie.indexOf(";",start);
	   if (end==-1)
     {
       end=length;
     }
	   cookieVal=unescape(allCookie.substring(start,end));
   }
  }
  return(cookieVal);
}

/**
 * Set cookie for name
 *
 * @param name  The cookie name
 * @param value The cookie value
 *
 * @return String The cookie value or empty string if not defined
 */
function windowManagement_setExpiringCookie(name, value)
{
  var todays_date = new Date();
  var expires_date = new Date(todays_date.getTime() + 20000); // 20 sec from now 
  document.cookie = name + "=" + escape(value) + "; expires=" + expires_date.toGMTString() ;
}

/**
 * Get window title for window name.
 *
 * @param windowName The window name as defined in com.oocl.frm.jsp.util.WindowNames
 *
 * @return String The window title
 */
function windowManagement_getWindowTitleForName(windowName)
{
  for(i=0; i<windowFormNames_windowTitleMapping.length; i+=2)
  {
    mappingWinName = windowFormNames_windowTitleMapping[i];
    mappingWinTitle = windowFormNames_windowTitleMapping[i+1];
    if ( mappingWinName == windowName )
    {
      return mappingWinTitle;
    }
  }
  return "windowFormNames_getWindow - no mapping for " + windowName;
}

/**
 * Has window title mapping
 *
 * @param windowName The window name as defined in com.oocl.frm.jsp.util.WindowNames
 *
 * @return boolean <code>true</code> if has mapping, otherwise <code>false</code>
 */
function windowManagement_hasWindowTitleMapping(windowName)
{
  for(i=0; i<windowFormNames_windowTitleMapping.length; i+=2)
  {
    mappingWinName = windowFormNames_windowTitleMapping[i];
    mappingWinTitle = windowFormNames_windowTitleMapping[i+1];
    if ( mappingWinName == windowName )
    {
      return true;
    }
  }
  return false;
}

/**
 * Write the window title for the current window to the document
 * This will use window.name to derive the window title based on mappings in
 * WindowFormNames.js
 */
function windowManagement_writeMyWindowTitle()
{
 document.write('<title>' + windowManagement_getWindowTitleForName(window.name) + ' - CargoSmart</title>');
}

/**
 * Write the application title for the current window to the document
 * This will use window.name to derive the application title based on
 * mappings in WindowFormNames.js
 */
function windowManagement_writeMyApplicationTitle()
{
 document.write(windowManagement_getWindowTitleForName(window.name).toUpperCase());
}

/**
 * Get warning message for reuse confirmation window
 *
 * @param windowName   The window name we are trying to open
 * @param editFormName The name of the edit form in the window
 */
function windowManagement_getWarningMessage(windowName, editFormName)
{
  var message="";

  for(i=0; i<windowFormNames_windowFormMapping.length; i+=3)
  {
    mappingWinName = windowFormNames_windowFormMapping[i];
    mappingFormName = windowFormNames_windowFormMapping[i+1];
    mappingFormTitle = windowFormNames_windowFormMapping[i+2];
    if ( mappingWinName == windowName && mappingFormName == editFormName )
    {
      return windowManagement_getWindowTitleForName(windowName) + " - " + mappingFormTitle;
    }
  }
  // Return default text from mapping file
  return mappingFormTitle + " " + windowName + "/" + editFormName;
}
