//############################################################################################
// 2005-03-02 : igor  : Added functionality that handles the popup of css window information
//                    : Note that this is provisional code ...
// 2005-04-07 : igor  : This is not provisional code any more
// 2007-11-13 : igor  : fixed email drop down for getdata
//############################################################################################


// ####################################
// initialization variables -- START --
var counter = 1;    // user sort selection index
var _console=null;  // holds the debug window
var Xoffset= 20;    // x offset of sdisp
var Yoffset= 40;    // y offset of sdisp
var x=0;            // x position of sdisp
var y=0;            // y position of sdisp
var sdisp;          // holds the sort display popup div/layer object
var eStack=0;       // counter for the cart data request transfer methods
var eFlag =1;       // flag for setting display condition for email address field
// initialization variables -- END --
// ####################################

//###############################
// Browser detection -- START --
// workout who is who
var isIE=(document.all && (navigator.userAgent.indexOf("MSIE")!=-1))?true:false;
var isNS4=document.layers?true:false;
var isMacOS=navigator.userAgent.indexOf("Mac OS")!=-1?true:false;
var isNS=navigator.userAgent.indexOf("Netscape")!=-1?true:false;
var isNS6=navigator.userAgent.indexOf("Gecko")!=-1?true:false;
var isSafari=navigator.userAgent.indexOf("Safari")!=-1?true:false;
var isMSMAC=((navigator.userAgent.indexOf("MSIE")!=-1) && (navigator.userAgent.indexOf("Mac")!=-1))?true:false;
var isOpera=navigator.userAgent.indexOf("Opera")!=-1?true:false;


var oldBrowser = !(isIE||isNS4||isNS6 || isNS ||isSafari||isOpera);

var isDHTML  = 0;
var isID     = 0;
var isAll    = 0;
var isLayers = 0;

if (document.getElementById) {
  isID    = 1;
  isDHTML = 1;
} else {
  if (document.all) {
    isAll   = 1;
    isDHTML = 1;
  } else {
    browserVersion = parseInt (navigator.appVersion);
    if ( ( navigator.appName.indexOf('Netscape') != -1 ) && ( browserVersion == 4) ) {
      isLayers  = 1;
      isDHTML   = 1;
    }
  }
}
// Browser detection -- END --
//###############################

//#########################################
// generic utilility functions -- START --
// The following two functions has been taken from
// www.quirksmode.org

function getObjNN4(obj,name)
{
	var x = obj.layers;
	var foundLayer;
	for (var i=0;i<x.length;i++)
	{
		if (x[i].id == name)
		 	foundLayer = x[i];
		else if (x[i].layers.length)
			var tmp = getObjNN4(x[i],name);
		if (tmp) foundLayer = tmp;
	}
	return foundLayer;
}

function getObj(name)
{
  if (document.getElementById) {
    this.obj = document.getElementById(name);
    if (document.getElementById(name) != null) {
      this.style = document.getElementById(name).style;
    }
  } else if (document.all) {
    this.obj = document.all[name];
    this.style = document.all[name].style;
  } else if (document.layers) {
    this.obj = getObjNN4(document,name);
	  this.style = this.obj;
  }
}

function hide (objectID)
{
  var _lhide = new getObj(objectID);
  if (_lhide == null ) return;
  if (_lhide.style) {
    _lhide.style.display='none';
  }
}

function show (objectID)
{
  // for DOM support browsers (not IE) let the display be set to empty string
  var _lshow = new getObj(objectID);
  if (_lshow == null ) return;

  if (isID && _lshow.style) {
    _lshow.style.display='';  // default should be inline
    _lshow.style.visibility='visible';
  } else if (_lshow.style) { 
    _lshow.style.display='block';
  }
}
// generic utilility functions -- END --
//#########################################

