var exportWindow; // used by openExportWindow function

// type checking functions

function checkValue(field, property, type, required) {

    // there IS a value
	if (field.value!="") {
	    if(required) {
	      document.images[property + "required"].src="images/astGray.gif";
	    } else {
		  document.images[property + "required"].src="images/clearpixel.gif";
		}
	} else {
		if (required) {
		  document.images[property + "required"].src="images/ast.gif";
		}
	}
}

/**
 *  Get's an element by Id scoped to the parent
 *  indicated by the parent parameter.
 *  Not nearly as efficient as document.getElementById()
 */
function getScopedElementById( parent, id )
{
   if ( parent.id == id )
      return parent;

   var children = parent.childNodes;
   for( var i = 0 ; i < (children ? children.length : 0) ; i++ )
   {
      var elem = getScopedElementById(children[i],id);
      if ( elem != null )
         return elem;
   }
   return null;
}

function borderTables( parent )
{
   if ( parent.tagName == "TABLE" )
      parent.style.border = "1px solid red";

   var children = parent.childNodes;
   for( var i = 0 ; i < (children ? children.length : 0) ; i++ )
      borderTables(children[i]);
}


// Return true if value is an e-mail address
function isEmail(value) {
	invalidChars = " /:,;";
	if (value=="") return false;

	for (i=0; i<invalidChars.length;i++) {
	   badChar = invalidChars.charAt(i);
	   if (value.indexOf(badChar,0) != -1) return false;
	}

	atPos = value.indexOf("@", 1);
	if (atPos == -1) return false;
	if (value.indexOf("@", atPos + 1) != -1) return false;

	periodPos = value.indexOf(".", atPos);
	if (periodPos == -1) return false;

	if (periodPos+3 > value.length) return false;

	return true;
}



// Return true if value is a number
function isNumber(value) {
    // This is commented because when we passs 0 it is considered same as ""
	//if (value=="") return false;

	var d = parseInt(value);
	if (!isNaN(d)) return true; else return false;

}

// return true if value is a date
// ie in the format XX/YY/ZZ where XX YY and ZZ are numbers
function isDate(value) {
	if (value=="") return false;

	var pos = value.indexOf("/");
	if (pos == -1) return false;
	var d = parseInt(value.substring(0,pos));
	value = value.substring(pos+1, 999);
	pos = value.indexOf("/");
	if (pos==-1) return false;
	var m = parseInt(value.substring(0,pos));
	value = value.substring(pos+1, 999);
	var y = parseInt(value);
	if (isNaN(d)) return false;
	if (isNaN(m)) return false;
	if (isNaN(y)) return false;

	var type=navigator.appName;
	if (type=="Netscape") var lang = navigator.language;
	else var lang = navigator.userLanguage;
	lang = lang.substr(0,2);

	if (lang == "fr") var date = new Date(y, m-1, d);
	else var date = new Date(d, m-1, y);
	if (isNaN(date)) return false;
	return true;
 }

// menu functions

function initMenu(menu) {
	if (getMenuCookie(menu)=="hide") document.getElementById(menu).style.display="none";
}


function GetCookie (name) {
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;
  while (i < clen) {
    var j = i + alen;
    if (document.cookie.substring(i, j) == arg)
      return getCookieVal (j);
    i = document.cookie.indexOf(" ", i) + 1;
    if (i == 0) break;
  }
  return null;
}

function changeMenu(menu) {
if (document.getElementById(menu).style.display=="none") {
	document.getElementById(menu).style.display="";
	document.getElementById(menu+"b").style.display="none";
	setMenuCookie(menu,"show");
}
else {
	var width = document.getElementById(menu).offsetWidth;
	document.getElementById(menu).style.display="none";
	if (navigator.vendor == ("Netscape6") || navigator.product == ("Gecko"))
		document.getElementById(menu+"b").style.width = width;
	else
		document.getElementById(menu+"b").width = width;
	document.getElementById(menu+"b").style.display="";
	setMenuCookie(menu,"hide");
}
return false;
}

function setMenuCookie(name, state) {
	var cookie = name + "STRUTSMENU=" + escape(state);
	document.cookie = cookie;
}

function getMenuCookie(name) {
	var prefix = name + "STRUTSMENU=";
	var cookieStartIndex = document.cookie.indexOf(prefix);
	if (cookieStartIndex == -1) return "???";
	var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length);
	if (cookieEndIndex == -1) cookieEndIndex = document.cookie.length;
	return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

