/*
 * sccsid = '@(#) 1.33 wt/wtp/htdocs/scripts/timeTables_3.js, wtcode, jtimedev 11/17/06 15:52:07'
 *
 * timeTables.js
 *
 * (C) COPYRIGHT Journyx, Inc 1997 - 2006
 *  All Rights Reserved
 *  Licensed Materials - Property of Journyx, Inc.
 *
 */


/* ======================================================================= 
FILE: scripts/timeTables.js                                           
CREATED: 08-Aug-2004 01:12                                              
----------------------------------------------------------------------  
PURPOSE: Functions to manipulate the primary input tables including
           scrollable areas and other features
REQUIRES: browserDetect.js, cookies.js

XXX TODO: -moz-scrollbars-horizontal only works in Gecko but its'
being used in all non-MSIE.


======================================================================= */

var blnRightCellFixed = false;

var fixingRowHeights = false;

function jtguiOnLoad() {

  // fncCreateLoadWaitNotice('persist_form');

  var PrimaryContent = document.getElementById('idPrimaryContent');

  if (bad(PrimaryContent)) { return null; }

  PrimaryContent.style.visibility = "hidden";

  try {

	var MainTable  = document.getElementById('idMainTable');
	
	if (!bad(MainTable)) {
	  fncPositionMainTables();
	  fixRowHeights();
	}
  } 
  finally {
	PrimaryContent.style.visibility = "visible";
  }

}


function fncDestroyLoadWaitNotice() {

  var LoadingWaitNotice = document.getElementById('idLoadingWaitNotice');

  if (!bad(LoadingWaitNotice)) {
	var itsParent = LoadingWaitNotice.parentNode;
	itsParent.removeChild(LoadingWaitNotice);	
  }
}

function switchToDay()
{

  if (document.persist_form.periodtype)
   {
       if (document.persist_form.periodtype.value != 'day')
          {
             document.persist_form.periodtype.value = 'switch';
             document.persist_form.submit();
             return; 
          }
        
        return;
      }
 
}

function switchToPeriod()
{

  if (document.persist_form.periodtype)
   {
       if (document.persist_form.periodtype.value != 'period')
          {
              document.persist_form.periodtype.value = 'switch';
              document.persist_form.submit();
              return;
          }
         
        return;
      }

}

function fixRows(id) {

  var lhsrow = document.getElementById('lhsrow'+id);
  var rhsrow = document.getElementById('rhsrow'+id);
  var totalrow = document.getElementById('totalrow'+id);
  var leftrow = document.getElementById('leftrow'+id);

  if (!lhsrow || !rhsrow || !totalrow || !leftrow) {
	return false;
  }

  var lhsrowH = fncGetHeight(lhsrow);
  var rhsrowH = fncGetHeight(rhsrow);
  var totalrowH = fncGetHeight(totalrow);
  var leftrowH = fncGetHeight(leftrow);

  
  var m1 = Math.max(lhsrowH,rhsrowH);
  var m2 = Math.max(totalrowH,leftrowH);
  var biggestheight = Math.max(m1,m2);

  var biggestheightpx = biggestheight + 'px';

  lhsrow.style.height   = biggestheightpx;
  rhsrow.style.height   = biggestheightpx;
  totalrow.style.height = biggestheightpx;
  leftrow.style.height  = biggestheightpx;
	
  /*
  if (lhsrowH != biggestheight) {
	lhsrow.style.height   = biggestheightpx;
  }

  if (rhsrowH != biggestheight) {
	rhsrow.style.height   = biggestheightpx;
  }

  if (totalrowH != biggestheight) {
	totalrow.style.height = biggestheightpx;
  }

  if (leftrowH != biggestheight) {
	leftrow.style.height  = biggestheightpx;
  }
  */
}



function fixRowHeights()
{ 

    fixingRowHeights = true;
	try {
	  // in a try block because in allocation entry screens
	  // there is no header row
	  fixRows('head');	   
	} catch(e) {}  // don't do anything on error
	  
    for (loopx=0;loopx < numrowids;loopx++)	{
	  fixRows(loopx);
	}	
    for (loopx=0;loopx < numfooters;loopx++) {
	  fixRows('foot'+loopx);
	}

    fixoverallHeights();	
    fixingRowHeights = false;	 
}