// ####################################
// initialization functions -- START --
function initPopup()
{
startTimer("initPopup");
//  debug ("initPopup");
  sdisp= new getObj('headerpopup');

  // On a "Go Back Page" make sure the header checkboxes
  // are in right sort order
startTimer("gobackpage");
  if (document.RecordSet.newSortIOrder != null &&
      (document.RecordSet.newSortIOrder.value.length>0
       || document.RecordSet.newDisplayIOrder.value.length>0)) {
      var lorder;
      if (document.RecordSet.newSortIOrder.value.length>0 )
        lorder = document.RecordSet.newSortIOrder.value;
      else
        lorder = document.RecordSet.newDisplayIOrder.value;
         
      var lallArr = lorder.split(/:\s/);
      var lorderArr = lallArr[0].split(/,\s/);
      counter = lorderArr.length + 1;
      for (var i=lorderArr.length;  i>0; i--)
        {
          sortArr[sortIndexName[lorderArr[i-1]]]=i;
        }
    }
endTimer("gobackpage");
   // work around funny safari behauviour
startTimer("safariworkaround");
//   if (document.RecordSet.elements["clickOption"] != null) {
//     document.RecordSet.elements["clickOption"][0].checked=false;
//     document.RecordSet.elements["clickOption"][1].checked=false;
//     document.RecordSet.elements["clickOption"][2].checked=true;
//   }
endTimer("safariworkaround");

startTimer("minMaxInit");
minMaxInit();
display_cartid();
endTimer("minMaxInit");
endTimer("initPopup");
}
// initialization functions -- END --
// ####################################

//#######################################
// grid column order functions -- START --

// Keeps the order status
// The little popup box under the checkbox header
function sortOrder(which, headType)
{
  var index=(headType =='h')?0:1;
  var nindex=(headType !='h')?0:1;

  document.RecordSet.elements[which.name][nindex].checked = document.RecordSet.elements[which.name][index].checked;

  if ( document.RecordSet.elements[which.name][index].checked == true)
    {
      sortArr[which.name]=counter++;
    }
  else
    {
      sortArr[which.name]=0;
    }

  removeBox();
  displayOrder(which, "white");
}

// Prepares the sort array
// before submiting it
function view(_name)
{
  // the hidden submit field acts as function trigger
//  debug (_name);
  document.RecordSet.viewname.value = _name;
  document.RecordSet.currentDisplayIOrder.value=document.RecordSet.elements[_name].value;
  document.RecordSet.newDisplayIOrder.value=document.RecordSet.elements[_name].value;
  document.RecordSet.newSortIOrder.value=document.RecordSet.elements[_name].value;

  document.RecordSet.doAction.value = "redraw";
  document.RecordSet.submit();
}

function toSession (_sessionID)
{
	if ( document.RecordSet.sessionID.value != _sessionID ) {
		document.RecordSet.sessionID.value = _sessionID;
		document.RecordSet.doAction.value = "redraw";
		document.RecordSet.submit();
	}
}

function toPage(_pageNumber)
{
  if ( document.RecordSet.currentPage.value != _pageNumber ) {
    document.RecordSet.nextPage.value = _pageNumber;
    document.RecordSet.doAction.value = "redraw";
    document.RecordSet.submit();
  }
}

// Prepares the sort array
// before submiting it
function sortColumns(_type)
{
  var lorder= buildOrderArray();

  document.RecordSet.colAction.value = _type;
  if (_type == 'sortonly')
   {
      document.RecordSet.newSortIOrder.value=lorder;
      document.RecordSet.newDisplayIOrder.value="";
   }
  else if (_type == 'sortarrange')
   {
      document.RecordSet.newSortIOrder.value=lorder;
      document.RecordSet.newDisplayIOrder.value=lorder;
   }
  else if (_type == 'arrangeonly')
   {
      document.RecordSet.newSortIOrder.value="";
      document.RecordSet.newDisplayIOrder.value=lorder;
   }
  // the hidden submit field acts as function trigger
  document.RecordSet.doAction.value = "redraw";
  document.RecordSet.submit();
}

// It does exactly what it says
function removeBox()
{
  sdisp.style.visibility="hidden";
}

// notice the ": " this devides selected columns
// from the not selected ones
function buildOrderArray()
{
  var msgArr = "";
  var msgDef = "";
  var newCnt = 0;
  var newColumnOrder = new Array();
  for (i=0; i<chkName.length ;i++) {
      if(sortArr[chkName[i]] > 0) {
          newColumnOrder[newCnt++] = chkName[i];           
        }
      else  {// build the default/left over (not selected) columns
          if (msgDef.length>0) { msgDef += ", "; }
          msgDef += sortNameIndex[chkName[i]];
        }
    }

  var lnames = newColumnOrder.concat([]);
  lnames.sort(_order);

  for (i=0; i<lnames.length ;i++) {
      if(sortArr[lnames[i]] > 0) {
          if (msgArr.length>0) { msgArr += ", "; }
          msgArr += sortNameIndex[lnames[i]];
        }
    }
  
  if (msgArr.length>0) { return msgArr + ": " + msgDef; }
  else { return ""; }
}

