/** Generic JavaScript Library ********************************** jslib.js **/
/************ Copyright (c) 1987-2007 by DISCOVERY TRAVEL SYSTEMS LP *********
 This program is the confidential and proprietary product of DISCOVERY TRAVEL
 SYSTEMS LP.  Any unauthorized use, reproduction or transfer of this product is
 strictly prohibited. Subject to limited distribution and restricted disclosure
 only.  All rights reserved.
*****************************************************************************/
var isNS = navigator.appName == "Netscape";
var isIE = !isNS;
var selectText = "";

// Generic function for submiting a form with optional capability
// to override default form action.
function formSubmit(frm, act)
{
   if (act != "")
      eval("document." + frm + ".action = '" + act + "'");
   eval("document." + frm + ".submit()");
}

// Platform-independent definition of JavaScript regular expressions
// used for validating data types.
var datePat = /^\d\d?\/\d\d?\/(\d\d)?\d\d$/;
var intePat = /^ *-?\d+ *$/;
var deciPat=/^ *-?\d*(\.\d*)? *$/;

// Body onload function to set onFocus and onKeypress event handlers
// on all <select> objects
function setupSelects()
{
  for (i=0; i<document.forms.length; i++)
    for (j=0; j<document.forms[i].elements.length; j++)
      if (document.forms[i].elements[j].type.search("select") == 0)
      {
        // Save existing onFocus handler if any
        document.forms[i].elements[j].oldOnfocus = document.forms[i].elements[j].onfocus;
        document.forms[i].elements[j].onfocus    = clearSelectText;
        document.forms[i].elements[j].onkeypress = handleSelectKeyPress;
        if (isIE)
        document.forms[i].elements[j].onkeydown  = handleSelectKeyPress;
        if (isNS && document.forms[i].elements[j].onchange)
          document.forms[i].elements[j].onblur = document.forms[i].elements[j].onchange;
      }

  // Disable Ctrl-N in IE
  if (window.event)
    document.onkeydown = function() {
      if (window.event.ctrlKey && window.event.keyCode == 78)
      {
        window.event.cancelBubble = true;
        window.event.returnValue  = false;
        window.event.keyCode      = false;
        return false;
      }
    }

  // Did the window have a previous onLoad handler?
  if (window.oldOnload) window.oldOnload();
}

function clearSelectText()
{
  selectText = "";

  // Did the widget have a previous onFocus handler?
  if (this.oldOnfocus)
    this.oldOnfocus();
}

function handleSelectKeyPress(evt)
{
  var evt, key, myChar, field;
  var fieldChanged = false;

  if (isIE)
    evt = window.event;
  key = isNS ? evt.which : evt.keyCode;
  myChar = String.fromCharCode(key);
  field = isNS ? evt.target : evt.srcElement;

  // For IE, we need to capture Backspace on the keyDown event;
  // otherwise it triggers the brower Back function.
  // All other keyDown events need to be handled by default handler.
  // For NS, all non-ASCII keys but BS need to be handled by default
  // handler.  Otherwise things like Tab and Backtab don't work.
  if (key == 8) /* Backspace */
    selectText = selectText.slice(0, -1);
  else if (evt.type == "keydown" || (isNS && key == 0))
    return true;
  else
    selectText += myChar.toLowerCase();

  // Any values begin with selectText?
  for (i=0; i<field.length; i++)
    if (field.options[i].text.toLowerCase().search(selectText) == 0)
    {
      if (field.selectedIndex != i && field.onchange)
        fieldChanged = true;
      field.selectedIndex = i;
      if (fieldChanged)
        field.onchange();
      return false;
    }

  // Nope - strip this char off end of selectText to ignore it
  selectText = selectText.slice(0, -1);
  return false;
}

// Re-size help popups to make sure they're wide enough for the contents
function resizeHelpPopup(win)
{
  if (win.resizeBy)
  {
    var doc  = win.document;
    var maxW = 0;
    var w    = doc.body.offsetWidth;

    for (i=0; i<doc.forms.length; i++)
      for (j=0; j<doc.forms[i].elements.length; j++)
        maxW = Math.max(maxW, doc.forms[i].elements[j].offsetWidth);

    maxW += 20;

    if (maxW > w)
      win.resizeBy(maxW - w, 0);
  }
}