function fixoverallHeights() {               
  totalheight = fncGetHeight('idMainTableRight')  + 20 + "px";
  document.getElementById('idMainTableLeftContainer').style.height  = totalheight;
  document.getElementById('idMainTableRightContainer').style.height = totalheight;
  document.getElementById('idTotalColsContainer').style.height      = totalheight;
  document.getElementById('idMainTableFarLeftContainer').style.height  = totalheight;
}

function fncPositionMainTables() {
  
  var MainTable               = document.getElementById('idMainTable');
  var MainTableLeftCell       = document.getElementById('idMainTableLeftCell');
  var MainTableLeftContainer  = document.getElementById('idMainTableLeftContainer');
  var MainTableRightContainer = document.getElementById('idMainTableRightContainer');

  // Exit out if we don't seem to have the MainTables stuff.
  if (MainTable === null || 
	  MainTableLeftContainer === null || 
	  MainTableLeftCell === null) { return false; }
  
  // First we fill fix the width of the outter two tables      
  if (!bad(USE_INNER_SCROLLBARS) && USE_INNER_SCROLLBARS) {
	MainTableLeftContainer.style.overflow = "auto";
	MainTableRightContainer.style.overflow = "auto"; 	
	MainTableLeftContainer.style.width = "1px";
	MainTableRightContainer.style.width = "1px";	
  } else {
	USE_INNER_SCROLLBARS = false;
  }

  MainTable.style.width = "100%";
  
  staticwidth  = fncGetWidth('idTotalCols') + fncGetWidth('idMainTableFarLeft');
  contentwidth = 2 + fncGetWidth('idPrimaryContent') - staticwidth;
      
  leftelementwidth  = fncGetWidth('idMainTableLeft'); 
  rightelementwidth = fncGetWidth('idMainTableRight'); 
	
  leftelementscroll = 0;
  rightelementscroll = 0;

  // the contents of both fit
  // we tighten up on the right hand side
  if (((leftelementwidth + rightelementwidth) < contentwidth) || (! USE_INNER_SCROLLBARS)) { 
	// Preston added the -15 magic number here -- to fix View Day having a browser horizontal scrollbar when it didn't need it.
	leftelementwidth = leftelementwidth + (contentwidth - leftelementwidth - rightelementwidth - 15);
	leftelementscroll = 0;
	rightelementscroll = 0;
  } 
  else {
	// ok, they do not fit.
	// someones gotta scroll
	// we will hake the right hand side scroll
	// but not make it go past our minimum of 100px
         
	if (rightelementwidth > 150) {
	  rightelementscroll = rightelementwidth - 150; 
	  rightelementwidth = 150;
	}

	// hopefully this fixed the left too, lets see
	if ((leftelementwidth + rightelementwidth) < contentwidth) {
	  rightelementwidth = contentwidth - leftelementwidth; 
	  leftelementscroll = 0;
	} 
	else {
	  // looks like double scrollbars are in order
	  leftelementscroll = (leftelementwidth + rightelementwidth) - contentwidth;
	  leftelementwidth  = leftelementwidth - leftelementscroll;
	} 	

  }
  
          
  lscreenpad = 0;	     
  rscreenpad = 0;
     
  if (leftelementscroll) {
	lscreenpad = 15;
  }
  else {
	if (rightelementscroll) {
	  rscreenpad = 15;
	}
  }
	    
  if (USE_INNER_SCROLLBARS) { 
	  MainTableLeftContainer.style.width = (leftelementwidth - lscreenpad) + 'px';	 
	  MainTableRightContainer.style.width = (rightelementwidth - rscreenpad) + 'px';

	  /* XXX TODO: -moz-scrollbars-horizontal only works on NS/Gecko browsers! */

	  if (leftelementscroll > 0) {    	  
		if (!(is.ie)) {		
		  MainTableLeftContainer.style.overflow = "-moz-scrollbars-horizontal";
		}
	  }
	  else {
		MainTableLeftContainer.style.overflow = "hidden";
	  }
	  
	  if (rightelementscroll > 0) { 	  
		if (!(is.ie)) {
		  MainTableRightContainer.style.overflow = "-moz-scrollbars-horizontal"; 
		}
	  }
	  else {	
		MainTableRightContainer.style.overflow = "hidden"; 
	  }	
  }
  
  return true;
}