function order2string(_b)
{
  var lnames = chkName.concat([]);
  lnames.sort(_order);

  var defArr = new Array(lnames.length);
  var msgArr = "";
  var msgDef = "";
  for (i=0; i<lnames.length ;i++) {
    if(sortArr[lnames[i]] > 0) {
      if (msgArr.length>0) {
        msgArr += ", ";
      }
    
      if (_b) {
        msgArr += lnames[i];
      } else {
        msgArr += sortNameDesc[lnames[i]];
      }
    } else {
      defArr[sortNameIndex[lnames[i]]]=lnames[i];
    }
  }
  
  if (_b) {
    for(i=0; i<defArr.length; i++) {
      if (defArr[i] != null) {
        if (msgDef.length>0) {
          msgDef += ", ";
        }
        msgDef += defArr[i];
      }
    }
  }
  
  if (msgArr.length>0) {
    if (_b) {
      return msgArr + ": " + msgDef;
    } else return msgArr;
  } else {
    if (_b) {
      return msgDef;
    } else return null;
  }
}

// Displays the use order selection
function displayOrder(object, _b)
{
  // notice that no args are passed in
  // 'cause we want the sort Descriptions
  // to display  
  var strOrder = order2string();
  var msgText ="";
  if (strOrder == null) {
    msgText = "No order defined";
  } else {
    var msgText = "Sort order ::" + order2string();
  }
  
  display(object, msgText,_b);
}

function _order(_a,_b)
{
  return (sortArr[_a] - sortArr[_b]);
}

function display(object, _m,_b)
{
  // Set skin position
  y = findTopObj(object);
  x = findLeftObj(object);
  sdisp.style.top= y + Yoffset + "px";
  sdisp.style.left= x + Xoffset + "px";

  var content ='<table border="0" cellpadding="2" cellspacing="0" '+'bgcolor="'+_b+'">';
      content+='<tr><td align="left">';
      content+=_m;
      content+="</td></tr></table>";

  if(oldBrowser) {
    alert(_m);
    return;
  } else {
    if(isNS4) {
      sdisp.obj.document.open();
      sdisp.obj.document.write(content);
      sdisp.obj.document.close();
      sdisp.style.visibility="visible";
    } else {

      sdisp.obj.innerHTML=content;
      sdisp.style.visibility="visible";
    }
  }
}
// grid column order functions -- END --
//#######################################

// ######################################################
// generic submit and other control functions -- START --
function doAction(_action)
{
  document.RecordSet.doAction.value = _action;
  document.RecordSet.submit();
}

function submitHelp(_action)
{
  var oldAction = document.RecordSet.action;//save old action 
  document.RecordSet.action=_action;        //target cgi
  document.RecordSet.target="Help Screen";  //target window
  document.RecordSet.submit();              //force submit
  document.RecordSet.target=null;           //remove target window
  document.RecordSet.action = oldAction;    //reset action in form
  return false;
}

function launchMoviePlayer(name)
{
  document.RecordSet.doAction.value = name;
  document.RecordSet.target="movieplayer";  //target window
  document.RecordSet.submit();              //force submit
  document.RecordSet.target=null;           //remove target window
  return false;
}
// Checks if any data is being selected
function validateData()
{
  if (document.RecordSet.data == null) {
     alert ("Empty Search Results");
     return false;
  }

  var maxSize=document.RecordSet.data.length;
  if (maxSize == null) {
    if (document.RecordSet.data.checked == true) {
      return true;
    }
  }

  for (i=0; i<maxSize && document.RecordSet.data[i] != null ; i++) 
    {
      if (document.RecordSet.data[i].checked == true)
  return true;
    }
  alert ("At least one row must be selected");
  return false;
      
}

function changeLocation(_LOC)
{
   location=_LOC;
}

function popThumb(_URL)
{
   popup=window.open(_URL, "new_window", 'toolbar=no,location=no,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width=800,height=600');
}

function popWin(_URL)
{
   popwin=window.open(_URL, "new_window", 'toolbar=yes,location=yes,directories=no,status=no,scrollbars=yes,resizable=yes,copyhistory=no,width=800,height=600');
}

// generic submit and other control functions -- END --
// #####################################################


// ####################################
// cart specific functions -- START --

function browseAll()
{
  // the hidden submit field acts as function trigger
  document.RecordSet.sessionID.value = "all";
  document.RecordSet.doAction.value = "redraw";
  document.RecordSet.submit();
}

function browseOne()
{
  // the hidden submit field acts as function trigger
  document.RecordSet.sessionID.value = "";
  document.RecordSet.doAction.value = "redraw";
  document.RecordSet.submit();
}