// Function for handling date entry into a field, automatically inserting
// slashes between every pair of digits.
function doDateEntry(evt)
{
  var key, ch, field;

  key = isNS ? evt.which : evt.keyCode;
  ch  = String.fromCharCode(key);
  field = isNS ? evt.target : evt.srcElement;

  if (key == 8) /* Backspace */
    return true;

  // For NS, all non-ASCII keys but BS need to be handled by default
  // handler.  Otherwise things like Tab and Backtab don't work.
  if (evt.type == "keydown" || (isNS && key == 0))
    return true;

  if (field.value.length == 1 && ch == '/')
  {
    field.value = "0" + field.value + "/";
    return false;
  }

  if (field.value.length == 4 && ch == '/')
  {
    field.value = field.value.substr(0,3) + "0" + field.value.substr(3,1) + "/";
    return false;
  }

  if ((field.value.length == 2 || field.value.length == 5) && ch != '/')
    field.value += '/';

  return (ch == '/' || (ch >= '0' && ch <= '9'));
}

// Function to re-sort the data in an HTML table.
// Implement like this:
// <th class="section" align="left" id="startDate"><a class="sortcol" href="javascript:tableSort('startDate/date,pkgCode/char,catg/char')">Start Date</a></th>
// - Add an ID to the <th> tag for each column to be used for sorting
// - Wrap an <a> tag around the column header
// - The arguments to the tableSort function are a comma-separated of sort columns.
// - Each entry in list is columnName/dataType
function tableSort(sortColList)
{
  var objTH, objTD, objTR, objTBODY;
  var dataRows;
  var i, j, s;

  // Input is list of sort columns and data types as id1/char,id2/date,id3/num
  sortColArray = sortColList.split(",");
  sortCols = new Array(sortColArray.length);
  for (i=0; i<sortColArray.length; i++)
  {
    sortCols[i] = new Object();
    sortCols[i].colID    = sortColArray[i].split("/")[0];
    sortCols[i].dataType = sortColArray[i].split("/")[1];
  }

  // Find the <th> or <td> for the first sort column
  objTH = document.getElementById(sortCols[0].colID);
  while (objTH.nodeName != "TH" && objTH.nodeName != "TD")
    objTH=objTH.parentNode;

  // Find the <tr> and <tbody>
  objTR=objTH.parentNode;
  objTBODY=objTR.parentNode;

  // Find the column numbers of the sort columns
  for (i=0; i<sortCols.length; i++)
    for (sortCols[i].colNo=0; sortCols[i].colNo<objTR.cells.length; sortCols[i].colNo++)
      if (objTR.cells[sortCols[i].colNo] == document.getElementById(sortCols[i].colID))
        break;

  // Create array for sorting
  dataRows = new Array(objTBODY.rows.length - 1);
  for (i=1; i<objTBODY.rows.length; i++)
  {
    dataRows[i-1] = new Object();
    dataRows[i-1].TR = objTBODY.rows[i].cloneNode(true);
    dataRows[i-1].sortData = new Array(sortCols.length);

    for (j=0; j<sortCols.length; j++)
    {
      objTD = objTBODY.rows[i].cells[sortCols[j].colNo].firstChild;
      while (objTD.nodeName != "#text")
        objTD = objTD.firstChild;
      s = objTD.nodeValue;

      switch (sortCols[j].dataType)
      {
        case "date":
          // Dates are in format DD MMM YYYY
          datePieces = s.split(/\W/);
          // Put into format MMM DD, YYYY
          s2 = datePieces[1] + " " + datePieces[0] + ", " + datePieces[2];
          dataRows[i-1].sortData[j] = new Date(s2);
          break;
        case "num":
          dataRows[i-1].sortData[j] = new Number(s);
          break;
        default:
          dataRows[i-1].sortData[j] = s;
          break;
      }
    }
  }

  // Sort rows and replace in <tbody> structure
  dataRows.sort(rowCompare);

  for (i=0; i<dataRows.length; i++)
    objTBODY.replaceChild(dataRows[i].TR, objTBODY.rows[i + 1]);

}

function rowCompare(a, b)
{
  for (var i=0; i<a.sortData.length; i++)
    if (a.sortData[i] > b.sortData[i]) return 1;
    else if (a.sortData[i] < b.sortData[i]) return -1;

  return 0;
}