function fncGetToggleColumnCookieName(strSection) {
  // we prepend the window location (patname only) to avoid conflicting with similarly named columns on other screens
  var cookie_name = window.location.pathname + strSection;

  return cookie_name;
}

function fncToggleColumn_getCurrentState(strSection, col_state) {

  if (bad(col_state)) {
	var col_state_name = 'toggle_column'+strSection;
	col_state = window[col_state_name];
  }
  
  if (bad(col_state)) { return null; }

  if (col_state == 'on') {
	return 'on';
  } 
  else {
	return 'off';
  }	

}

// DIN 12894 changed how this function works a bit.  See the defect
// notes for a full explanation.  In short, previously it was using
// innerHTML to remember the old contents, the resetting the innerHTML
// after expansion.  The problem with that is that it recreates the
// objects (breaking references in JS to the old objects) and also
// that it assumes the objects won't change in the interim (while
// collapsed) - it restored the original state of the objects even if
// they changed in the meantime.
//
// In the new version, we don't use innerHTML at all and there is no
// copying / duplication of objects.  Instead we rely on the server
// side code creating the containing DIV for us, as well as a SPAN to
// contain the "Expand the Column" link.  We fiddle with these
// exisiting elements display style when expanding/collapsing columns.
// This is also a bit faster to run.  Well we do use innerHTML on the
// SPAN for the "Expand Column" link, but we're not using innerHTML
// any more to copy the actual content of the cells.
//
function fncMainTableToggleColumn(strSection, usecookies) {
  
  var col_state_name = 'toggle_column'+strSection;

  var col_state = window[col_state_name];

  if (bad(col_state)) { return null; }

  var cookie_name = fncGetToggleColumnCookieName(strSection);

  var currenttoggle = fncToggleColumn_getCurrentState(strSection, col_state);
  if (bad(currenttoggle)) { return null; }

  column_elem_name = 'column'+strSection;
  columntocollapse = window[column_elem_name];

  thtocollapse = document.getElementById(strSection);
  if (currenttoggle == 'on') {

	// DIN 12894 - Warning: using childNodes assumes that there will
	// be no extraneous nodes screwing this up.  That means in the
	// server generated HTML we can't have any extraneous linefeeds or
	// whitespace because those become Text nodes, screwing up the
	// indexes of childNodes.

	thtocollapse.childNodes[0].style.display = 'none';
	thtocollapse.childNodes[1].innerHTML = '<a href="#" ' +
	  'onClick="fncMainTableToggleColumn(\'' +
	  strSection +
	  '\');return false;">' + 
	  '<img HEIGHT=7 WIDTH=7 src="../jtime/image/plus.gif" title="Show Column">' +
	  '</a>';
	

	thtocollapse.style.whiteSpace = 'nowrap';
  }
  else {
	// See DIN 12894 comments above.
	thtocollapse.style.whiteSpace = 'nowrap';
	thtocollapse.childNodes[0].style.display = 'block';
	thtocollapse.childNodes[1].innerHTML = '';  // remove the "Show Column" link

  }


  for (i=0; i < columntocollapse.length; i++) { 
	tdtocollapse = document.getElementById(columntocollapse[i]);
	if (currenttoggle == 'on'){
	  tdtocollapse.childNodes[0].style.display = 'none';

	  // See DIN 12894 comments above.
	  tdtocollapse.style.width = '10px';
	  tdtocollapse.style.whiteSpace = 'nowrap';
	}
	else { 
	  // See DIN 12894 comments above.
	  tdtocollapse.childNodes[0].style.display = 'block';
	  tdtocollapse.style.whiteSpace = 'nowrap';
	}
  }

  cookie_state = '0';
  if (currenttoggle == 'on') { 
	col_state = 'off';	
  }
  else {
	col_state = 'on';
	cookie_state = '1';
  }
  // plug the setting back into the 'global' variable
  window[col_state_name] = col_state;

  // Sets default value of this parameter to 1 if not otherwise supplied
  if (bad(usecookies)) {
	usecookies = 1;
  }

  if (usecookies) {
	setCookie(cookie_name,cookie_state,'never');
  }
  
  fncPositionMainTables();
  fixRowHeights();

  return true;
}






