//--------------------------------------------------- 
// Global Javascript Code
//---------------------------------------------------

// Global for browser version branching.
var isIE = (navigator.appName == "Microsoft Internet Explorer");
var isDOM = (document.getElementById ? true : false); 
var isIE4 = ((document.all && !isDOM) ? true : false);
var isNS4 = (document.layers ? true : false);

var objUpperArrow;				    // Stores pleloaded upper arrow (triangle) image
var objLowerArrow;				    // Stores pleloaded lower arrow (triangle) image
var objSpacer;    				    // Stores pleloaded spacer image
var objBGIMG;				        	// Stores pleloaded background image for dynamicly genrated pop-up windows.
var aryImages = new Array();	// Stores other pleloaded images

var objPlsWaitWin;		  			// "Please Wait" window handler.

//Preload repetetive images
if(document.images)
{
	if (!isNS4)
	{
		objBGIMG = new Image(); 
		objBGIMG.src = '/images/blueBG.gif';
		objUpperArrow = new Image(); 
		objUpperArrow.src = '/images/blue_arrow_up.gif';
		objLowerArrow = new Image(); 
		objLowerArrow.src = '/images/blue_arrow_down.gif';
		objSpacer = new Image(); 
		objSpacer.src = '/images/spacer.gif';
	}
}  

// General purpose variable to be evaluated using eval() called from performAction()
var Action;  

// sort variables
var sortByCol = -1;
var sortByDir = '';
var arTable = new Array();
var ColumnCount;
var AlternateLines = true;
var useHighlight = true;

var treeMode = false;
var reveal = null;
var useSpecStyle = null;

// QueryString processing arrays
QueryString.keys = new Array();
QueryString.values = new Array();

// keyCode definitions
var KEY_HOME  = 36;
var KEY_END   = 35;
var KEY_PGUP  = 33;
var KEY_PGDN  = 34;
var KEY_UP    = 38;
var KEY_DOWN  = 40;
var KEY_LEFT  = 37;
var KEY_RIGHT = 39;
var KEY_ENTER = 13;

// default search text
var SEARCH_DEFAULT = '';

var resetField;
var resetField2;
var errorArray = new Array();

// tabular data variables
var tableData = new Array();
var arId = new Array();
var arActive = new Array();
var dataIdx = 0;
var lastPageNumber = 0;
var startPageNumber = 0;
var firstPageNumber = 1;
var pagesPerSet = 5;
var finishPageNumber = pagesPerSet;
var pageSize = 0;
var tableOffset = 0;
var linesPerRecord = 1;
var currTableName;
var currPageNumber = 0;
var showEmptyColumn = false;
var showLineNumbers = false;
var columnsPerLine = 0;
var tableColumnCount = 0;
var tableColumnShift = 0;
var isTableReverse = false;
var showStatus = true;
var additionalPageProcessing = null;
var onShowGenericCell = null;
var tableRowOffset = 1;
var paging = false;
var generateTicketNumber = null;

var dirty = false;

var SPECIAL_COLUMN = 15;

// tabular data constants
var MAX_RECORD_COUNT = 1800;
var DEFAULT_PAGE_SIZE = 15;
var EMPTY_CELL = '&nbsp;';

// variables to handle dynamic tabled for lists
var TableRowCounter = 0;
var ExtraRowCounter = 0;

var selectedRow = null;

// cookies
var PROJECT_LIST_PAGE_COOKIE = 'ProjectListPageCookie';
var NO_PAGING_COOKIE 				 = 'NoPagingCookie';

var severity = new Array();
severity[1] = 'Highest';
severity[2] = 'High';
severity[3] = 'Medium';
severity[4] = 'Low';
severity[5] = 'Lowest';

//Pop-up Processing variables
var tempParam = null;
var tempList = null;
var locationPathname = null;
var needToRefreshList = true;
var beforeClose = null;

//Banner positioning
var scrollObjName;
var origPosX;
var origPosY;

//Ticket list Groupping
var groupId = -1;

// Global Variables
//*****************************************************
// One object tracks the current modal dialog opened from this window.
var dialogWin = new Object();

//--------------------------------------------------- 
// Browser-independent util methods
//---------------------------------------------------
function getRefId(id) 
{
  if (isDOM) return document.getElementById(id);
  if (isIE4) return document.all[id];
  if (isNS4) return document.layers[id];
}

function getStyleId(id) 
{
  return (isNS4 ? getRefId(id) : getRefId(id).style);
} 

function setObjStyle(object, value) 
{
	if (object)
	{
		var obj = (isNS4 ? object : object.style);
	  obj = value;
	}  
} 

//--------------------------------------------------- 
// Writes in-line data value to the page stream
//---------------------------------------------------
function setTableValue(irow, icol)
{
  if (linesPerRecord > 1)
    setTableValueMultiLine(irow, icol, false);
  else
    setTableValueOneLine(irow, icol, false);
}

//--------------------------------------------------- 
// clear in-line data value to the page stream
//---------------------------------------------------
function clearTableValue(irow, icol)
{

  if (linesPerRecord > 1)
    setTableValueMultiLine(irow, icol, true);
  else
    setTableValueOneLine(irow, icol, true);
}

//--------------------------------------------------- 
// Writes single-line data into the table 
//---------------------------------------------------
function setTableValueOneLine(irow, icol, clearField)
{
	var oTable = getRefId(currTableName);
	if (oTable)
	{
	  var irow1 = irow - Math.floor(irow / pageSize) * pageSize + 1;
	  var icol1 = icol;
		
	  var itablerow = (isTableReverse ? icol1 : irow1) + tableOffset;
	  if (itablerow < oTable.rows.length)
	  {
	    var itablecol = (isTableReverse ? irow1 : icol1) + tableColumnShift;

			// Show optionally Line Numbers for Vertically positioned table
			if (showLineNumbers && isTableReverse && itablerow == 0 && irow < tableData.length)
			{
				var irow1 = irow + 1;
				var oCell = getRefId('lineHeader' + itablecol);
				if (oCell)
				{
				  var itablecol_1 = itablecol - 1;
				  if (clearField)
			      	setCellHTML(oCell, EMPTY_CELL, false);
				  else
			      	setCellHTML(oCell, (arId && arId[irow] ? arId[irow] : irow1), false);
				}		
			}	
				
			// Fill-in the rest of the table
    	if (irow < tableData.length && oTable.rows(itablerow))
    	{
      	var oCell = oTable.rows(itablerow).cells(itablecol);
      	if (clearField)
	      	setCellHTML(oCell, EMPTY_CELL, true);
      	else
      	{
		      if (onShowGenericCell)
		      	onShowGenericCell(oCell, irow, icol);
	      	setCellHTML(oCell, tableData[irow][icol], true);
      	}	
    	}										
	  }                      
	}  
}

//--------------------------------------------------- 
// Writes multi-line data into the table 
//---------------------------------------------------
function setTableValueMultiLine(irow, icol, clearField)
{
	var oTable = getRefId(currTableName);
	if (oTable)
	{
	  var itablerow = irow - Math.floor(irow / pageSize) * pageSize + tableOffset;
	  
	  itablerow = linesPerRecord * itablerow + 1;
	  if (itablerow < oTable.rows.length)
	  {
	    var floorCol = Math.floor(icol / columnsPerLine);
	    var itablecol = icol - (floorCol * columnsPerLine) + tableColumnShift;
	    for (var j = 0; j < floorCol; j++)
	      itablerow++;
	    if (showEmptyColumn || icol > 0)
	    {
	      var cell = oTable.rows(itablerow).cells(itablecol);
	      if (cell)
	        setCellHTML(cell, (oTable.rows(itablerow) && irow < tableData.length && !clearField ?
	        										 tableData[irow][icol] : EMPTY_CELL), true);
	    }                    
	  }                      
	}  
}

//--------------------------------------------------- 
// Writes in-line menu (Select/Edit/Delete)
//---------------------------------------------------
function setCellHTML(cell, text, toWrap)
{
//alert('cell.innerHTML='+cell.innerHTML+'\n\ntext='+text);	
  if (cell != null)
  {
  	var width = parseInt(cell.width - 2)	;
		if (toWrap)
    	cell.innerHTML = '<span style="width: ' + width + '; overflow: hidden;">' + text + '</span>';
		else
    	cell.innerHTML = text;
  }  
}