// Function to implement an AJAX call.
// httpRequest(url, method, isXML, payload, handler)
// url = URL to send message to, e.g. 'wstabval.p?etc.' or 'wsdxi.p'
// method = GET or POST
// isXML = logical if call is to send/retrieve XML data
// payload = data, if any, to post
// handler = function to handle return data

var myXHRlist = new Array();

function myXHR(objXHR, isXML, handler)
{
   this.objXHR  = objXHR;
   this.isXML   = isXML;
   this.handler = handler;
}

function httpRequest(url, method, isXML, payload, handler)
{
   var http_request = false;

   if (window.XMLHttpRequest)
   {
     try { http_request = new XMLHttpRequest(); }
     catch(e) { http_request = false; }
   }
   else if (window.ActiveXObject)
   {
     try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); }
     catch (e)
     {
       try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); }
       catch(e) { http_request = false; }
     }
   }

   if (!http_request)
   {
// Browser doesn't support XMLHttpRequest
      return false;
   }

   myXHRlist.push(new myXHR(http_request, isXML, handler));

   if (isXML && http_request.overrideMimeType)
      http_request.overrideMimeType('text/xml');

  http_request.onreadystatechange = function() { processAJAXreq(http_request); };
  http_request.open(method, url, true);

  if (isXML)
    http_request.setRequestHeader("Content-type", "text/xml");
  else if (method == "POST")
    http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  if (payload) http_request.setRequestHeader("Content-length", payload.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(payload);
}

function processAJAXreq(http_request)
{
  for (var i=0; i<myXHRlist.length; i++)
    if (myXHRlist[i].objXHR == http_request)
      break;

  if (http_request.readyState == 4 && http_request.status == 200)
    myXHRlist[i].handler(myXHRlist[i].isXML ? http_request.responseXML : http_request.responseText);
}
function clearData(strChkBoxValue)
{
if(confirm("Do you want to Clear All the changes ?") == true) 
{
var tmpRadName = "tempR1"
for (i = 0; i< document.forms[1].elements.length ; i++)
{
  if(document.forms[1].elements[i].type == "radio" )
   {
    if (document.forms[1].elements[i].name != tmpRadName )
	 {
	  document.forms[1].elements[i].checked = true;
	  tmpRadName = document.forms[1].elements[i].name;
	 }
   }
  else if(document.forms[1].elements[i].type == "checkbox" && document.forms[1].elements[i].value == strChkBoxValue)
    {   alert(document.forms[0].elements[i].value);
	 document.forms[1].elements[i].checked = true;
    }  
  
  else if(document.forms[1].elements[i].type == "text") 
    {	
	 document.forms[1].elements[i].value = "";
	} 
}
}
else 
{ return;
}
}

// Function for handling time entry into a field, automatically inserting
// colons between every pair of digits.
function doTimeEntry(evt)
{
  var key, ch, field;

  key = isNS ? evt.which : evt.keyCode;
  ch  = String.fromCharCode(key);
  field = isNS ? evt.target : evt.srcElement;

  if (key == 4) /* Backspace */
    return true;

  if (field.value.length == 1 && ch == ':')
  {
    field.value = "0" + field.value + ":";
    return false;
  }

  if ((field.value.length == 2) && ch != ':')
    field.value += ':';

  return (ch == ':' || (ch >= '0' && ch <= '9'));
}

function SelectAll(t)
{
eval("document.forms[1]." +t+ ".checked=false");
changed();
}

function selectWeekDays(t)
{
for (i=0; i < eval("document.forms[1]."+t+".length"); i++) 
  {
    eval("document.forms[1]."+t+"["+i+"].checked=false");
  }
changed();
}
/** Checking any change has been occured for data **/
function changed()
{
 document.forms[1].txtChangedEvent.value = "true";
}

/** Function Will invoke From the Scroller Screen of a Page when delete is invoked **/
function doOption(vrecid,mode,str)
 {
    document.forms[1].TxtRecid.value = vrecid; 
    document.forms[1].TxtMode.value  = mode;
    if (mode == "delete")
	  {
			if (confirm("Are you sure want to Delete the Record?"))
			{

				document.forms[1].action='webinit.p?SCR=' + str;
				document.forms[1].submit();
			}
	   }
 }
 /*** **/