function fncMainTableToggleSection(strSection,usecookies) {

  // XXX TODO: eval sucks!!
  if (eval('toggle_'+strSection) == 'on') {
	currenttoggle = 'on';
  } else { 
	currenttoggle = 'off';
  }	
  rowstocollapse = eval('rows'+strSection);
    
  imagetochange  =  document.getElementById(strSection + 'image');
  
  // From the image, get the parent container row to change its color
  // Currently this is 4 elements up... IMG -> SPAN (collapse onclick) -> TD -> TR
  // This is sensitive to layout generated in wtdoc.py
  //
  var collapsible_row = imagetochange;
  collapsible_row = collapsible_row.parentNode; // Move up to IMG's parent <SPAN>
  var collapsible_span = collapsible_row;       // Save the SPAN to mess with its TITLE (tooltip)

  collapsible_row = collapsible_row.parentNode; // Move up to SPAN's parent <TD>
  collapsible_row = collapsible_row.parentNode; // Move up to TD's parent <TR>
  
  // If we've indeed found the containing Table Row (TR) then fiddle
  // with it's style to change the color.
  if (collapsible_row.tagName.toUpperCase() == "TR") {
	if (currenttoggle == 'on') {    
	  collapsible_row.className = 'togglerowCollapsed';
	  collapsible_span.title = 'Click to Show This Section';
	}
	else {
	  collapsible_row.className = 'togglerow';
	  collapsible_span.title = 'Click to Hide This Section';
	}
  }


  if (imagetochange) {   
	if (currenttoggle == 'on'){
      imagetochange.src   = "../jtime/image/plus.gif";
      // imagetochange.title = "Display This Section";	
	  
	} else {
	  imagetochange.src="../jtime/image/minus.gif";
	  // imagetochange.title = "Hide This Section";	
	}  
  }

  for (i=0;i < rowstocollapse.length;i++) { 
	rowtocollapse = document.getElementById(rowstocollapse[i]);
	if (currenttoggle == 'on') {
	  rowtocollapse.style.display = "none";
	} else { 
	  rowtocollapse.style.display = "";
	}
  }
  
  
  if (currenttoggle == 'on') {    
	if (usecookies == 1) { 
	  setCookie(strSection,'0','never','/'); 
	}	
	eval('toggle_'+strSection+" = 'off'");
  } else {
	eval('toggle_'+strSection+" = 'on'");
	if (usecookies == 1) { 
	  setCookie(strSection,'1','never','/'); 
	}
  }
}

// Warning: time depends on length of b
function isIn(a,b) { 
  for(xx=0;xx < b.length;xx++) {
    if (a == b[xx]) { 
	  return 1;
	}
  }
  return 0;
}