//--------------------------------------------------- 
// Function to plug tabular data into Table
//---------------------------------------------------
function refreshTable()
{
	var oPageLinks = getRefId('pageLinks');
	var oPageNumberTD = getRefId('pageNumberTD');

  var irowStart = (currPageNumber - 1) * pageSize;
  var irowEnd = irowStart + pageSize;

  if (tableColumnCount == 0 && tableData.length > 0)  
    if (tableData[0])  
      tableColumnCount = tableData[0].length;

  if (columnsPerLine == 0)
    columnsPerLine = (tableColumnCount == 0 ? 1 : tableColumnCount);
    
  //clean-up all cells first 
  if (paging) 
	  for (var irow = 0; irow < pageSize ; irow++)
	  {
	    for (var icol = 0; icol < tableColumnCount; icol++)
	      clearTableValue(irow, icol);
	  } 
  //fill-in cells that need to be filled-in, second
  for (var irow = irowStart; irow < irowEnd && tableData.length > 0 && irow <= MAX_RECORD_COUNT; irow++)
  {
    for (var icol = 0; icol < tableColumnCount; icol++)
     	setTableValue(irow, icol);
  }    
  if (oPageLinks)
  {
		startPageNumber = Math.floor((currPageNumber - 1) / pagesPerSet) * pagesPerSet;
		finishPageNumber = (startPageNumber + pagesPerSet > lastPageNumber ? lastPageNumber : startPageNumber + pagesPerSet);
		
 		var strHtml = '';
  	for (var i = startPageNumber; i < finishPageNumber; i++)
  	{
			var i1 = i + 1;
  		if (strHtml != '')
  			strHtml += '&nbsp;';
  		if (i1 == currPageNumber)
  			strHtml += '[' + currPageNumber + ']';
  		else	
  			strHtml += '<a href="#" onclick="showPage(' + i1 + ')" class="PageNumber">' + i1 + '</a>';
  	}
  	oPageLinks.innerHTML = strHtml;

    setupPageCounterLinks();
 	
  	if (oPageNumberTD)
  		if (tableData.length == 0 || lastPageNumber == 1)
  			oPageNumberTD.innerHTML = '&nbsp;';
  }
}

//--------------------------------------------------- 
// Function to set dirty flag
//---------------------------------------------------
function setDirty(obj)
{
  dirty = true;
}

//--------------------------------------------------- 
// Function to setup page counter links
//---------------------------------------------------
function setupPageCounterLinks()
{
	var oPrevSetLink = getRefId('prevSetLink');
	var oPrevPageLink = getRefId('prevPageLink');
	var oNextPageLink = getRefId('nextPageLink');
	var oNextSetLink = getRefId('nextSetLink');
	
	if (oPrevSetLink)
	{
		oPrevSetLink.disabled  = (startPageNumber == 0);
		oPrevSetLink.title = (oPrevSetLink.disabled ? 'no previous pages available' : 'show previous ' + pagesPerSet + ' pages');
	}	
	if (oPrevPageLink)
	{
		oPrevPageLink.disabled = (currPageNumber == 1);
		oPrevPageLink.title = (oPrevPageLink.disabled ? 'no previous page available' : 'show previous page');
	}
	if (oNextPageLink)
	{
		oNextPageLink.disabled = (currPageNumber + 1 > lastPageNumber);
		oNextPageLink.title = (oNextPageLink.disabled ? 'no next page available' : 'show next page');
	}
	if (oNextSetLink)
	{
		oNextSetLink.disabled  = (finishPageNumber == lastPageNumber);
		oNextSetLink.title = (oNextSetLink.disabled ? 'no next pages available' : 'show next ' + pagesPerSet + ' pages');
	}	
}

//--------------------------------------------------- 
// Function to set Current Page Number (incl. cookies)
//---------------------------------------------------
function setCurrPageNumber(pageNumber)
{
	currPageNumber = pageNumber;
	eraseCookie(PROJECT_LIST_PAGE_COOKIE);
	createCookie(PROJECT_LIST_PAGE_COOKIE, pageNumber, 1);
}

//--------------------------------------------------- 
// Function to show the Current page of the table
//---------------------------------------------------
function showPage(pageNo)
{
	if (pageNo > 0 && pageNo <= lastPageNumber)
	{
		setCurrPageNumber(pageNo);
		refreshTable();
		if (additionalPageProcessing)
		  additionalPageProcessing();
	}	
}

//--------------------------------------------------- 
// Function to show the previous set of the pages
//---------------------------------------------------
function prevSet()
{
	if (currPageNumber > pagesPerSet)
		setCurrPageNumber(currPageNumber - pagesPerSet);
	else	
		setCurrPageNumber(1);
	refreshTable();
	if (additionalPageProcessing)
	  additionalPageProcessing();
}

//--------------------------------------------------- 
// Function to show the previous page of the table
//---------------------------------------------------
function prevPage()
{
	if (currPageNumber > 1)
	{
		setCurrPageNumber(currPageNumber - 1);
		refreshTable();
		if (additionalPageProcessing)
		  additionalPageProcessing();
	}
}

//--------------------------------------------------- 
// Function to show the next page of the table
//---------------------------------------------------
function nextPage()
{
	if (currPageNumber < lastPageNumber)
	{
		setCurrPageNumber(currPageNumber + 1);
		refreshTable();
		if (additionalPageProcessing)
		  additionalPageProcessing();
	}
}

//--------------------------------------------------- 
// Function to show the next set of the pages
//---------------------------------------------------
function nextSet()
{
	if (currPageNumber + pagesPerSet <= lastPageNumber)
		setCurrPageNumber(currPageNumber + pagesPerSet);
	else
	  setCurrPageNumber(lastPageNumber);	
	refreshTable();
	if (additionalPageProcessing)
	  additionalPageProcessing();
}

//--------------------------------------------------- 
// Function to consume click() event
//---------------------------------------------------
function consumeClick()
{
//  if (window.event)
//  	window.event.returnValue = false;
}	

//--------------------------------------------------- 
// Function to show the alert message
// and consume click() event
//---------------------------------------------------
function safeAlert(msg)
{
  consumeClick();  
  alert(msg);
}	

//--------------------------------------------------- 
// Function to show the "Not implemented yet!" message
// and consume click() event
//---------------------------------------------------
function notImplemented()
{
	safeAlert('Not implemented yet!');
}	
//--------------------------------------------------- 
// Function to open new modal window
//---------------------------------------------------
function openNewModalWindow(url, param, width, height)
{
	var feature = ' status=yes,dependent=yes,scrollbars=no,titlebar=no,toolbar=no,menubar=no';

	if (param > "")
		url += param;	

    openDialog(url, '', width, height, '', feature);
    blockEvents(); 	
}

//--------------------------------------------------- 
// Function to open new modal window
//---------------------------------------------------
function openNewModalResizableWindow(url, param, width, height)
{
    var feature = ' status=no,dependent=yes,scrollbars=no,titlebar=no,toolbar=no,menubar=no';

    if (param > "")
      url += param;	

    openGenericDialog(url, '', width, height, '', feature, true);
    blockEvents(); 	
}

//--------------------------------------------------- 
// Function to open new non-modal window
//---------------------------------------------------
function openNewNonModalResizableWindow(url, param, width, height)
{
    var feature = ' status=no,dependent=yes,scrollbars=no,titlebar=no,toolbar=no,menubar=no';

    if (param > '')
      url += param;	
    openNewResizableWindow(url, '', width, height, '', feature);
}

//--------------------------------------------------- 
// Function to open new modal HTML window
//---------------------------------------------------
function showTicketInModal(width, height, windowTitle, htmlText)
{
  //clear it to create new window
  if (dialogWin.win)
    dialogWin.win.close();
  
  //open up new window
  var messagePopup;
  var winName = 'ticketPopup';
  
  openDialog('', winName, width, height, '', 'status=yes,dependent=no,scrollbars=no,titlebar=no,toolbar=no,menubar=no');

  //generate the window on the fly 
  if (dialogWin && dialogWin.win)
  {
  	dialogWin.win.focus();
    dialogWin.win.opener = self;
	  dialogWin.win.document.write('<html>');
	  dialogWin.win.document.write('<head>\n');
	  dialogWin.win.document.write('  <title>' + windowTitle + '</title>\n');
	  dialogWin.win.document.write('  <link rel="stylesheet" href="/app/mc/style/main.css">\n');
	  dialogWin.win.document.write('  <script language="JavaScript1.2" src="/app/common/util.js"><\/script>\n');
	  dialogWin.win.document.write('  <script language="JavaScript1.2" src="/app/common/calendar.js"><\/script>\n');
	  dialogWin.win.document.write('</head>\n');
	  dialogWin.win.document.write('<body bgcolor="#FFFFFF" topmargin="0" leftmargin="0" rightmargin="0" bottommargin="0" onunload="unblockEvents()">\n');
//    dialogWin.win.document.write('<body bgcolor="#FFFFFF" topmargin="0" leftmargin="0" rightmargin="0" bottommargin="0">\n');
	  dialogWin.win.document.write(htmlText);
	  dialogWin.win.document.write('</body>\n');
	  dialogWin.win.document.write('</html>\n');
//	  alert(htmlText);
  }
/*
  if (window.event)
    window.event.returnValue = false;
*/
  blockEvents();
  return (dialogWin.win);
}
//--------------------------------------------------- 
// Function to go to a page outside of the application
//---------------------------------------------------
function gotoExternalUrl(urlPage)
{
  consumeClick();
	location.href = urlPage;
}

//--------------------------------------------------- 
// Function to get current index from selected row
//---------------------------------------------------
function getCurrentIndexFromRow()
{
	return getIndexFromRow(selectedRow);	
}
//--------------------------------------------------- 
// Function to get a index from selected row
//---------------------------------------------------
function getIndexFromRow(row)
{
  var idx = -1; 
  if (row)
  	idx = getPagedIndex(row.rowIndex);
  return idx;	
}