function goPanel(act)
{  
  document.forms[0].target = "_top";
  document.forms[0].action = act;
  document.forms[0].submit();
}
function callSubmit(str)
 {
  document.forms[1].action='webinit.p?SCR=' + str;
  document.forms[1].submit();
 } 
function doCaps(strField)
{
eval("document.forms[1]."+strField+".value=document.forms[1]."+strField+".value.toUpperCase();");

}

function closeWindow()
{
   window.open("", "_self", "");
   window.close();
}

function goBackOrClose()
{
  if (isIE && history.length > 0) history.go(-1);
  else if (!isIE && history.length > 1) history.go(-1);
  else closeWindow();
}

/** Fuctions for New  Module start *****************************************************/

function callclearData(strChkBoxValue)
{
if(confirm("Do you want to clear all the changes ?") == true) 
{
var tmpRadName = "tempR1"
for (i = 0; i< document.forms[0].elements.length ; i++)
{
  if(document.forms[0].elements[i].type == "radio" )
   {
    if (document.forms[0].elements[i].name != tmpRadName )
	 {
	  document.forms[0].elements[i].checked = true;
	  tmpRadName = document.forms[0].elements[i].name;
	 }
   }
  else if(document.forms[0].elements[i].type == "checkbox" && document.forms[0].elements[i].value == strChkBoxValue)
    {   
	 
       for (j = i; j< document.forms[0].elements.length; j++)
	  { 
         	if(document.forms[0].elements[j].type == "checkbox")
            		{ document.forms[0].elements[j].checked = ""; }
         }
     document.forms[0].elements[i].checked = true;
    }  
  
  else if(document.forms[0].elements[i].type == "text") 
    {	
	 document.forms[0].elements[i].value = "";
	} 
}
}
else 
{ return;
}
}

// Function for handling time entry into a field, automatically inserting
// colons between every pair of digits.
function calldoTimeEntry(evt)
{
  var key, ch, field;

  key = isNS ? evt.which : evt.keyCode;
  ch  = String.fromCharCode(key);
  field = isNS ? evt.target : evt.srcElement;

  if (key == 4) /* Backspace */
    return true;

  if (field.value.length == 1 && ch == ':')
  {
    field.value = "0" + field.value + ":";
    return false;
  }

  if ((field.value.length == 2) && ch != ':')
    field.value += ':';

  return (ch == ':' || (ch >= '0' && ch <= '9'));
}

function callSelectAll(t)
{
eval("document.forms[0]." +t+ ".checked=false");
callchanged();
}

function callselectWeekDays(t)
{
for (i=0; i < eval("document.forms[0]."+t+".length"); i++) 
  {
    eval("document.forms[0]."+t+"["+i+"].checked=false");
  }
callchanged();
}
/** Checking any change has been occured for data **/
function callchanged()
{
 document.forms[0].txtChangedEvent.value = "true";
}

/** Function Will invoke From the Scroller Screen of a Page when delete is invoked **/
function calldoOption(vrecid,mode,str)
 {
    document.forms[0].txtRecid.value = vrecid; 
    document.forms[0].txtMode.value  = mode;
    if (mode == "delete")
	  {
			if (confirm("Are you sure want to Delete the Record?"))
			{

				document.forms[0].action='webinit.p?SCR=' + str;
				document.forms[0].submit();
			}
	   }
 }
 /*** Function invoked when clicking the left panel **/
function callgoPanel(act)
{  
  document.forms[0].target = "_top";
  document.forms[0].action = act;
  document.forms[0].submit();
}
function calldoSubmit(str)
 {
  document.forms[0].action='webinit.p?SCR=' + str;
  document.forms[0].submit();
 } 

function calldoCaps(strField)
{
eval("document.forms[0]."+strField+".value=document.forms[0]."+strField+".value.toUpperCase();");
}

function checkAvailability(arrayName, field)
{ 
for (i=0; i<validData[arrayName].length; i++)
  if (field.value.toUpperCase() == validData[arrayName][i][0].toUpperCase())
           break;
   if (i >= validData[arrayName].length)
           {
             alert(field.value + " is not a valid value.");
             field.value = "";
             field.focus();
             return(false);
           }
calldoCaps(field.name);
return true;
}
function resetMode()
{
  document.forms[0].txtMode.value = "";
}


/** END of jslib.js **/