sortcolumn = 0;
sortdir = 'down';
function fncMainTableSortColumn(columnNumber,tblName,sortheader) 
{
 
  // get the sorter cell
  var scell = document.getElementById(sortheader);
  		
  if (scell.getAttribute("sortdir") == 'down')
  {
    sortdir = 'up';
    scell.setAttribute('sortdir','up');
    scell.innerHTML = '<div style="white-space: nowrap">'+scell.originalvalue + '<big>&nbsp;&nbsp;&uarr;</big></div>';   
  }
  else { 
    if (scell.getAttribute("sortdir") == 'up')
    {	
      sortdir = 'down';
      scell.setAttribute('sortdir','down');	
      
      scell.innerHTML = '<div style="white-space: nowrap">'+ scell.originalvalue + '<big>&nbsp;&nbsp;&darr;</big></div>'; 
    }  
    else
    {
      sortdir = 'down';
      scell.setAttribute('sortdir','down');	
      scell.originalvalue = scell.innerHTML;
      scell.innerHTML = '<div style="white-space: nowrap">'+ scell.originalvalue + '<big>&nbsp;&nbsp;&darr;</big></div>'; 
    }
  }
  // get the table body we want to sort 
  

	

  tblBodyObj = document.getElementById(tblName);  
  if (tblName == 'idMainTableLeftbody')
  {
     OtherTblBodyObjs = [document.getElementById('idMainTableFarLeftbody'),
                         document.getElementById('idMainTableRightbody'),
                         document.getElementById('idTotalColsbody')];
                    
  }
  else
  {
     OtherTblBodyObjs = 'notjtgui';  
  }



  
  // get the column index we want to sort on
  sortcolumn = columnNumber; 	
  
  // get a copy of the rows we want to sort on
  var allRows = [];
  var newRows = [];
  
  for (j=0;j<tblBodyObj.rows.length;j++) 
  {
    if (tblBodyObj.rows[j].className == 'togglerow')
    {
      if (OtherTblBodyObjs != 'notjtgui')
      {
        newRows.sort(blahSort2);
	newRows[newRows.length] = [tblBodyObj.rows[j],OtherTblBodyObjs[0].rows[j],OtherTblBodyObjs[1].rows[j],OtherTblBodyObjs[2].rows[j]];
	for (i=0;i<newRows.length;i++) 
        { 
          allRows[allRows.length] = newRows[i];
        }
        newRows = [];
      }
      else
      {
         newRows.sort(blahSort);
         newRows[newRows.length] = tblBodyObj.rows[j];
         for (i=0;i<newRows.length;i++) {allRows[allRows.length] = newRows[i];}
         newRows = [];
      }
    } 
    else
    {
      if (OtherTblBodyObjs != 'notjtgui')
      {
        newRows[newRows.length] = [tblBodyObj.rows[j],OtherTblBodyObjs[0].rows[j],OtherTblBodyObjs[1].rows[j],OtherTblBodyObjs[2].rows[j]];
      }
      else
      {
        newRows[newRows.length] = tblBodyObj.rows[j];
      }
    }
  }
  
  // once more for the last section
  if (OtherTblBodyObjs != 'notjtgui')
  {
    newRows.sort(blahSort2);
  }
  else
  {
    newRows.sort(blahSort);
  }

  for (i=0;i<newRows.length;i++) {allRows[allRows.length] = newRows[i];}
  
  
  // add all the new rows to the table
  
  if (OtherTblBodyObjs != 'notjtgui')
  {
    for (i=0;i<allRows.length;i++) {tblBodyObj.appendChild(allRows[i][0]);OtherTblBodyObjs[0].appendChild(allRows[i][1]);OtherTblBodyObjs[1].appendChild(allRows[i][2]);OtherTblBodyObjs[2].appendChild(allRows[i][3]);} 
  }
  else
  {
    for (i=0;i<allRows.length;i++) {tblBodyObj.appendChild(allRows[i]);}
  }

}



function blahSort(robj1,robj2)
{

  var x = getInnerText(robj1.cells[sortcolumn]).toLowerCase();
  var y = getInnerText(robj2.cells[sortcolumn]).toLowerCase();
  if (sortdir == 'down'){
  return ((x < y) ? -1 : ((x > y) ? 1 : 0));
  }
  else
  {
  return ((x > y) ? -1 : ((x < y) ? 1 : 0));
  }
}



function blahSort2(robj1,robj2)
{

  var x = getInnerText(robj1[0].cells[sortcolumn]).toLowerCase();
  var y = getInnerText(robj2[0].cells[sortcolumn]).toLowerCase();
  if (sortdir == 'down'){
  return ((x < y) ? -1 : ((x > y) ? 1 : 0));
  }
 else
  {
  return ((x > y) ? -1 : ((x < y) ? 1 : 0));
  }

}



function getInnerText(obj)
{

  if (typeof obj == "string") {
	return obj;
  }
  if (typeof obj == "undefined") {
	return obj;
  }
  if (obj.innerText) {
	return obj.innerText;
  }
  var str = "";
  
  var cs = obj.childNodes;
  var l  = cs.length;
  for (var i = 0; i < l; i++)
  {
    switch (cs[i].nodeType) {
	case 1:	  
	  str += getInnerText(cs[i]);
	  break;
         
	case 3:
	  str += cs[i].nodeValue;
	  break;
	}
  }
return str;
} 