//--------------------------------------------------- 
// Function to get an array index from the row index
//---------------------------------------------------
function getPagedIndex(index)
{
  var idx = index - tableOffset; 
  idx += (currPageNumber - 1) * pageSize;
  return idx;	
}

//--------------------------------------------------- 
// Function to open new modal window
//---------------------------------------------------
function openNewModalWindowMS(url, param, width, height)
{
	var top = (screen.height - height) / 2;
	var left = (screen.width - width) / 2;
	var feature = 'dialogWidth: ' + width + 'px;';
	feature += 'dialogHeight: ' + height + 'px;';
	feature += 'status: off; scroll: off; center: yes; resizable: off; help: off;';

	if (param > '')
		url += param;	

	window.showModalDialog(url, '', feature);
}

//--------------------------------------------------- 
// Function to highlight a row in the table
//---------------------------------------------------
function highlightRow(row)
{
	highlightRowNoFocus(row);
 	if (selectedRow)
 	  if (selectedRow.focus)
      selectedRow.focus();    
}

//--------------------------------------------------- 
// Function to highlight a row in the table without focus
//---------------------------------------------------
function highlightRowNoFocus(row)
{
  if (row)
  {
  	if (selectedRow)
  	{
      selectedRow.className = savedClassName;
      if (treeMode)	
      	assignClassToChildren(selectedRow, selectedRow.className);
  	}  
    savedClassName = row.className;
    row.className = 'tableRowSelected';
	  if (treeMode)	
	  	assignClassToChildren(row, row.className);
    if (viewDetail)
      if (reveal)
	  		reveal(row);

    selectedRow = row;
//alert(selectedRow.className);    
  }
}
//--------------------------------------------------- 
// Function to highlight a row in the table
//  and consume event that cause this action
//---------------------------------------------------
function highlightRowConsumeEvent(row)
{
	if (row.rowIndex >= tableOffset)
		highlightRow(row);
  consumeClick();
}

//--------------------------------------------------- 
// Function to toggle a checkbox 
//---------------------------------------------------
function toggleRow(row, name)
{
 	if (row)
 	{
 		var idx = row.rowIndex;
 		
 		if (row.parentNode)
 		{
 			if (row.parentNode.rows.length == 1)
 				eval('document.forms[0]. ' + name + '.checked = !document.forms[0]. ' + name + '.checked;');
 			else if (row.parentNode.rows.length > 1)
 				eval('document.forms[0]. ' + name + '[' + idx + '].checked = !document.forms[0]. ' + name + '[' + idx + '].checked;');
 		}			
 	}	
}

//--------------------------------------------------- 
// Function to highlight the 1st row in the table
//---------------------------------------------------
function highlight1stRow(tableName)
{
  var oTable = getRefId(tableName);
  if (oTable)
  {
    if (oTable.rows.length > 0)
      highlightRow(oTable.rows[1]);
    if (oTable.focus)  
  	  oTable.focus();    
  }  
}
//--------------------------------------------------- 
// Function to synchronize scrolling position of the
// Header table (tableName + 'Header') with the table
//---------------------------------------------------
function scrollDiv(DivName)
{
	var oDiv = getRefId(DivName);
	if (oDiv && event)
		oDiv.scrollLeft = event.srcElement.scrollLeft;
}

//--------------------------------------------------- 
// Function to move highlight in the Grid (up and down)
//---------------------------------------------------
function moveGridHighlight(tableName)
{
  moveGridHighlightGen(tableName, true);
}
function moveGridHighlightGen(tableName, usePositioning)
{
//alert('in moveGridHighlightGen()');
  if (selectedRow)
  {
		var oTable = getRefId(tableName);
		if (oTable && event)
		{  
		  switch (event.keyCode)
		  {
		    case KEY_UP:
		    {
	    	  if (selectedRow.rowIndex > tableRowOffset)
	          	highlightRowConsumeEvent(oTable.rows(selectedRow.rowIndex - 1));
			  	break;	
		    }	
		    case KEY_DOWN:
		    {
	    	  if (selectedRow.rowIndex < oTable.rows.length - 1)
	          	highlightRowConsumeEvent(oTable.rows(selectedRow.rowIndex + 1));
			  	break;	
		    }	
		    case KEY_PGUP:
		    {
	    	  if (selectedRow.rowIndex - gridPageSize >= tableRowOffset)
	          ighlightRowConsumeEvent(oTable.rows(selectedRow.rowIndex - gridPageSize));
	        else	
		        highlightRowConsumeEvent(oTable.rows(tableRowOffset));
			  	break;	
		    }	
		    case KEY_PGDN:
		    {
	    	  if (selectedRow.rowIndex + gridPageSize < oTable.rows.length - 1)
	         	highlightRowConsumeEvent(oTable.rows(selectedRow.rowIndex + gridPageSize));
	    	  else
	         	highlightRowConsumeEvent(oTable.rows(oTable.rows.length - 1));
			  	break;	
		    }	
		    case KEY_HOME:
		    {
	    	  if (event.ctrlKey)
		        highlightRowConsumeEvent(oTable.rows(tableRowOffset));
			  	break;	
		    }	
		    case KEY_END:
		    {
	    	  if (event.ctrlKey)
		        highlightRowConsumeEvent(oTable.rows(oTable.rows.length - 1));
			  	break;	
		    }	
		  }
	    if (usePositioning)
	      selectedRow.scrollIntoView(false);
		}
  }
}

//--------------------------------------------------- 
// Function to alternate style for rows in the table
//---------------------------------------------------
function alternateRowStyles(tableName)
{
  var oTable = getRefId(tableName);
  if (oTable)
  {  
    var alt = 0;
    for (var j = 0; j < oTable.rows.length; j++)
    {
      if (alt == 0)
        oTable.rows[j].className = 'tableRow';
      else  
        oTable.rows[j].className = 'tableRowAlt';
      if (useSpecStyle)
      	useSpecStyle(oTable.rows[j], j);  
      alt = 1 - alt;  
    }  
  }  
}

//--------------------------------------------------- 
// Function to clear-up the the search box.
//---------------------------------------------------
function initFindLine(obj)
{
	if (obj)
		if (obj.value)
			if (obj.value == SEARCH_DEFAULT)
				obj.value = '';
}


//--------------------------------------------------- 
// Function to initialize Project List
//---------------------------------------------------
function initProjectList(tableName)
{
	var ck = readCookie(PROJECT_LIST_PAGE_COOKIE);
	if (ck)
	  firstPageNumber = parseInt(ck);
	  
  setCurrPageNumber(firstPageNumber > lastPageNumber ? 1 : firstPageNumber);
  currTableName = tableName;
  ColumnCount = 14;
  onShowGenericCell = formatProjectListCell;
  if (paging)	
  	refreshTable();
  else
  {
	  oLinks = getRefId('pageNumberTD');
	  if (oLinks)
	    oLinks.innerHTML = '&nbsp;';
  }	
  initList(tableName, pageSize, false, null, 0);
}

//--------------------------------------------------- 
// Function to initialize Ticket List
//---------------------------------------------------
function initTicketList(tableName)
{
	paging = false;
	pageSize = tableData.length + 1;
  setCurrPageNumber(firstPageNumber > lastPageNumber ? 1 : firstPageNumber);
  currTableName = tableName;
  currPageNumber = 1;
  ColumnCount = 10;
  SPECIAL_COLUMN = 16;
  onShowGenericCell = formatTicketListCell;
//  reveal = refreshTicketView;
  if (paging)	
  	refreshTable();
  else
  {
	  oLinks = getRefId('pageNumberTD');
	  if (oLinks)
	    oLinks.innerHTML = '&nbsp;';
  }	
  initList(tableName, pageSize, true, null, 0);
  if (getCurrentIndexFromRow() <= 0)
   highlight1stRow(tableName);
  if (selectedRow)
  {
  	var tab = getRefId(tableName);
    if (tab && tab.click)
      tab.click();
    selectedRow.scrollIntoView(true);
  }  
    
}

//----------------------------------------------------------------------- 
// Function to refresh Ticket Detail while moving through Ticket List
//-----------------------------------------------------------------------
function refreshTicketView(row)
{
	refreshTicketViewWithForm(row, 1);
}