function validateAddress()
{
//  return true;
  if (document.RecordSet.elements["email"].value.length>0)
  {
    return true;
  }
  else
  {
    alert("Please specify an e-mail address");
    return false; 
  }
}

function validateDataRequest()
{
  if (eStack >= 0) {
    return validateAddress();
  }
  return true;
}

function display_cartid()
{
   cartid_widget = new getObj('cart_display');
   if (cartid_widget.obj
       && document.RecordSet.elements["sc_id"]
       && document.RecordSet.elements["sc_id"].value.length > 0 ) {

       sc_id = document.RecordSet.elements["sc_id"].value;
       cartid_widget.obj.innerHTML="<b>Cart ID:<i>" +sc_id +"</i></b>"; 
   }
}  
// cart specific functions -- END --
// ###################################



//###########################################
// Check data boxes functionality -- START --
// checks/unchecks all pages
function checkAllPages(value)
{

  if (value) {
      document.RecordSet.checkallpages.value="all";
  } else {
      document.RecordSet.checkallpages.value="none";
  }
  checkAll(value);

  return false;
}

// checks all the data boxes
function checkAll(value)
{

  var i=0;
  if ( document.RecordSet.data[0] != null ) {
    while (document.RecordSet.data[i] != null)
      {
        document.RecordSet.data[i].checked = value;
        i++;
      }
  } else if (document.RecordSet.data != null )  {
    document.RecordSet.data.checked = value;
  }
  return false;
}

function findDataElement(element)
{
  var i=0;
  while (document.RecordSet.data[i] != null) {
    if (document.RecordSet.data[i] == element)
      return i;
    i++;
  }
}

function doCheck(which)
{

  // See if clickOption "above" is checked
  if (document.RecordSet.clickOption[0].checked==true) {
      //find current element position
      var pos=findDataElement(which);
      //See if we are checking or unchecking
      for (var i=pos-1; i>=0 && document.RecordSet.data[i] != null; i--) {
        document.RecordSet.data[i].checked = which.checked;
      }
  }
  // See if clickOption "below" is checked
  else if (document.RecordSet.clickOption[1].checked==true) {
      //find current element position
      var pos=findDataElement(which);
      
      var maxSize=document.RecordSet.data.length;
      for (i=pos+1; i<maxSize && document.RecordSet.data[i] != null ; i++) {
        document.RecordSet.data[i].checked = which.checked;
      }
  }
}
// Check data boxes functionality -- END --
//###########################################


//######################################
// window popup functionality -- START --
// sets the initial popup status for
// the popups in the left menu

var maxSnapObj = new Array();

// This bit although commented out, still exists but embedded in the HTML code
// so whenever we drop a showTocToggle a maxSnapObj["whatever"] will preceed it
// E.g.     <script type="text/javascript">
//            //<![CDATA[
//              maxSnapObj["summaryterms"]       = false;
//              showTocToggle("summaryterms", "hide","show")
//            //]]>
//          </script>
// **
// A value of false means window is collapsed
// oppossite for true ...
//maxSnapObj["status"]            = false;   //status information window
//maxSnapObj["columnsmenu"]       = false;   //add/remove columns menu
//maxSnapObj["rowsreturned"]      = false;   //rows returned info window
//maxSnapObj["summaryterms"]      = false;   //rows returned info window
//maxSnapObj["queryoptions"]      = true;    //rows returned info window

function minMaxInit() {
  for ( oName in maxSnapObj ) {
	  if (maxSnapObj[oName]) {
      show(oName);
      show('hidelink' + oName);
	    hide('showlink' + oName);
    } else {
      hide(oName);
      show('showlink' + oName);
      hide('hidelink' + oName);
    }
  }
}

function minMaxSnapObj(oName) {
	if (maxSnapObj[oName]) {
      hide(oName);
      hide('hidelink' + oName);
	  	show('showlink' + oName);
   }
 	else {
      show(oName);
      hide('showlink' + oName);
      show('hidelink' + oName);
  }

	minMaxObj(oName);
}