function openWindow(url, name, windowOptions)
{
   sessionCheckGuard( function() {
      if (windowOptions == null ||windowOptions== "")
        windowOptions= 'width=800,height=600,resizable=yes,scrollbars=yes,toolbar=yes';
      windowName = window.open(url, name, windowOptions);
      windowName.focus();
      if (!windowName.opener)
         windowName.opener = self;
    } );
}


function gotoPopupHandlerPage( currentPage, popupUrl, name, extraArgs )
{
   location.replace( "handlePopup.page" +
                             "?currentPage=" +  currentPage +
                             "&popup="       + popupUrl +
                             "&popupName="   + name +
                             "&extraArgs="   + escape(extraArgs) );
}

/**
 *  Sets the opacity of element with id to value n
 *  n is a value between 0 and 1.
 */
function setOpacity(id, n)
{
   setOpacityByObj( document.getElementById(id), n );
}
function setOpacityByObj(el, n)
{
   el.style.opacity = n;
   el.style.MozOpacity = n;
   el.style.filter = "Alpha(Opacity=" + Math.round(n * 100) + ")";
}

function getIFrameDocument( anIFrame )
{
   if (anIFrame.contentDocument)
      return anIFrame.contentDocument;        // For NS6
   else if (anIFrame.contentWindow)
       return anIFrame.contentWindow.document; // For IE5.5 and IE6
   else if (anIFrame.document)
      return anIFrame.document;               // For IE5
   else
      return null;
}

function toAbsolutePosition( anHTMLElement )
{
   var x = 0;
   var y = 0;
   var parent = anHTMLElement;
   while ( parent )
   {
      x += parent.offsetLeft;
      y += parent.offsetTop;      
      parent = parent.offsetParent;
   }
   if ( navigator.userAgent.indexOf("Mac") != -1 &&
        typeof document.body.leftMargin != "undefined" )
   {
      x += document.body.leftMargin;
      y += document.body.topMargin;
   }

   return { x:x, y:y };
}

function isPositionedElement(el) {
   if (el && el.style && ((el.style.position == "absolute" || el.style.position == "relative")
         || (el.style.overflow == "auto" || el.style.overflow == "scroll")
         || isDivHavingScrollbar(el))) {
      return true;
   }     
   return false;
}

function isDivHavingScrollbar(elem) {
   if (elem && elem.tagName == "DIV") {
      if (elem.clientHeight !=0 && elem.clientHeight < elem.scrollHeight)
         return true;      
   }
   return false;
}

function toPositionedElement(o) {
    var left = 0;
    var top = 0;
    var width = 0;
    var height = 0;
    var parentNode = null;
    var offsetParent = null;
    var fixBrowserQuirks = true;

    offsetParent = o.offsetParent;    
    var originalObject = o;
    var el = o;
    var positionedElementFound = false;
    while (el.parentNode!=null && !positionedElementFound) {
      el = el.parentNode;       
      if (isPositionedElement(el)) {
         positionedElementFound = true;
      }      
      if (el.offsetParent==null) {
      }
      else {
        var considerScroll = !positionedElementFound;

        if (fixBrowserQuirks && window.opera) {
          if (el==originalObject.parentNode || el.nodeName=="TR") {
            considerScroll = false;
          }
        }
        if (considerScroll) {
          if (el.scrollTop && el.scrollTop>0) {
            top -= el.scrollTop;
          }
          if (el.scrollLeft && el.scrollLeft>0) {
            left -= el.scrollLeft;
          }
        }
      }
      // If this node is also the offsetParent, add on the offsets and reset to the new offsetParent
      if (el == offsetParent) {
        left += o.offsetLeft;
        if (el.clientLeft && el.nodeName!="TABLE") {
          left += el.clientLeft;
        }
        top += o.offsetTop;
        if (el.clientTop && el.nodeName!="TABLE") {
          top += el.clientTop;
        }
        o = el;
        if (o.offsetParent==null) {
          if (o.offsetLeft) {
            left += o.offsetLeft;
          }
          if (o.offsetTop) {
            top += o.offsetTop;
          }
        }
        offsetParent = o.offsetParent;
      }
    }
    return {x:left, y:top};
}

function getElementsComputedStyle(el, sProp, sProp2)
{
   if ( arguments.length == 2 )
      sProp2 = sProp;

   if ( el.currentStyle )
      return el.currentStyle[sProp];
   else
      return document.defaultView.getComputedStyle(el, null).getPropertyValue(sProp2);
}