function refreshTicketViewWithForm(row, formIdx)
{
	if (dirty)
	{
		if (saveIfDirty(formIdx))
		  return;
	}	

	dirty = false;
	var ix = getIndexFromRow(row) - tableRowOffset;
  if (ix >= tableData.length)
    ix = tableData.length - 1;
  if (ix >= 0)
  {
		with (document.forms[formIdx])
		{
		  ticketId.value = tableData[ix][0];
		  currentStatus.value = tableData[ix][9];
		  ticketName.value = tableData[ix][19].replace(/&#39;/g, '\'').replace(/&quot;/g, '\'');
		  ticketType.value = tableData[ix][11];
		  ticketCategory.value = tableData[ix][12];
		  severity.value = tableData[ix][13];
		  urgency.value = tableData[ix][6];
		  targetDate.value = tableData[ix][8];
		  owner.value = tableData[ix][15];
		  creator.value = tableData[ix][17];
		  
		  deployedDate.value = tableData[ix][20];
		  version.value = tableData[ix][21];
		  estimateDate.value = tableData[ix][22];
		  estimate.value = tableData[ix][23];
		  priority.value = tableData[ix][24];
		  
		  comments.value = '';
		  if (tableData[ix][14])
			  for (var j = 0; j < tableData[ix][14].length; j++)
			    comments.value += tableData[ix][14][j].replace(/`~/g, '\r\n').replace(/&#39;/g, '\'').replace(/&quot;/g, '\'');		
		  forwardTicketBtn.disabled = tableData[ix][16];
		  assignTicketBtn.disabled = forwardTicketBtn.disabled;
  
  	  for (var j = attachments.options.length - 1; j >= 0; j--)
  	    if (attachments.options.remove)
	      	attachments.options.remove(j);
	      else	
	      	attachments.options[j] = null;
		  if (tableData[ix][18] && tableData[ix][18].length > 0)
		  {
			  for (var j = 0; j < tableData[ix][18].length; j++)
			  {
	        var opt = document.createElement("OPTION");      
	        attachments.options.add(opt);
	        opt.value = tableData[ix][18][j];
	        opt.text = tableData[ix][18][j];
			  }
			  viewBtn.disabled = false;
		  }    
		  else
		  {
        var opt = document.createElement("OPTION");      
	      attachments.options.add(opt);
	      opt.value = '';
	      opt.text = '< No Attachments >';
			  viewBtn.disabled = true;
		  }
		}  
  }	
}

//--------------------------------------------------- 
// Function to post form # idx  
//---------------------------------------------------
function refreshList()
{
  if (opener)
  {
    var url = opener.getVarValue('locationPathname'); 
    
    if (!url)
      url = opener.location.pathname;
    if (QueryString('mode') == 'new')
    {
  	  url += getUrlSymbol(url);
      url += 'rid=99999';
    }    
    else if (opener.getVarValue('selectedRow'))
    {
  	  url += getUrlSymbol(url);
      url += 'page=' + opener.getVarValue('currPageNumber');
      var idx = opener.getVarValue('selectedRow.rowIndex');
      if (idx)
        url += '&rid=' + idx;
    } 
    
    if (opener.document.forms[0])
      opener.document.forms[0].action = '';
//alert(url);
    opener.location.href = url; 
  }
}

//--------------------------------------------------- 
// Function to return '?' (or '&' if  '?' is already 
//  used in url) 
//---------------------------------------------------
function getUrlSymbol(url)
{
  return (url.indexOf('?') > -1 ? '&' : '?');
}

//--------------------------------------------------- 
// Function to initialize Project List
//---------------------------------------------------
function saveIfDirty(formIdx)
{
  if (confirm('Save changed ticket?'))
  {
    saveTicket(formIdx);
    return true;
  }  
  else
    return false;
}

//--------------------------------------------------- 
// Function to initialize Project List
//---------------------------------------------------
function saveTicket(formIdx)
{
  if (dirty)
  {
    var ix = getCurrentIndexFromRow() - tableRowOffset;
    document.forms[formIdx].currentRow.value = ix;
    document.forms[formIdx].submit();
    dirty = false;
  } 	
}

//--------------------------------------------------- 
// Function to add new Ticket
//---------------------------------------------------
function addTicket(formIdx)
{
	addTicketEx(formIdx, null);
}

//--------------------------------------------------- 
// Function to add new Ticket (Expanded)
//---------------------------------------------------
function addTicketEx(formIdx, projectID)
{
	openNewResizableWindow('http://defects.arteis.net', 'OnTime', '1000', '700', null, ' status=no,dependent=yes,scrollbars=yes,titlebar=no,toolbar=yes,menubar=no' );
}

//--------------------------------------------------- 
// (OLD Ticket System in the MC) Function to add new Ticket (Expanded)
//---------------------------------------------------
function addTicketEx_OLD(formIdx, projectID)
{
	if (dirty)
	{
		if (saveIfDirty(formIdx))
		  return;
	}	
	var url = '/mc-app/newTicket.do' + (projectID ? '?tname=' + escape('Project #' + projectID) : '');
	if (formIdx == -1)
    locationPathname = location.pathname + '?serviceid=3';
	else if (formIdx == -2)
    locationPathname = location.pathname + '?PROJECTID=' + projectID;
	else if (document.forms[formIdx] && document.forms[formIdx].showGroupId)
    locationPathname = '/mc-app/showAllTickets.do?gid=' + document.forms[formIdx].showGroupId.value;
	openNewModalWindow(url, "", 760, 540);
}

//--------------------------------------------------- 
// Function to forward existing Ticket
//---------------------------------------------------
function forwardTicket(formIdx)
{
	if (dirty)
	{
		if (saveIfDirty(formIdx))
		  return;
	}	
  postAndRefreshTicket(formIdx, 'forwardTicket.do');
}

//--------------------------------------------------- 
// Function to add comments to existing Ticket
//---------------------------------------------------
function addCommentsToTicket(formIdx)
{
  postAndRefreshTicket(formIdx, 'addComment.do');
}

//--------------------------------------------------- 
// Function to forward existing Ticket
//---------------------------------------------------
function postAndRefreshTicket(formIdx, action)
{
	var url = '/mc-app/' + action + '?id=' + document.forms[formIdx].ticketId.value;
	if (document.forms[formIdx] && document.forms[formIdx].showGroupId)
    locationPathname = '/mc-app/showAllTickets.do?gid=' + document.forms[formIdx].showGroupId.value;
	openNewModalWindow(url, "", 740, 460);
}

//--------------------------------------------------- 
// Function to add uploaded attachment name to the 
// list of attachamnets
//---------------------------------------------------
function beforeThisTicketClose()
{
    if (tempList)
    {
      if (tempList.length > 0 && 
          document.forms[0].attachments.options.length == 1 &&
          document.forms[0].attachments.options[0].value == '')
      {
        if (document.forms[0].attachments.options.remove)
          document.forms[0].attachments.options.remove(0);
        else
          document.forms[0].attachments.options[0] = null;
        document.forms[0].viewBtn.disabled = '';
      }  
      for (var i = 0; i < tempList.length; i++)
      {
        var opt = document.createElement("OPTION");      
        document.forms[0].attachments.options.add(opt);
        opt.value = tempList[i];
        opt.text = tempList[i];
        if (document.forms[0].fileList.value != '')
          document.forms[0].fileList.value += '|';
        document.forms[0].fileList.value += tempList[i];
      }
      if (tempList.length > 0)
        dirty = true;   
    }  
}
  
//--------------------------------------------------- 
// Function to add new Ticket Attachment
//---------------------------------------------------
function addTicketAttachment(formIdx, refreshPage, beforeCloseProcessing, ticketid)
{
	var url = '/mc-app/ticketAttachments.do' + (ticketid == null ? '' : '?tid=' + ticketid);
	needToRefreshList = refreshPage;
	if (beforeCloseProcessing)
	  beforeClose = beforeCloseProcessing;
	openNewModalWindow(url, "", 400, 440);
}

//--------------------------------------------------- 
// Function to view ticket attachment
//---------------------------------------------------
function viewAttachment(param)
{
  var idx = document.forms[0].attachments.options.selectedIndex;
  if (idx >= 0 && document.forms[0].attachments.options[idx].value > '')
  {
    var url = '/uploads/tickets/' + param + '/' + document.forms[0].attachments.options[idx].value;
    openNewModalResizableWindow(url, "", 800, 600);
  }
}
//--------------------------------------------------- 
// Function to initialize Project List
//---------------------------------------------------
function togglePaging(oCheckbox)
{
	var showAllParam = '&showAll=true';
	var checked = oCheckbox && oCheckbox.checked;
	var param = (checked ? showAllParam : '');
	var url = location.href.replace('#', '').replace(showAllParam, '') + param;
	var value = (checked ? 'true' : 'false');

	eraseCookie(NO_PAGING_COOKIE);
	createCookie(NO_PAGING_COOKIE, value, 1);

	location.href = url;
}

//--------------------------------------------------- 
// Function to initialize Paging Mode
//---------------------------------------------------
function initPaging()
{
	var result = (QueryString('showAll') == null);
	if (result)
	{
	  var ck = readCookie(NO_PAGING_COOKIE);
	  if (ck)  
	    result = (ck != 'true');
	}
	return result;  
}

//--------------------------------------------------- 
// Function to format Project List Cell
//---------------------------------------------------
function formatProjectListCell(oCell, irow, icol)
{
	var oStyle = (oCell.style ? oCell.style : oCell);
  if (oStyle && tableData[irow][SPECIAL_COLUMN]);
  	oStyle.backgroundColor = tableData[irow][SPECIAL_COLUMN]; 
}

//--------------------------------------------------- 
// Function to format Project List Cell
//---------------------------------------------------
function formatTicketListCell(oCell, irow, icol)
{
//	var oStyle = (oCell.style ? oCell.style : oCell);
  oCell.className =  (tableData[irow][SPECIAL_COLUMN] ? "completed" : "normal");
}

//--------------------------------------------------- 
// Generic Function to initialize a list 
//---------------------------------------------------
function initList(tableName, pageSize, viewDet, revealFunc, colCount)
{
  gridPageSize = pageSize;
  viewDetail = viewDet;

  var row = initSelectedRow(tableName);
  if (revealFunc)
    reveal = revealFunc;

  if (AlternateLines)
    alternateRowStyles(tableName);
	if (useHighlight)
  	highlightRow(row);

  if (selectedRow)
  {
//    getRefId(tableName).click();
    selectedRow.scrollIntoView(true);
  }  
  if (colCount > 0)
    ColumnCount = colCount;
//  prepareSort(tableName);
}

//--------------------------------------------------- 
// Function to initialize selected row based on a 
// parameter (rid) sent over the URL 
//---------------------------------------------------
function initSelectedRow(tableName)
{
  var t = getRefId(tableName);
  if (t)
  {
		var idx = (QueryString('rid') ? parseInt(QueryString('rid')) : tableOffset);
		idx = (idx < t.rows.length ? idx : t.rows.length - 1);
		idx = (idx < 0 ? 0 : idx);
		return t.rows[idx];
  }
  else
		return null;
}

//--------------------------------------------------- 
// Function to consume Enter key pressing event
//---------------------------------------------------
function consumeEnterKey()
{
	if (event && event.keyCode == KEY_ENTER)
 		event.returnValue = false;
}

//--------------------------------------------------- 
// Function to assign className to the children
// nodes of the node obj.
//---------------------------------------------------
function assignClassToChildren(obj, className)
{
	if (obj)
		if (obj.childNodes)
			for (var i = 0; i < obj.childNodes.length; i++)
			{
				var child = obj.childNodes[i];
				if (child.nodeName == 'TR')
					child.className = className;
				assignClassToChildren(child, className);
			}	
}

//--------------------------------------------------- 
// Function to show context-sensitive help 
//---------------------------------------------------
function printPage()
{
  window.print();  
}

//--------------------------------------------------- 
// Function to show (hide outside of the visible area) 
// the printer-ready page 
//---------------------------------------------------
function printPrinterReadyPage(page, winName)
{
  if (page)
  {
  	var param = ' status=no,dependent=yes,scrollbars=yes,titlebar=no,toolbar=no,menubar=no';
  	printWin = openNewWindowGeneral(page, winName, 750, 500, 0, 100, null, param);
 		printWin_saved = window.onfocus;
		window.onfocus = closePrintWindow;
  }
}

//--------------------------------------------------- 
// Function to make sure the print window is closed.
//---------------------------------------------------
function closePrintWindow()
{
	if (printWin)
		printWin.win.close();
//alert('onFocus');	
 	window.onfocus = printWin_saved;
}

/*****************************************************
	Procedure:		QueryString
	Author:			Cat Milea
	Created:		9/18/02
	Description:	This function gets querystring variable 
	              	from querystring array
*****************************************************/
function QueryString(key)
{
  var value = null;
  QueryString_Parse();
  if (QueryString.keys)
    for (var i = 0; i < QueryString.keys.length; i++)
    {
	    if (QueryString.keys[i] == key)
	    {
		    value = QueryString.values[i];
		    break;
	    }
    }
  return value;
}

/*****************************************************
	Procedure:		QueryString_Parse
	Author:			Cat Milea
	Created:		9/18/02
	Description:	This function parses querystring to get 
	              	name/value pairs.
*****************************************************/
function QueryString_Parse()
{
  var query = window.location.search.substring(1);
  var pairs = query.split("&");
  
  for (var i=0; i < pairs.length; i++)
  {
	  var pos = pairs[i].indexOf('=');
	  if (pos >= 0)
	  {
		  var argname = pairs[i].substring(0,pos);
		  var value = pairs[i].substring(pos+1);
		  QueryString.keys[QueryString.keys.length] = argname;
		  QueryString.values[QueryString.values.length] = value;		
	  }
  }
}
/*****************************************************
	Procedure:		strQueryString
	Author:			Craig Scribner
	Created:		4/2/2007
	Description:	This function gets querystring variable 
	              	from querystring array (url passed in as string)
*****************************************************/
function strQueryString(key, urlString)
{
  var value = null;
  strQueryString.keys = new Array();
  strQueryString.values = new Array();
 
  strQueryString_Parse(urlString);
  if (strQueryString.keys)
    for (var i = 0; i < strQueryString.keys.length; i++)
    {
	    if (strQueryString.keys[i] == key)
	    {
		    value = strQueryString.values[i];
		    break;
	    }
    }
  return value;
}

/*****************************************************
	Procedure:		strQueryString_Parse
	Author:			Craig Scribner
	Created:		4/2/2007
	Description:	This function parses a string's "querystring" section 
	              	to get name/value pairs.
*****************************************************/
function strQueryString_Parse(urlString)
{
  var query = urlString.substring(urlString.indexOf('?')+1);
  var pairs = query.split("&");
  
  for (var i=0; i < pairs.length; i++)
  {
	  var pos = pairs[i].indexOf('=');
	  if (pos >= 0)
	  {
		  var argname = pairs[i].substring(0,pos);
		  var value = pairs[i].substring(pos+1);
		  strQueryString.keys[strQueryString.keys.length] = argname;
		  strQueryString.values[strQueryString.values.length] = value;		
	  }
  }
}

//--------------------------------------------------- 
// Function to open new non-modal window centered
//---------------------------------------------------
function openNewWindow(url, winName, width, height, returnFunc, args)
{
  return openNewWindowCentered(url, winName, width, height, returnFunc, args, false);
}

//---------------------------------------------------------- 
// Function to open new non-modal resizable window centered
//----------------------------------------------------------
function openNewResizableWindow(url, winName, width, height, returnFunc, args)
{
  return openNewWindowCentered(url, winName, width, height, returnFunc, args, true);
}

//---------------------------------------------------------- 
// Function to open new non-modal window centered
//----------------------------------------------------------
function openNewWindowCentered(url, winName, width, height, returnFunc, args, isResizable)
{
	var top, left;
  // Assemble window attributes and try to center the dialog.
  if (isNS4) 
  {
		// Center on the main window.
		top = window.screenY + ((window.outerHeight - height) / 2);
		left = window.screenX + ((window.outerWidth - width) / 2);
  } 
  else 
  {
		// The best we can do is center in screen.
		top = (screen.height - height) / 2;
		left = (screen.width - width) / 2;
  }
  return openNewWindowBase(url, winName, width, height, top, left, returnFunc, args, isResizable);
}

//-------------------------------------------------------------- 
// Function to open new non-modal non-resizable Generic window
//--------------------------------------------------------------
function openNewWindowGeneral(url, winName, width, height, top, left, returnFunc, args)
{
	return openNewWindowBase(url, winName, width, height, top, left, returnFunc, args, false);
}

//--------------------------------------------------- 
// Function to open new non-modal General window
//---------------------------------------------------
function openNewWindowBase(url, winName, width, height, top, left, returnFunc, args, isResizable)
{
	return openNewWindowBase0(url, winName, width, height, top, left, returnFunc, args, true, isResizable);
}

//------------------------------------------------------------------- 
// Function to open new non-modal General window with flexible name
//------------------------------------------------------------------
function openNewWindowBase0(url, winName, width, height, top, left, returnFunc, args, isUniqueName, isResizable)
{
  var newWin = new Object();
  var resizeText = (isResizable ? 'yes' : 'no');
  // Initialize properties of the new window object.
  newWin.returnFunc = returnFunc;
  newWin.returnedValue = "";
  newWin.args = args;
  newWin.url = url;
  newWin.width = width;
  newWin.height = height;
  newWin.top = top;
  newWin.left = left;
  
  // Keep name unique so Navigator doesn't overwrite an existing dialog.
  newWin.name = winName + (isUniqueName ? (new Date()).getSeconds().toString() : '');

  attr = args;
  
  // Assemble window attributes and try to center the dialog.
  if (isNS4) 
  {
		attr += ',screenX=' + newWin.left + ',screenY=' + 
			newWin.top + ',resizable=' + resizeText + ',width=' + newWin.width + ',height=' + newWin.height;
  } 
  else 
  {
		// The best we can do is center in screen.
		attr += ',left=' + newWin.left + ',top=' + 
		  newWin.top + ',resizable=' + resizeText + ',width=' + newWin.width + ',height=' + newWin.height;
  }
  newWin.name = newWin.name.replace(' ', '');
  newWin.win = window.open(newWin.url, newWin.name, attr);
  
  if (newWin.win)
  {
    newWin.win.focus();
    newWin.win.opener = self;
  }  
  else
    alert('Please disable your popup blocker!');
  return newWin;
}

//--------------------------------------------------- 
// Function to open new modal dialog window
//---------------------------------------------------
function openDialog(url, winName, width, height, returnFunc, args) 
{
  openGenericDialog(url, winName, width, height, returnFunc, args, false); 
}

/*****************************************************
Procedure:     Modal dialog code for action window popups 
Author:        Dan Kormylo
Created:       1/15/02
Description:   This code must be included for any page that uses the pop up
               action window. 
******************************************************/
// Generate a modal dialog.
// Parameters:
//    url -- URL of the page/frameset to be loaded into dialog
//    width -- pixel width of the dialog window
//    height -- pixel height of the dialog window
//    returnFunc -- reference to the function (on this page)
//                  that is to act on the data returned from the dialog
//    args -- [optional] any data you need to pass to the dialog
//    isResizable -- whether or not window is resizable
//
function openGenericDialog(url, winName, width, height, returnFunc, args, isResizable) 
{
	var attr;
	//change cursor hourglass
	if (!isNS4 && document.body) 
		document.body.style.cursor = 'wait';
	
	if (!dialogWin.win || (dialogWin.win && dialogWin.win.closed)) 
	{
		// Initialize properties of the modal dialog object.
		dialogWin.returnFunc = returnFunc;
		dialogWin.returnedValue = "";
		dialogWin.args = args;
		dialogWin.url = url;
		dialogWin.width = width;
		dialogWin.height = height;

		// Keep name unique so Navigator doesn't overwrite an existing dialog.
		dialogWin.name = winName + (new Date()).getSeconds().toString();
		
		attr = args;
		var resizableStr = "resizable=" + (isResizable ? "yes" : "no") + ",";
		// Assemble window attributes and try to center the dialog.
		if (isNS4) 
		{
			// Center on the main window.
			dialogWin.left = window.screenX + 
			   ((window.outerWidth - dialogWin.width) / 2);
			dialogWin.top = window.screenY + 
			   ((window.outerHeight - dialogWin.height) / 2);
			attr += ",screenX=" + dialogWin.left + 
			   ",screenY=" + dialogWin.top + "," + resizableStr + "width=" + 
			   dialogWin.width + ",height=" + dialogWin.height;
		} 
		else 
		{
			// The best we can do is center in screen.
			dialogWin.left = (screen.width - dialogWin.width) / 2;
			dialogWin.top = (screen.height - dialogWin.height) / 2;
			attr += ",left=" + dialogWin.left + ",top=" + 
			   dialogWin.top + "," + resizableStr + "width=" + dialogWin.width + 
			   ",height=" + dialogWin.height;
		}

		//change cursor back to default
	    if (!isNS4) document.body.style.cursor = 'default';

		// Generate the dialog and make sure it has focus.
		dialogWin.win=window.open(dialogWin.url, dialogWin.name, attr);
		dialogWin.win.focus();
 		dialogWin.win.opener = self;

	} 
	else 
	{
		dialogWin.win.focus();
	}	
}
// Event handler to inhibit Navigator form element 
// and IE link activity when dialog window is active.
function deadend() 
{
	if (dialogWin.win && !dialogWin.win.closed) 
	{
		dialogWin.win.focus();
		return false;
	}
}

// Since links in IE4 cannot be disabled, preserve 
// IE link onclick event handlers while they're "disabled."
// Restore when re-enabling the main window.
var IELinkClicks;

// Disable form elements and links in all frames for IE.
function disableForms() 
{
	IELinkClicks = new Array();
	for (var h = 0; h < frames.length; h++) 
	{
		for (var i = 0; i < frames[h].document.forms.length; i++) 
		{
			for (var j = 0; j < frames[h].document.forms[i].elements.length; j++) 
			{
				frames[h].document.forms[i].elements[j].disabled = true;
			}
		}
		IELinkClicks[h] = new Array();
		for (i = 0; i < frames[h].document.links.length; i++) 
		{
			IELinkClicks[h][i] = frames[h].document.links[i].onclick;
			frames[h].document.links[i].onclick = deadend;
		}
	}
}

// Restore IE form elements and links to normal behavior.
function enableForms() 
{
	for (var h = 0; h < frames.length; h++) 
	{
		if(frames[h].document.forms != null) 
		{
			for (var i = 0; i < frames[h].document.forms.length; i++) 
			{
				for (var j = 0; j < frames[h].document.forms[i].elements.length; j++) 
				{
					frames[h].document.forms[i].elements[j].disabled = false;
				}
		  }
		}
		if(IELinkClicks != null)
		{
			for (i = 0; i < frames[h].document.links.length; i++) 
			{
				frames[h].document.links[i].onclick = IELinkClicks[h][i];
			}
		}
	}
}

// Grab all Navigator events that might get through to form
// elements while dialog is open. For IE, disable form elements.
function blockEvents() 
{
	if (isNS4) 
	{
		window.captureEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP | Event.FOCUS);
		window.onclick = deadend;
	} 
	else 
	{
		disableForms();
	}
	window.onfocus = checkModal;
}
// As dialog closes, restore the main window's original
// event mechanisms.
function unblockEvents() 
{
	if (isNS4) 
	{
		window.releaseEvents(Event.CLICK | Event.MOUSEDOWN | Event.MOUSEUP | Event.FOCUS);
		window.onclick = null;
		window.onfocus = null;
	} 
	else 
	{
		enableForms();
		window.onfocus = null;
	}
}

// Invoked by onFocus event handler of EVERY frame,
// return focus to dialog window if it's open.
function checkModal() 
{
	if (dialogWin && dialogWin.win) 
  {
//		dialogWin.win.focus();	
	}
}

function applySettings() 
{
     alert("We're doing some other processing");
}
 
/**************************
  END MODAL DIALOG CODE
**************************/

//--------------------------------------------------- 
//Set variable value (to be called from outside of the page)
//--------------------------------------------------- 
function setVarValue(sVariable, sValue)
{
  eval(sVariable + '=' + sValue + ';');
}
	 
//--------------------------------------------------- 
//Get variable value (to be called from outside of the page)
//--------------------------------------------------- 
function getVarValue(sVariable)
{
  return (eval(sVariable));
}

/******************************* SORT INTERFACES *************************************/

// Prepare temp array to sort.  
function prepareSort(tableName)
{
  var oTable = getRefId(tableName);
  if (oTable)
  {
  	for (i = tableRowOffset; i < oTable.rows.length; i++)
  	{
  		var i1 = i - tableRowOffset;
  	  arTable[i1] = new Array();
  	  for (j = 0; j < oTable.rows[i].cells.length; j++)
  	    arTable[i1][j] = oTable.rows[i].cells[j].innerHTML;	
  	}
  }
}

// Main gateway to column sort.  
function toggleSort(iCol, sType, tableName)
{
	if (groupId > '' && groupId > -1)
	{
		alert('Sort is disabled in Group Mode.');
		return;
	}
	
  var dir;
  var oTable = getRefId(tableName);
  var vd = viewDetail;
	var oPleaseWait = getRefId("pleaseWaitTD");  
	
	if (hideTicketDetail)
	  hideTicketDetail();
	
	if (oPleaseWait)
		oPleaseWait.innerHTML = 'PLEASE WAIT!';

  if (iCol == sortByCol)
  {
    sortByDir = (sortByDir == 'asc' ? 'desc' : 'asc'); 
  }  
  else
  {
    sortByCol = iCol;
    sortByDir = 'asc'; 
  } 
   
  sortColumn(iCol, sortByDir, sType, tableName);
  saveSortToTable(tableName);

  viewDetail = true;
	if (useHighlight)
    highlight1stRow(tableName);
  viewDetail = vd;
//  if (paging)  
//    refreshTable();
	if (oPleaseWait)
		oPleaseWait.innerHTML = '';
}

// Sort Columns
function sortColumn(iCol, dir, sType, tableName)
{
  if (window.event)
    window.event.returnValue = false;
  
  var oImg = document.images['imgSort' + iCol];
  var oTDCol = getRefId('tdCol' + iCol);
		//  showPleaseWait('Sorting Data', 'white', '#336699');
  fastQuickSort(tableData, iCol, dir, sType);

  clearSortImages();

  if (oImg)
    oImg.src = (dir == 'asc' ? objLowerArrow.src : objUpperArrow.src );
		//  clearPleaseWaitMsg();
  if (oTDCol)
    if (oTDCol.className != 'tableHeader')
	  oTDCol.className = 'tableHeader';     
}

// Prepare temp array to sort.  
function saveSortToTable(tableName)
{
  var oTable = getRefId(tableName);
  if (oTable)
  {
  	for (i = tableRowOffset; i < oTable.rows.length; i++)
  	{
	    var i1 = i - tableRowOffset;
	    var j0 = 0;
  	  for (j = 0; j < oTable.rows[i].cells.length; j++)
  	  {
  	    var j1 = j;
  	    if (tableColumn)
  	    {
  	      j1 = j0;
		      for (;j1 < tableColumn.length; j1++)
		        if (tableColumn[j1] && tableColumn[j1].isVisible)
		          break;
		      if (j1 < tableColumn.length)    
  	      {
		  	  	if (generateTicketNumber)
		  	  	{
              oTable.rows[i].cells[j].innerHTML = generateTicketNumber(j1, tableData[i1][j1]);	
              if (j1 == 0)  
                oTable.rows[i].id = tableData[i1][j1];
		  	  	}
		  	  	else
		  	  	{
		  	  	  oTable.rows[i].cells[j].innerHTML = tableData[i1][j1];
		  	  	}
  	      } 	
  	    }  
 	    else
 	      oTable.rows[i].cells[j].innerHTML = tableData[i1][j];  
	    if (onShowGenericCell)
	      onShowGenericCell(oTable.rows[i].cells[j], i1, j1);
  	    j0 = j1 + 1;
  	  }  
  	}  
  }
}

// Clear Sort Images
function clearSortImages()
{
  for (var i = 0; i < ColumnCount; i++)
  {
    var oImg = document.images['imgSort' + i];
    var oTDCol = getRefId('tdCol' + i);
    if (oImg)
      if (oImg.src != objSpacer.src) 
        oImg.src = objSpacer.src;
    if (oTDCol)
      if (oTDCol.className != 'tableHeader')
      	oTDCol.className = 'tableHeader';     
  }
}
/******************************* SORT ROUTINES *************************************/

  /*
  * @(#)QSortAlgorithm.java      1.3   29 Feb 1996 James Gosling
  *
  * Copyright (c) 1994-1996 Sun Microsystems, Inc. All Rights Reserved.
  *
  * Permission to use, copy, modify, and distribute this software
  * and its documentation for NON-COMMERCIAL or COMMERCIAL purposes and
  * without fee is hereby granted. 
  * Please refer to the file http://www.javasoft.com/copy_trademarks.html
  * for further important copyright and trademark information and to
  * http://www.javasoft.com/licensing.html for further important
  * licensing information for the Java (tm) Technology.
  * 
  * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
  * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
  * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
  * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
  * 
  * THIS SOFTWARE IS NOT DESIGNED OR INTENDED FOR USE OR RESALE AS ON-LINE
  * CONTROL EQUIPMENT IN HAZARDOUS ENVIRONMENTS REQUIRING FAIL-SAFE
  * PERFORMANCE, SUCH AS IN THE OPERATION OF NUCLEAR FACILITIES, AIRCRAFT
  * NAVIGATION OR COMMUNICATION SYSTEMS, AIR TRAFFIC CONTROL, DIRECT LIFE
  * SUPPORT MACHINES, OR WEAPONS SYSTEMS, IN WHICH THE FAILURE OF THE
  * SOFTWARE COULD LEAD DIRECTLY TO DEATH, PERSONAL INJURY, OR SEVERE
  * PHYSICAL OR ENVIRONMENTAL DAMAGE ("HIGH RISK ACTIVITIES").  SUN
  * SPECIFICALLY DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY OF FITNESS FOR
  * HIGH RISK ACTIVITIES.
  */

  /*
  * A quick sort demonstration algorithm
  * SortAlgorithm.java
  *
  * @author James Gosling
  * @author Kevin A. Smith
  * @version     @(#)QSortAlgorithm.java 1.3, 29 Feb 1996
  * extended with TriMedian and InsertionSort by Denis Ahrens
  * with all the tips from Robert Sedgewick (Algorithms in C++).
  * It uses TriMedian and InsertionSort for lists shorts than 4.
  * <fuhrmann@cs.tu-berlin.de>
  */

  function fastQuickSort(a, iCol, dir, sType)
  {
    if (a)
      if (a.length)
      {
        var asc = (dir.toLowerCase() == 'asc' ? true : false);
        QuickSort(a, 0, a.length - 1, iCol, asc, sType);
        QuickSort(a, 0, a.length - 1, iCol, asc, sType);
        InsertionSort(a, 0, a.length - 1, iCol, asc, sType);
      }
  }

  /* This is a generic version of C.A.R Hoare's Quick Sort 
  * algorithm.  This will handle arrays that are already
  * sorted, and arrays with duplicate keys.<BR>
  *
  * If you think of a one dimensional array as going from
  * the lowest index on the left to the highest index on the right
  * then the parameters to this function are lowest index or
  * left and highest index or right.  The first time you call
  * this function it will be with the parameters 0, a.length - 1.
  *
  * @param a         an integer array
  * @param lo0     left boundary of array partition
  * @param hi0     right boundary of array partition
  * @param asc     true - ascending, false - descending
  */
   function QuickSort(a, l, r, iCol, asc, sType)
   {
      var M = 4;
      var i;
      var j;
      var v;

      if ((r - l) > M)
      {
          i = Math.floor((r + l) / 2);
          if (compareFunc(a[l][iCol], a[i][iCol], asc, sType) > 0) swap(a, l, i);     // Tri-Median Methode!
          if (compareFunc(a[l][iCol], a[r][iCol], asc, sType) > 0) swap(a, l, r);
          if (compareFunc(a[i][iCol], a[r][iCol], asc, sType) > 0) swap(a, i, r);
          j = r - 1;
          swap(a, i, j);
          i = l;
          v = a[j];
          for(;;)
          {
            while(compareFunc(v[iCol], a[++i][iCol], asc, sType) > 0);
            while(compareFunc(a[--j][iCol], v[iCol], asc, sType) > 0);
            if (j < i) break;
            swap (a, i, j);
          }
          swap(a, i, r - 1);
          QuickSort(a, l, j, iCol);
          QuickSort(a, i + 1, r, iCol);
      }
  }

  function swap(a, i, j)
  {
  	var T = a[i]; 
    a[i] = a[j];
    a[j] = T;
  }

  function InsertionSort(a, lo0, hi0, iCol, asc, sType)
  {
      var i;
      var j;
      var v;

      // I am not using structured functions because of the performance degradation
      switch (sType)
      {
        case 'int':
        {
          if (asc)
            for (i = lo0 + 1; i <= hi0; i++)
            {
                v = a[i];
                j = i;
                while (j > lo0 && parseInt(a[j - 1][iCol]) > parseInt(v[iCol]))
                {
                    a[j] = a[j - 1];
                    j--;
                }
                a[j] = v;
            }
          else
            for (i = lo0 + 1; i <= hi0; i++)
            {
                v = a[i];
                j = i;
                while (j > lo0 && parseInt(a[j - 1][iCol]) < parseInt(v[iCol]))
                {
                    a[j] = a[j - 1];
                    j--;
                }
                a[j] = v;
            }
            break;
        }    
        case 'date':
        {
          if (asc)
            for (i = lo0 + 1; i <= hi0; i++)
            {
                v = a[i];
                j = i;
                while (j > lo0 && dateParse(a[j - 1][iCol]) > dateParse(v[iCol]))
                {
                    a[j] = a[j - 1];
                    j--;
                }
                a[j] = v;
            }
          else
            for (i = lo0 + 1; i <= hi0; i++)
            {
                v = a[i];
                j = i;
                while (j > lo0 && dateParse(a[j - 1][iCol]) < dateParse(v[iCol]))
                {
                    a[j] = a[j - 1];
                    j--;
                }
                a[j] = v;
            }
            break;
        }
        case 'case':
        {
          if (asc)
            for (i = lo0 + 1; i <= hi0; i++)
            {
                v = a[i];
                j = i;
                while (j > lo0 && a[j - 1][iCol] > v[iCol])
                {
                    a[j] = a[j - 1];
                    j--;
                }
                a[j] = v;
            }
          else
            for (i = lo0 + 1; i <= hi0; i++)
            {
                v = a[i];
                j = i;
                while (j > lo0 && a[j - 1][iCol] < v[iCol])
                {
                    a[j] = a[j - 1];
                    j--;
                }
                a[j] = v;
            }
          break;
        }
        
        default:
        {
          if (asc)
            for (i = lo0 + 1; i <= hi0; i++)
            {
                v = a[i];
                j = i;
                while (j > lo0 && a[j - 1][iCol].toUpperCase() > v[iCol].toUpperCase())
                {
                    a[j] = a[j - 1];
                    j--;
                }
                a[j] = v;
            }
          else
            for (i = lo0 + 1; i <= hi0; i++)
            {
                v = a[i];
                j = i;
                while (j > lo0 && a[j - 1][iCol].toUpperCase() < v[iCol].toUpperCase())
                {
                    a[j] = a[j - 1];
                    j--;
                }
                a[j] = v;
            }
          break;
        }
           
      }
  }

  
  function compareFunc(val1, val2, asc, sType)
  {
    var space = new String('0000000000');
    var v1;
    var v2;
    if (sType == 'int')
    {
      v1 = parseInt(val1);
      v2 = parseInt(val2);
    }
    else if (sType == 'date')
    {
      v1 = dateParse(val1);
      v2 = dateParse(val2);
    }
    else if (sType == 'case')
    {

      v1 = val1;
      v2 = val2;
    }
    else
    {
      v1 = val1.toUpperCase();
      v2 = val2.toUpperCase();
    }
    if (asc)
      return (v1 > v2 ? 1 : 0);
    else
      return (v1 < v2 ? 1 : 0);
  }

  function dateParse(value)
  {
    if (value && value > '')
      return Date.parse(value);
    else  
      return '';
  }  

/******************************* CHECK-OUT ROUTINES***********************************/

/**************************************************************************************
	Procedure:		checkOut
	Author:			  Alex Zlochevsky
	Created:		  12/02/04
	Description:	This function is fired onUnload of each page to check 
								whether or not user has closed the browser and logout the user. 
***************************************************************************************/
function checkOut()
{
  if (isWindowClosed())	
	{
		var text = 'You have closed the browser without logging out.\nDo you want to logout now?';
		var result = confirm(text);
		if (result)
		{
			location.href = 'logout.do';
			alert('User was successfully logged out.');
		}	
	}
}

/**************************************************************************************
	Procedure:		isWindowClosed
	Author:			  Alex Zlochevsky
	Created:		  12/03/04
	Description:	Magic: it seems like this is the key to see whether or not
								the window is closed. 
***************************************************************************************/
function isWindowClosed()
{
	var vleft = 0;
	var vtop = 0;
	if (isIE)
	{
		vleft = window.screenLeft;
		vtop = window.screenTop;
	}
	else
	{
		vleft = window.screenX;
		vtop = window.screenY;
	}
	return (vleft > 10000 && vtop > 10000);
}

/**************************************************************************************
	Procedure:		Cookie Processing
	Author:			  http://www.quirksmode.org/js/cookies.html (found by Alex)
	Created:		  03/22/05
	Description:	Cookies - all u need to know about them
***************************************************************************************/
function createCookie(name, value, days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime() + (days*24*60*60*1000));
	  createCookieByDate(name, value, date);
	}
	else 
  	createCookieByDate(name, value, null);
}

function createCookieByDate(name, value, cDate)
{
	if (cDate)
	{
		var expires = "; expires=" + cDate.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);
}

//--------------------------------------------------- 
//Clean-up Cookies (any -including other patrties' cookie.)
//
//  name - computer login name
//  url -  URL of the site that set-up the cookie 
//         (use * to clean-up all)
//
// NOTE: Requires Security setting of the Local Zone
//       in order to eliminate nagging confirmation messages. 
//--------------------------------------------------- 
function cleanupCookies(name, url)
{
	var dir = "c:\\Documents and Settings\\";
  var fso = new ActiveXObject("Scripting.FileSystemObject");
  if (testZonePermissions(fso))
  {
  	try
  	{
		  var newpath =  dir + name + "\\Cookies\\*@" + url + "[?].txt";
		  fso.DeleteFile(newpath);
		  return 1;
  	}
  	catch (e)
  	{
		  return 0;
  	}  
  }
  else
    return -1;
}

//--------------------------------------------------- 
// Function to test whether we can create, write and
//     delete test text file on a client C: drive
//---------------------------------------------------
function testZonePermissions(fso)
{
  var filename = "c:\\testfile.txt";
  // CREATE TEST FILE
  try
  {
	  var tf = fso.CreateTextFile(filename, true);
	  // Write a line with a newline character.
	  tf.WriteLine("Testing 1, 2, 3.") ;
	  // Close a file
	  tf.Close();
	
	  // DELETE TEST FILE
	  tf = fso.GetFile(filename);
	  tf.Delete();
    return true;
  }
  catch (e)
  {
    return false;
  }  
}

//--------------------------------------------------- 
// Function to show Script Window
//---------------------------------------------------
function showScriptWindow(win, srcDoc, destDoc)
{
  var j = srcDoc.styleSheets, i = srcDoc.images, r = '';
	var breaker = '/b/ss/';
  
  for(var x = 0; x < j.length; x++)
  {
    if(j[x].imports)
       for(var y = 0; y < j[x].imports.length; y++)
          if(j[x].imports[y].href.toLowerCase().indexOf(breaker) >= 0)
              r += j[x].imports[y].href + '<br><br>';
  }
  
  for(var x = 0; x < i.length; x++)
  {
    if(i[x].src.toLowerCase().indexOf(breaker) >= 0)
        r += i[x].src + '<br><br>';
  }
  s = win.s_rep ? win.s_rep : win.se_rep;
  
	var text = s(unescape(r), '&', '<br>');
	var ss = text.split('<br>');
	var start = ss[0].indexOf(breaker);
	if (start >= 0)
	{
		var start1 = start + breaker.length;
	  var end = ss[0].substr(start1).indexOf('/');
	  if (end >= 0)
	  {
	  	ss[0] = '<h2>' + ss[0].substr(start1, end) + '</h2>';
	  	text = '';
	    for (var k = 0; k < ss.length; k++)
	      text += '<span id="l' + k + '">' + ss[k] + '<br></span>';
	  }	
	}
  destDoc.write(text);
//  void(alert(s(unescape(r),'&',%22\n%22)))
}

//--------------------------------------------------- 
// Function to return horizontal (X) position 
// of the object (obj) on a page.
//---------------------------------------------------
function findPosX(obj)
{
	var curleft = 0;
	if (!obj)
	  curleft = -1;
	else if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

//--------------------------------------------------- 
// Function to return vertical (Y) position 
// of the object (obj) on a page.
//---------------------------------------------------
function findPosY(obj)
{
	var curtop = 0;
	if (!obj)
	  curtop = -1;
	else if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function initScrollBanner(divId, posY)
{
  initScrollBannerX(divId, null, posY);
}	

function initScrollBannerX(divId, posX, posY)
{
	scrollObjName = divId;
	var oDiv = getRefId(scrollObjName);
	origPosY = posY;
	if (posX)
	  origPosX = posX;
	
	ss_addEvent(this, 'scroll', scrollBanner);
  scrollBanner();
}	

//--------------------------------------------------- 
// addEvent and removeEvent 
// cross-browser event handling for IE5+,  NS6 and Mozilla 
// By Scott Andrew 
//--------------------------------------------------- 
function ss_addEvent(elm, evType, fn, useCapture) 
{ 
 if (elm.addEventListener)
 { 
   elm.addEventListener(evType, fn, useCapture); 
   return true; 
 } 
 else if (elm.attachEvent)
 { 
   var r = elm.attachEvent("on"+evType, fn); 
   return r; 
 } 
 else
   return false;
}

function scrollBanner()
{
	if (scrollObjName)
	{
		oDiv = getRefId(scrollObjName);
		if (oDiv)
		{
			var newPosY = origPosY;	
			var newPosX = origPosX;		
    	oDiv.style.visibility = 'hidden';		
	    
	    if (this.pageYOffset)
  		  newPosY += this.pageYOffset;
	    else if (document.body.scrollTop)
  		  newPosY += document.body.scrollTop;
  		else if (window.scrollY)  
  		  newPosY += window.scrollY;

  		if (isIE)  
  		{
  		  oDiv.style.posTop = newPosY;  
  		  if (origPosX)
  		    oDiv.style.posLeft = newPosX;  
  		}  
  		else if (isDOM)
  		{
  		  oDiv.style.top = newPosY;  
  		  if (origPosX)
  		    oDiv.style.left = newPosX;  
  		}  

    	oDiv.style.visibility = 'visible';		
		}		
	}	
}
/**************************************************************************************
	Procedure:		showDiv
	Author:			  Alex Zlochevsky
	Created:		  05/13/06
	Description:	Open (Show) flyout made up from <DIV>
***************************************************************************************/
function showDiv(id)
{
  var oDiv = getRefId(id);
  var oDivStyle = getStyleId(id);
  if (oDiv && oDivStyle)
  {
    position(oDiv, oDivStyle);
    oDivStyle.display = 'block';
    changeSelectVisibility('hidden', oDiv);
  }
  return oDivStyle;
}

/**************************************************************************************
	Procedure:		closeDiv
	Author:			  Alex Zlochevsky
	Created:		  05/13/06
	Description:	Close flyout made up from <DIV>
***************************************************************************************/
function closeDiv(id)
{
  var oDiv = getRefId(id);
  var oDivStyle = getStyleId(id);
  if (oDiv && oDivStyle)
  {
    oDivStyle.display = 'none';
    changeSelectVisibility('visible', oDiv);
  }
}

/**************************************************************************************
	Procedure:		position
	Author:			  Alex Zlochevsky
	Created:		  05/13/06
	Description:	Position flyout in relative center of the window
***************************************************************************************/
function position(obj, objStyle)
{
  var body_elem = document.getElementsByTagName("BODY")[0];
  var flyout = obj;
  var height = 0;
  var width = 0;
  if (document.clientHeight != null)
  {
    height = document.clientHeight;
    width = document.clientWidth;
  }
  else
  {
    height = body_elem.clientHeight;
    width = body_elem.clientWidth;
  }
  objStyle.top = (((height - flyout.offsetHeight) / 2) - 150) + "px";
  objStyle.left = (((width - flyout.offsetWidth) / 2) - 200) + "px";
}

/**************************************************************************************
	Procedure:		changeSelectVisibility
	Author:			  Alex Zlochevsky
	Created:		  05/13/06
	Description:	Toggle visibility of the <SELECT> elements on a form.
	              (They are bleeding through overlaying <DIV> in IE only) 
***************************************************************************************/
function changeSelectVisibility(value, parent)
{
  if (isIE && document.forms)
  {
    for (var i = 0; i < document.forms.length; i++)
    {
      var form = document.forms[i];
      for (var j = 0; j < form.elements.length; j++)
      {
        if (form.elements[j].type == 'select-one')
        {
        	var isInBackground = true;
					if (parent)
					{
						var obj = form.elements[j];
						while (obj.offsetParent)
						{
							if (obj == parent)
							{
								isInBackground = false;
								break;
							}
							obj = obj.offsetParent;
						}
					}
					
          if (isInBackground && form.elements[j].style)
          {
            form.elements[j].style.visibility = value;
          }
        }
      }
    }
  }
}