function showTocToggle(oName,show,hide) {
  var _show = hide;
  var _hide = show;
	if(document.getElementById) {
		document.writeln('<a class="snapLink" href="javascript:minMaxSnapObj(\'' + oName + '\');" >' + '<span id="showlink' + oName + '" class="snapLink" style="display:none;" >' + '[' + _show + ']' + '</span>' + '<span id="hidelink' + oName + '" class="snapLink" >' + '[' + _hide + ']' + '</span>' + '</a>');
	}
}
function toggleSearchParams(toc1,toc2) {
  var _show = toc2;
  var _hide = toc1;
    oName="searchparams";
		document.writeln('<a class="snapLink" href="javascript:minMaxSnapObj(\'' + oName + '\');" >' + '<span id="showlink' + oName + '" style="display:none;" ><span>Show Search Params ::&nbsp;</span><span class="snapLink">' + '[' + _show + ']' + '</span></span>' + '<span id="hidelink' + oName + '" class="snapLink" >' + '[' + _hide + ']' + '</span>' + '</a>');
}
//keeps track of window state
function minMaxObj(oName) {
  maxSnapObj[oName] = (maxSnapObj[oName]) ? false : true;
}

// function that governs the display of the email address text field
// for the cart data request screen
function checkTransfer(value) {
//debug ("eStack before: " + eStack);
  eStack =  value * eFlag;
//debug ("eStack after : " + eStack);
  if ( eStack >= 0 ) {
//debug ("eStack show");
     show("emailaddress");
  } else if ( eStack < 0 ){
//debug ("eStack hide");
     hide("emailaddress");
  }
}
// window popup functionality -- END --
// ####################################


//#########################################
// position/dimension functions --START -- 
// find object dimensions and positions
// it's supposed to work across browsers

function findTop(objectID)
{
  var o = new getObj(objectID);
  return findTopObj(o);
}

function findLeft(objectID)
{
  var o = new getObj(objectID);
  return findLeftObj(o);
}

function findLeftObj(obj)
{
	var curleft = 0;
  var lobj = null;
  // so I can pass any object
  // a DOM object or a self created object through getObj()
  if (obj.obj) { lobj = obj.obj }
  else { lobj=obj }

	if (lobj.offsetParent)
	{
    curleft += lobj.offsetLeft;
    var pObj = lobj.offsetParent;
		while (pObj)
		{
			curleft += pObj.offsetLeft
			pObj = pObj.offsetParent;
		}
	}
	else if (lobj.x)
		curleft += lobj.x;
	return curleft;
}

function findTopObj(obj)
{
	var curtop = 0;
  var lobj = null;
  // so I can pass any object
  // a DOM object or a self created object through getObj()
  if (obj.obj) { lobj = obj.obj }
  else { lobj=obj }

	if (lobj.offsetParent)
	{
    curtop = lobj.offsetTop;
    var pObj = lobj.offsetParent;
		while (pObj)
		{
			curtop += pObj.offsetTop
			pObj = pObj.offsetParent;
		}
	}
	else if (lobj.y)
		curtop += lobj.y;
	return curtop;
}


function findScrollTop() {
  //check if it is NS and use pageYOffset instead
  // for large results the scrollTop breaks in NS
  if ( isNS ) {
    if (window.pageYOffset)
      return window.pageYOffset;
  } else {
    if (document.body.scrollTop)
     return document.body.scrollTop;
  }
}

// position/dimension functions -- END -- 
//########################################


//#############################
// DEBUG FUNCTIONS -- START --
//#############################
// debug function
// opens a new window
// It might create some security issues
// particularly if your browser 
// don't allow popups
function debug(msg)
{
// return true;
  if((_console==null) || (_console.closed))
    {
      _console = window.open("","console","width=600,height=300,resizable");
      _console.document.open("text/plain");
    }

  _console.focus();
  _console.document.writeln(msg + "<br />");
  
  return true;
}

function objectElements (object) {
  for ( name in object ) {
     debug("object elem:"+name);
  }
}

function recordSetObjs () {
  for ( name in document.RecordSet ) {
     debug("RecordSet elem:"+name);
  }
}

function daytest () {
      var dToday = new Date();
      alert(dToday);
      dToday.setTime(dToday.getTime()+(7*24*60*60*1000)); // 1 week 
      alert(dToday);
}

// Timer Debug
var timeStack= new Array();
function Timer() {
  this.start = 0; 
  this.end   = 0;
}
function startTimer(name) {
  timeStack[name]=new Timer(name);
  timeStack[name].start = new Date();
}
function endTimer(name) {
  timeStack[name].end = new Date();
}

function showTime (tName) {
  debug("interval " + tName + " :" + (timeStack[tName].end.getTime() - timeStack[tName].start.getTime()))
}

function showTimeAll () {
  var tbuffer=""
  for ( tName in timeStack ) {
    tbuffer += "interval " + tName + " :" + (timeStack[tName].end.getTime() - timeStack[tName].start.getTime()) + "<br />";
  }
//  debug(tbuffer);
}

// DEBUG FUNCTIONS -- END --
//#############################