function findParent( anHTMLElement, aParentTagName )
{
   var parent = anHTMLElement;
   while ( parent )
   {
      parent = parent.offsetParent;
      if ( parent.tagName == aParentTagName )
         return parent;
   }
   return null;
}

function addEvent( elem, eventName, anObj, aMethod )
{
   if ( typeof document.implementation != "undefined" &&
      document.implementation.hasFeature("HTML",   "1.0") &&
      document.implementation.hasFeature("Events", "2.0") &&
      document.implementation.hasFeature("CSS",    "2.0") )
      elem.addEventListener( eventName, function (e) { anObj[aMethod](e); }, false);
   else
      elem.attachEvent( "on" + eventName, function() { anObj[aMethod](window.event); } );
}

function openSaveAsWindow(url, name)
{

   windowName = window.open(url, name, 'width=400,height=200');
   windowName.focus();
   if (!windowName.opener)
      windowName.opener = self;
}

// Clear a form so that default initial values are erased
function clearForm(button) {
   var form = findForm(button);
   var element;
   for (var i = 0; i < form.elements.length; i++)
   {
      element = form.elements[i];
      if (element.type == "text" || element.type == "password" || element.type == "textarea")
         element.value = '';
      else if (element.type.indexOf("select") != -1)
         element.selectedIndex = 0;
      else if (element.type == "checkbox" && element.checked)
         element.checked = false;
      else if (element.type == "radio" && element.checked == true)
         element.checked = false;
   }
}
function findForm( formElement )
{
   var parent = formElement.parentNode;
   while ( parent != null && parent.nodeName != "FORM" )
      parent = parent.parentNode;
   return parent;
}

function submitFormAction( formObject, anActionName )
{
   formObject.action = anActionName + ".do"
   formObject.submit();
}

function submitFormActionWithConfirm( formObject, anActionName, confirmMsg )
{
   formObject.action = anActionName;

   if(confirmMsg != null && confirmMsg.length > 0)
   {
      if(confirm(confirmMsg))
      {
         formObject.submit();
      }
   }
   else
   {
      formObject.submit();
   }
}

function fixElementSize( anElement )
{
   anElement.style.width = anElement.offsetWidth;
}

function openExportWindow( aURL )
{
      if( exportWindow == null)
      {
         exportWindow = window.open("");
         exportWindow.location.href = aURL;
      }
      else if(!exportWindow.closed)
      {
         exportWindow.focus();
         exportWindow.location.href = aURL;
      }
      else
      {
         exportWindow = window.open("");
         exportWindow.location.href = aURL;
      }
}

function makeEnterKeySubmitForm( aForm )
{
   var submitFunction = null;
   if ( arguments.length == 2 )
      submitFunction = arguments[1];

   var genericEventModel = false;
   if ( typeof document.implementation != "undefined" &&
			document.implementation.hasFeature("HTML",   "1.0") &&
			document.implementation.hasFeature("Events", "2.0") &&
			document.implementation.hasFeature("CSS",    "2.0") )
      genericEventModel = true;

   var formElements = aForm.elements;
   for ( var i = 0 ; i < formElements.length ; i++ )
   {
      var formElement = formElements[i];
      if ( formElement.tagName == "INPUT" && formElement.type == "text" )
      {
         if ( genericEventModel )
            formElement.addEventListener( "keydown", function(e) { performFormSubmitOnEnter(aForm, submitFunction); }, false );
         else
            formElement.attachEvent( "onkeydown", function() { performFormSubmitOnEnter(aForm, submitFunction); } );
      }
   }
}

/**
 *  If a submit method has been supplied, then use it, otherwise just
 *  call the forms submit method...
 *
 */
function performFormSubmitOnEnter(aForm, aSubmitMethod)
{
   var e = window.event;
   var enterKeyCode = 13;

   var src = e.target != null ? e.target : e.srcElement;
   if (e.keyCode == enterKeyCode)
   {
      if (aSubmitMethod != null)
         aSubmitMethod();
      else
         aForm.submit();
   }
}

  /**
  * Adds an event to the target object and calls function eventListener. eventCapture
  *can be false. event can be any event like click OR blur or focus...etc
  *
  */
  function addEvent(targetObject, event, eventListener, eventCapture)
  {
      if(targetObject.addEventListener)
      {
            targetObject.addEventListener(event, eventListener, eventCapture);
      }
      else if(targetObject.attachEvent)
      {
            targetObject.attachEvent('on' + event, eventListener);
      }
   }



function checkMaxLength(field, maxLength)
{
   if (field.value.length > maxLength)
      field.value = field.value.substring(0,maxLength);
}



