// (C) 2000-2009
// Written by Roberto Cisternino
// Compliance Level:	W3C DOM Standard Browsers
//						Internet Explorer non standard (layers)
//						Netscape Navigator non standard (layers)
//						Opera (base compliance)
// Version 3.1
var agent=navigator.userAgent.toLowerCase();
var ie4=document.all? true : false;
// Detect IE5+ and Firefox (including NS6+) [Modern Browser with DOM support]
var W3C=document.getElementById && !isEmpty(document.getElementById);
// Detect Firefox (and NS6+) exclusively
var FFox = W3C && !document.all;
var ns4=document.layers? true : false;
var MOZ5 = ((agent.indexOf('mozilla')==0) && (agent.charAt(8) >= 5) && (agent.indexOf('compatible')<0));
// Detect Opera 6+ exclusively
var OP = agent.indexOf('opera')>=0;	// window.opera && window.print
var mLeft = 0;	// Mouse X
var mTop = 0;	// Mouse Y
var contentType = 'HTM';
var keyCode;		// Key pressed
var ctxBack;		// Context Back URL
// Inputs
var inputs = document.getElementsByTagName('input');
for (var i=0;i<inputs.length;i++) {
	addEvent(inputs[i], 'keydown', CRasTAB());
}
function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}
function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}
function noBubble(e)
{
	if (e && e.stopPropagation)
		e.stopPropagation();
	else
		window.event.cancelBubble = true;
}
function CRasTAB(nextInput, e) {
	var sysKeys=new Array(8,9,16,17,18,20,27,33,34,35,36,37,38,39,40,45,46,92,112,113,114,115,116,117,118,119,120,121,122,123,144);
	keyCode = (ns4 || MOZ5) ? ((e.keyCode) ? e.keyCode : e.which) : window.event.keyCode;
	var tgt = (ns4 || MOZ5) ? e.target : window.event.srcElement;
	var isFull = (tgt.type=='text' && tgt.maxLength && tgt.value.length==tgt.maxLength && ArraySearch(sysKeys, keyCode)==-1);

	// Enter is pressed and/or select-one (combobox) is empty or text input is full
	if ((keyCode==13 && !(tgt.type=='select-one' && tgt.value=='') && tgt.type!='submit') || isFull==true) {
		if (isFull==true && nextInput) {
			nextInput.select();
		} else {
			if (ns4 || MOZ5)
				e.which = 9;
			else
				window.event.keyCode = 9;
		}
	} 
	return true;
}
// Keyboard Edit control
var keybYN = new keybEdit('yn','Valid values are \'Y\' or \'N\'.');
var keybNumeric = new keybEdit('-0123456789','Numeric input only.');
var keybAlpha = new keybEdit('abcdefghijklmnopqrstuvwxyz ','Alpha input only.');
var keybAlphaNumeric = new keybEdit('abcdefghijklmnopqrstuvwxyz-0123456789 ','Alpha-numeric input only.');
var keybDecimal = new keybEdit('-0123456789.','Decimal input only.');
var keybDate =  new keybEdit('0123456789/','Date input only');
var keybYNNM = new keybEdit('yn');
var keybNumericNM = new keybEdit('-0123456789');
var keybAlphaNM = new keybEdit('abcdefghijklmnopqrstuvwxyz ');
var keybAlphaNumericNM = new keybEdit('abcdefghijklmnopqrstuvwxyz-0123456789 ');
var keybDecimalNM = new keybEdit('-0123456789.');
var keybDateNM = new keybEdit('0123456789/');
// Common Regex strings
var nameRegex = /^[A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]+$/;
var emailRegex = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
var isoDateRegex = /^\d{4}-[0-1]\d-[0-3]\d$/;
function testRegex(field, msg, rule) {
	var reg = new RegExp(rule);
	if (reg.test(field.value))
		return true;
		
	window.alert(msg);
	field.focus();
	return false;
}
function keybEdit(strValid, strMsg) {
	/*	Function:		keybEdit
		Creation Date:	October 11, 2001
		Programmer:		Edmond Woychowsky
		Purpose:		The purpose of this function is to be a constructor for
						the keybEdit object.  keybEdit objects are used by the
						function editKeyBoard to determine which keystrokes are
						valid for form objects.  In addition, if an error occurs,
						they provide the error message.
						
						Please note that the strValid is converted to both
						upper and lower case by this constructor.  Also, that
						the error message is prefixed with 'Error:'.
						
						The properties for this object are the following:
							valid	=	Valid input characters
							message	=	Error message
							
						The methods for this object are the following:
							getValid()	=	Returns a string containing valid
											characters.
							getMessage()=	Returns a string containing the
											error message.

		Update Date:	Programmer:			Description:
	*/

	//	Variables
	var reWork = new RegExp('[a-z]','gi');		//	Regular expression

	//	Properties
	if(reWork.test(strValid))
		this.valid = strValid.toLowerCase() + strValid.toUpperCase();
	else
		this.valid = strValid;

	if(!strMsg || isEmpty(strMsg))
		this.message = '';
	else
		this.message = strMsg;

	//	Methods
	this.getValid = keybEditGetValid;
	this.getMessage = keybEditGetMessage;
	
	function keybEditGetValid() {
	/*	Function:		keybEdit
		Creation Date:	October 11, 2001
		Programmer:		Edmond Woychowsky
		Purpose:		The purpose of this function act as the getValid method
						for the keybEdit object.  Please note that most of the
						following logic is for handling numeric keypad input.

		Update Date:		Programmer:			Description:
	*/

		return this.valid.toString();
	}
	
	function keybEditGetMessage() {
	/*	Function:		keybEdit
		Creation Date:	October 11, 2001
		Programmer:		Edmond Woychowsky
		Purpose:		The purpose of this function act as the getMessage method
						for the keybEdit object.

		Update Date:	Programmer:			Description:
	*/
	
		return this.message;
	}
}

void function editKeyBoard(objForm, objKeyb) {
	/*	Function:		editKeyBoard
		Creation Date:	October 11, 2001
		Programmer:		Edmond Woychowsky
		Purpose:		The purpose of this function is to edit edit keyboard input
						to determine if the keystrokes are valid.
	
		Update Date:		Programmer:			Description:
	*/
	keyCode = (ns4 || MOZ5) ? e.which : window.event.keyCode ;

	strWork = objKeyb.getValid();
	strMsg = '';							// Error message
	blnValidChar = false;					// Valid character flag

	if (!keyCode) {
		return;
	}
	
	// Part 1: Validate input
	if(!blnValidChar)
		for(i=0;i < strWork.length;i++) {
			if(keyCode == strWork.charCodeAt(i)) {
				blnValidChar = true;

				break;
			}
		}

	// Part 2: Build error message
	if(!blnValidChar) {
		if(objKeyb.getMessage().toString().length != 0)
			alert('Error: ' + objKeyb.getMessage());

		if (!ns4 && !MOZ5)
			window.event.returnValue = false;		// Clear invalid character

		objForm.focus();						// Set focus
	}
}
function validateMandatoryInput(field, msg) {
	if (!field || isEmpty(field)) {
		alert('Parameter 1 is undefined !');
		return true;	// non-blocking check
	}
	if (!field.disabled && field.type != 'hidden' && (field.type=='select-one' ? field.selectedIndex <= 0 : field.value.length < 1 || field.value == null)) {
		window.alert(msg);
		if (field.type != 'hidden')
			field.focus();
		return false;
	}
	return true;
}
function _SetMouseCoordinate(e) {
	if (!e) e = window.event; // works on IE, but not NS (we rely on NS passing us the event)

    if (e.pageX || e.pageY)
    { // this doesn't work on IE6!! (works on FF,Moz,Opera7)
      mLeft = e.pageX;
      mTop = e.pageY;
    }
    else if (e.clientX || e.clientY)
    { // works on IE6,FF,Moz,Opera7
      mLeft = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      mTop = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
    }	
}
function enableMouseCoordinates(enable) {
	if (enable == 1) {
		addEvent(document, 'mousemove', _SetMouseCoordinate);
//		if (ns4)
//			document.captureEvents(Event.MOUSEMOVE);

//		document.onmousemove = _SetMouseCoordinate;
	} else {
		removeEvent(document, 'mousemove', _SetMouseCoordinate);
//		if (ns4)
//			document.releaseEvents(Event.MOUSEMOVE);

//		document.onmousemove = null;
	}
}
function _GetWindowWidth(w) {
	var theWidth = 0;

	if (w.innerWidth)
	{
		theWidth = w.innerWidth
	}
	else if (w.document.documentElement && w.document.documentElement.clientWidth)
	{
		theWidth = w.document.documentElement.clientWidth
	}
	else if (w.document.body)
	{
		theWidth = w.document.body.clientWidth
	}
	return theWidth;
}

function _GetWindowHeight(w) {
	var theHeight = 0;

	if (w.innerHeight)
	{
		theHeight = w.innerHeight
	}
	else if (w.document.documentElement && w.document.documentElement.clientHeight)
	{
		theHeight = w.document.documentElement.clientHeight
	}
	else if (w.document.body)
	{
		theHeight = w.document.body.clientHeight
	}
	return theHeight;
}

function _GetHorzScrollOffset(w) {
	var pos = 0;
	if (w.pageXOffset)
	{
		  pos = w.pageXOffset
	}
	else if (w.document.documentElement && w.document.documentElement.scrollLeft)
	{
		pos = w.document.documentElement.scrollLeft
	}
	else if (w.document.body)
	{
		  pos = w.document.body.scrollLeft
	}
	return pos;
}

function _GetVertScrollOffset(w) {
	var pos = 0;

	if (w.pageYOffset)
	{
		  pos = w.pageYOffset
	}
	else if (w.document.documentElement && w.document.documentElement.scrollTop)
	{
		pos = w.document.documentElement.scrollTop
	}
	else if (w.document.body)
	{
		  pos = w.document.body.scrollTop
	}
	return pos;
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function _PreloadImages() {
  var d=document; if(d.images){ if(!d._p) d._p=new Array();
    var i,j=d._p.length,a=_PreloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d._p[j]=new Image; d._p[j++].src=a[i];}}
}

function _ShowObj(lId)
{
  var ob;ob=new Array;
  if (W3C)
  {
    ob[lId] = document.getElementById(lId).style;	//getAttribute('style');

    if (ob[lId]) {
        ob[lId].visibility = "visible";
        ob[lId].display = "";
    }
  } else if (ns4)
  {
    w_str = "document." + lId;ob[lId] = eval(w_str);
    if (!ob[lId]) ob[lId] = _FindObj(document, lId);
    if (ob[lId]) {
    	ob[lId].visibility = "show";
        ob[lId].display = "";
    }
  } else if (ie4)
  {
    w_str = "document.all.item(\"" + lId + "\").style";
    ob[lId] = eval(w_str);
    ob[lId].visibility = "visible";
    ob[lId].display = "";
  }
}

function _HideObj(lId)
{
  var ob;ob=new Array;
  if (W3C)
  {
    ob[lId] = document.getElementById(lId).style;	//getAttribute('style');

    if (ob[lId]) {
        ob[lId].visibility = "hidden";
        ob[lId].display = "none";
    }
  } else if (ns4)
  {
    w_str = "document." + lId;ob[lId] = eval(w_str);
    if (!ob[lId]) ob[lId] = _FindObj(document, lId);
    if (ob[lId]) {
       ob[lId].visibility = "hide";
       ob[lId].display = "none";
    }
  } else if (ie4)
  {
    w_str = "document.all.item(\"" + lId + "\").style";ob[lId] = eval(w_str);
    ob[lId].visibility = "hidden";
    ob[lId].display = "none";
  }
}

// Tested with IE 7 and Firefox 2.0.0.2
function _isVisible(lId)
{
  var ob;ob=new Array;
  if (W3C)
  {

    ob[lId] = document.getElementById(lId).style;	//getAttribute('style');

    if (ob[lId] && (ob[lId].visibility == "visible" && ob[lId].display == "")) {
    	return 1;
    }
  } else if (ns4)
  {
    w_str = "document." + lId;ob[lId] = eval(w_str);
    if (!ob[lId]) ob[lId] = _FindObj(document, lId);
    if (ob[lId] && (ob[lId].visibility == "show" && ob[lId].display == "")) {
    	return 1;
    }
  } else if (ie4)
  {
    w_str = "document.all.item(\"" + lId + "\").style";ob[lId] = eval(w_str);
    
    if (ob[lId].visibility == "visible" && ob[lId].display == "") {
    	return 1;
    }
  }
  return 0;
}
function _GetObject(lId, targetframe)
{
  var ob;ob=new Array;
  if (W3C) {
    ob[lId] = eval(targetframe).document.getElementById(lId);
  } else if (ns4) {
    w_str = targetframe + ".document." + lId;
    ob[lId] = eval(w_str);
    if (!ob[lId]) ob[lId] = _FindObj(eval(targetframe + ".document"), lId);
  } else if (ie4) {
    w_str = targetframe + ".document.all.item(\"" + lId + "\")";
    ob[lId] = eval(w_str);
  }
  return ob[lId];
}
function setClassName(lId, cName) {
    _GetObject(lId, 'self').className = cName;
}
function _ShowObjAt(lId, targetframe, atX, atY)
{
	var ob;ob=new Array;

	try {
		if (W3C) {
			ob[lId] = eval(targetframe).document.getElementById(lId).style;	//getAttribute('style');

			if (ob[lId]) {
				ob[lId].left = atX+"px";
				ob[lId].top = atY+"px";
				ob[lId].visibility = "visible";
				ob[lId].display = "";
			}
		} else if (ns4) {
			w_str = targetframe + ".document." + lId;
		    ob[lId] = eval(w_str);
		    if (!ob[lId]) ob[lId] = _FindObj(document, lId);
		    if (ob[lId]) {
    		    ob[lId].top = atY;
		        ob[lId].left = atX;
		        ob[lId].visibility = "show";
        		ob[lId].display = "";
		    }
		} else if (ie4) {
		    w_str = targetframe + ".document.all.item(\"" + lId + "\").style";

		    ob[lId] = eval(w_str);
		    ob[lId].top = atY;
		    ob[lId].left = atX;
		    ob[lId].visibility = "visible";
		    ob[lId].display = "";
		}
	} catch(err) {
		// ignore
	}
}
function _ShowObjAtCursor(lId, targetframe, shiftX, shiftY)
{
  var ob;ob=new Array;
  var w_width;w_width = _GetWindowWidth(eval(targetframe));
  var ob_width;
  var delta;

  if (W3C)
  {
    ob[lId] = eval(targetframe).document.getElementById(lId).style; //getAttribute('style');

    if (ob[lId]) {
        ob_width = _GetObjWidth(ob[lId]);
	delta = ((mLeft + ob_width > w_width) ? (mLeft + ob_width - w_width) : 0);
        ob[lId].left = mLeft - delta + shiftX+"px";
        ob[lId].top = mTop + shiftY+"px";
        ob[lId].visibility = "visible";
        ob[lId].display = "";
    }
  } else if (ns4)
  {
    w_str = targetframe + ".document." + lId;
    ob[lId] = eval(w_str);

    if (!ob[lId]) ob[lId] = _FindObj(document, lId);
    if (ob[lId]) {
        ob_width = _GetObjWidth(ob[lId]);
	delta = ((mLeft + ob_width > w_width) ? (mLeft + ob_width - w_width) : 0);
        ob[lId].left = mLeft - delta + shiftX;
        ob[lId].top = mTop + shiftY;
        ob[lId].visibility = "show";
        ob[lId].display = "";
    }
  } else if (ie4)
  {
    w_str = targetframe + ".document.all.item(\"" + lId + "\").style";

    ob[lId] = eval(w_str);
    if (ob[lId]) {
        ob_width = _GetObjWidth(ob[lId]);
	delta = ((mLeft + ob_width > w_width) ? (mLeft + ob_width - w_width) : 0);
        ob[lId].left = mLeft - delta + shiftX;
        ob[lId].top = mTop + shiftY;
        ob[lId].visibility = "visible";
        ob[lId].display = "";
    }
  }

}
function _FindObj(doc, lId)
{
  for (var i=0; i < doc.layers.length; i++)
  {
    var w_str = "doc.layers[i].document." + lId;
    var obj;obj=new Array;
    obj[lId] = eval(w_str);
    if (!obj[lId]) obj[lId] = _FindObj(doc.layers[i], lId);
    if (obj[lId]) return obj[lId];
  }
  return null;
}

function _GetLeft(daObj){
        var returnVal;
        // set left if auto-calculated (left=0) or if not specified in-line/with style sheet
        if(W3C){
            if(!daObj.style.left){
				if (daObj.currentStyle)
					daObj.style.left = daObj.currentStyle['left']+"px";
				else {
					var w = document.defaultView;
					if(w == null)
						w = window;
					daObj.style.left = w.getComputedStyle(daObj, '').getPropertyValue('left')+"px";
            }
            }
            returnVal = parseInt(daObj.style.left);
        }
        else if(ns4){ returnVal = daObj.left; } // daObj.pageY if undef
        else{ returnVal = daObj.style.pixelLeft; } // daObj.offsetLeft if undef
        return returnVal;
}

function _SetLeft(daObj, newLeft){
        if (W3C) { daObj.style.left = newLeft + 'px'; }
        else if (ns4) { daObj.left = newLeft; }
        else { daObj.style.pixelLeft = newLeft; }
}

function _GetTop(daObj){
        var returnVal;
        if(W3C){
            if (!daObj.style.top) {
				if (daObj.currentStyle)
					daObj.style.top = daObj.currentStyle['top'];
				else {
					var w = document.defaultView;
					if (w == null)
						w = window;
					daObj.style.top = w.getComputedStyle(daObj, '').getPropertyValue('top');
				}
            }
            returnVal = parseInt(daObj.style.top);
        }
        else if(ns4){ returnVal = daObj.top; } // daObj.pageX if undef
        else{ returnVal = daObj.style.pixelTop; } // daObj.offsetTop if undef
        return returnVal;
}

function _SetTop(daObj, newTop){
        if(W3C){ daObj.style.top = newTop + 'px'; }
        else if(ns4){ daObj.top = newTop; }
        else{ daObj.style.pixelTop = newTop; }
}

function _GetObjHeight(daObj){
	var returnVal;

	if(W3C) {
		if(!daObj.height) {
			if (daObj.currentStyle)
				daObj.height = daObj.currentStyle['height'];
			else {
				var w = document.defaultView;
				if(w == null)
					w = window;
				daObj.height = w.getComputedStyle(daObj, '').getPropertyValue('height');
			}
		}
		returnVal = parseInt(daObj.height);
    } else if (ie4) {
		if (daObj.pixelHeight) {
			returnVal = daObj.pixelHeight;
		} else {
			if (daObj.clientHeight) {
				returnVal = daObj.clientHeight;
			} else {
				returnVal = daObj.offsetHeight;
			}
		}
    } else {
		returnVal = daObj.clip.height;
	}

    return returnVal;
}

function _GetObjWidth(daObj) {
        var returnVal;

        if (W3C) {
                if (daObj.width){                   
                    daObj.width = getStyleProp(daObj, 'width');
                }
                returnVal = parseInt(daObj.width);
        } else if (ie4) {
			if (daObj.pixelWidth) {
				returnVal = daObj.pixelWidth;
			} else {
				if (daObj.clientWidth) {
					returnVal = daObj.clientWidth;
				} else {
					returnVal = daObj.offsetWidth;
				}
			}
        } else {
		returnVal = daObj.clip.width;
	}

    return returnVal;
}

function _GetHTML(id_element) {
	if (W3C) {
		if (document.getElementById(id_element) == null)
			return '';
		return document.getElementById(id_element).innerHTML;
	} else if (ie4) {
		if (document.all[id_element] == null)
			return '';
		return document.all[id_element].innerHTML;
	} else {
		return '';
	}
}
function contextBack() {
	if (ctxBack) {
		self.location.href=ctxBack;
	} else {
		history.go(-1);
	}
}
//*****************************************************************************
// Do not remove this notice.
//
// Copyright 2001 by Mike Hall.
// See http://www.brainjar.com for terms of use.
//*****************************************************************************

// Determine browser and version.

function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();

// Global object to hold drag information.

var dragObj = new Object();
dragObj.zIndex = 0;

function dragStart(e, id) {
  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = e.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = e.clientX + window.scrollX;
    y = e.clientY + window.scrollY;
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.

  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

		addEvent(document, 'mousemove', dragGo);
		addEvent(document, 'mouseup', dragStop);
		noBubble(e);
//  if (browser.isIE) {
//    document.attachEvent("onmousemove", dragGo);
//    document.attachEvent("onmouseup",   dragStop);
//    window.event.cancelBubble = true;
//    window.event.returnValue = false;
//  }
//  if (browser.isNS) {
//    document.addEventListener("mousemove", dragGo,   true);
//    document.addEventListener("mouseup",   dragStop, true);
//    event.preventDefault();
//  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function dragStop(event) {

  // Stop capturing mousemove and mouseup events.

  if (browser.isIE) {
    document.detachEvent("onmousemove", dragGo);
    document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
    document.removeEventListener("mousemove", dragGo,   true);
    document.removeEventListener("mouseup",   dragStop, true);
  }
}

function evalObj(id) {
  var obj;
  var _begin;
  var _end;
  if (browser.isNS) {
    _begin = "document.";
    _end = "";
  }
  if (browser.isIE) {
    _begin = "";
    _end = ".style";
  }
  return eval(_begin + id + _end);
}

function setIndex(event, id) {
  var ribbon = 'ABCDEF';
  var shift = 0;
  var x, y;
  var obj = new Object();

  // Reset zindex
  obj = document.getElementById(id);

  shift = - (id.charCodeAt(0) - "F".charCodeAt(0)) + 5;
  obj = document.getElementById("F");
  obj.style.zIndex = (shift > 5) ? 0 : 1;
  x = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  y = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  _ShowObjAt("F", 'self', x, y);

  shift = - (id.charCodeAt(0) - "E".charCodeAt(0)) + 5;
  obj = document.getElementById("E");
  obj.style.zIndex = (shift > 5) ? 0 : 1;
  x = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  y = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  _ShowObjAt("E", 'self', x, y);

  shift = - (id.charCodeAt(0) - "D".charCodeAt(0)) + 5;
  obj = document.getElementById("D");
  obj.style.zIndex = (shift > 5) ? 0 : 1;
  x = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  y = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  _ShowObjAt("D", 'self', x, y);

  shift = - (id.charCodeAt(0) - "C".charCodeAt(0)) + 5;
  obj = document.getElementById("C");
  obj.style.zIndex = (shift > 5) ? 0 : 1;
  x = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  y = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  _ShowObjAt("C", 'self', x, y);

  shift = - (id.charCodeAt(0) - "B".charCodeAt(0)) + 5;
  obj = document.getElementById("B");
  obj.style.zIndex = (shift > 5) ? 0 : 1;
  x = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  y = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  _ShowObjAt("B", 'self', x, y);

  shift = - (id.charCodeAt(0) - "A".charCodeAt(0)) + 5;
  obj = document.getElementById("A");
  obj.style.zIndex = (shift > 5) ? 0 : 1;
  x = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  y = 25 + (20 * (shift > 5 ? shift - 6 : shift));
  _ShowObjAt("A", 'self', x, y);

}

function getXMLHttpRequest() {
    var xmlReq = false;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        xmlReq = new XMLHttpRequest();

        if (xmlReq.overrideMimeType) {
            xmlReq.overrideMimeType('text/xml;charset=UTF-8');
        }
    } else if (window.ActiveXObject) { // IE
        try {
        	// 5.5 or previous
            xmlReq = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
            	// 5.5 or later
                xmlReq = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                xmlReq = false;
            }
        }
    } else if (window.createRequest) {	// IceBrowser
        try {
            xmlReq = window.createRequest();
        } catch (e) {
            xmlReq = false;
        }
    }

	if (!xmlReq) {
		alert("ERROR: Your browser do not support AJAX or Javascript technology is not fully enabled\nplease contact your technical support !");
	}
	return xmlReq;
}
function isEmpty(v) {
	return v == null || v == '' || v == 'null';
}
function _FillElement(id_element, content, addToTarget) {
	if (isEmpty(id_element))
		return;
	if (W3C) {
		if (document.getElementById(id_element) == null)
			return;
		if (addToTarget)
			document.getElementById(id_element).innerHTML += content;
		else
			document.getElementById(id_element).innerHTML = content;
	} else if (ie4) {
		if (document.all[id_element] == null)
			return;
		if (addToTarget)
			document.all[id_element].innerHTML += content;
		else
			document.all[id_element].innerHTML = content;
	} else if (ns4 && document.layers[id_element] != null) with (document.layers[id_element].document) {
		// addToTarget is not supported
		write(content);
		close();
	} else {
		return;
	}
	 _ShowObj(id_element);
}
function execXMLHttpAction(xmlReq, url, act, async, fn, postData) {
	if (xmlReq) {
        xmlReq.open(act, url, async);
        if (act == 'POST' && postData && !isEmpty(postData)) {
        	xmlReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlReq.setRequestHeader('Content-length', postData.length);
			xmlReq.setRequestHeader('Connection', 'close');
	    }
        xmlReq.onreadystatechange = fn;
        if (!postData || isEmpty(postData))
	        xmlReq.send(null);
		else
			xmlReq.send(postData);
        if (!async && window.XMLHttpRequest && fn && !isEmpty(fn)) // Mozilla, Safari,...
			fn();
    }
}
function checkURLAvailability(url) {
	return checkURLAvailability(url, null, null);
}
// The URL availability is tested using Ajax, however in case a browser is not ajax compliant this test will be always true.
function checkURLAvailability(url, redUrl, redFrame) {
    var xmlReq = getXMLHttpRequest();

	execXMLHttpAction(xmlReq, url, 'HEAD', false, function() {
		return checkURLCallback(xmlReq, url, redUrl, redFrame);
    });
    return (xmlReq && xmlReq.status==200 ? true : (xmlReq ? false : true));
}

function checkURLCallback(xmlReq, url, redUrl, redFrame) {
	if (xmlReq.readyState==4) {
		if (xmlReq.status==200) {
			return true;
	    } else if (xmlReq.status==404 || xmlReq.status==500) {
	    	if (redUrl)
		    	redFrame.document.location.href=redUrl;
			return false;
	    } else {
	    	alert('Unable to reach ' + url + '\n\n' + xmlReq.statusText + ' (' + xmlReq.status + ')');
	    	if (redUrl)
				redFrame.document.location.href=redUrl;
			return false;
		}
    }
    return false;
}
// Send asynchronously a form query using AJAX
function postFormData(url, target, formData, linkUserFunction, retry) {
    var xmlReq = getXMLHttpRequest();

	for (var ri = 0; ri < 3; ri++) {
		try {
			execXMLHttpAction(xmlReq, url, 'POST', true, function() {
				return getPostFormDataCallback(xmlReq, url, target, linkUserFunction);
	    	}, formData);
	    	break;
	    } catch (err) {
	    	if (err.message.substring(0, 13)!='#Error#Retry#')
	    		alert(err.message);
	    }
	}
}
// Retrieve asynchronously an URL content using AJAX
function getURLData(url, target, userFunction, userMethod, addToTarget) {
	$.get(url, {}, setCallback(data, target, userFunction, userMethod, addToTarget), 'xml');
//    var xmlReq = getXMLHttpRequest();

//	myRand=parseInt(Math.random()*99999999);  // cache buster
//	url = url + (url.indexOf('?') != -1 ? '&rand=' : '?rand=') + myRand;

//	execXMLHttpAction(xmlReq, url, 'GET', true, function() {
//		return getURLCallback(xmlReq, url, target, userFunction, userMethod, addToTarget);
//    });
}
// A User Callback can be used (as a function or class)
function setCallback(data, target, userCallback, userMethod, addToTarget) {
			if (target != null) {
				_FillElement(target, data, addToTarget);
				
				if (userCallback) {
					/**
					 * On-Demand Javascript:
					 * The user Callback function is a JS function/class generated by this 
					 * asynchronous process which is required to be available on the final page.
					 * The function is automatically linked to the page for subsequent use (moved to head).
					 * JS functions generated after page is loaded are not reachable until these are moved on the page head.
					 */				
					linkJSFunction(document, userCallback);

					try {
						if (userCallback) {
							var usercall = '';
									
							if (userMethod) {
								// Executes an existing method
								if (userMethod.indexOf(')') != -1) {
									usercall = userMethod + ';';
								} else {	// Executes a method from the linked library
									usercall = 'var userObj = new ' + userCallback + '();userObj.' + userMethod + '();'
								}
							} else {
								usercall = 'try { ' + userCallback + '(); }	catch(e) {}';
							}
							setTimeout(usercall, 500);
						}
					}
					catch(err) {
						alert('AJAX Callback Error\n\n' + userCallback + ' has not been generated successfully\n\n' + err.message);
						return false;
					}
				}
    }
    return false;
}


// A User Callback can be used (as a function or class)
function getURLCallback(xmlReq, url, target, userCallback, userMethod, addToTarget) {
	if (xmlReq.readyState==4) {
		if (xmlReq.status==200) {
			if (target != null) {
				_FillElement(target, xmlReq.responseText, addToTarget);
				
				if (userCallback) {
					/**
					 * On-Demand Javascript:
					 * The user Callback function is a JS function/class generated by this 
					 * asynchronous process which is required to be available on the final page.
					 * The function is automatically linked to the page for subsequent use (moved to head).
					 * JS functions generated after page is loaded are not reachable until these are moved on the page head.
					 */				
					linkJSFunction(document, userCallback);

					try {
						if (userCallback) {
							var usercall = '';
									
							if (userMethod) {
								// Executes an existing method
								if (userMethod.indexOf(')') != -1) {
									usercall = userMethod + ';';
								} else {	// Executes a method from the linked library
									usercall = 'var userObj = new ' + userCallback + '();userObj.' + userMethod + '();'
								}
							} else {
								usercall = 'try { ' + userCallback + '(); }	catch(e) {}';
							}
							setTimeout(usercall, 500);
						}
					}
					catch(err) {
						alert('AJAX Callback Error\n\n' + userCallback + ' has not been generated successfully\n\n' + err.message);
						return false;
					}
				}
			}
			return true;
	    } else if (xmlReq.status==404 || xmlReq.status==500) {
	    	alert('AJAX Runtime Error\n\n' + xmlReq.statusText + '(' + xmlReq.status + ')');
//			_FillElement(target, 'AJAX Error:<BR>' + xmlReq.statusText + '(' + xmlReq.status + ')');
			return false;
	    } else {
	    	alert('Unable to reach ' + url + '\n\n' + xmlReq.statusText + '(' + xmlReq.status + ')');
			return false;
		}
    }
    return false;
}
function getPostFormDataCallback(xmlReq, url, target, linkUserCallback) {
	if (xmlReq.readyState==4) {
		if (xmlReq.status==200) {
			if (target != null) {
//			alert(xmlReq.responseText);
				if (!isEmpty(xmlReq.responseText) && xmlReq.responseText.length > 7 && trim(xmlReq.responseText).substring(0, 7)=='#Error#')
					_FillElement('errors', trim(xmlReq.responseText).substring(7));
				_FillElement(target, xmlReq.responseText);
//				if (linkUserCallback) {
					/**
					 * When the User Callback function is generated during this 
					 * asynchronous request it is automatically linked to the page (moved to head)
					 */
//					linkJSFunction(document, 'userPostAJAX');
//					userPostAJAX();
//				}
			}
			return true;
	    } else if (xmlReq.status==404 || xmlReq.status==500) {
	    	alert('AJAX Runtime Error\n\n' + xmlReq.statusText + ' (' + xmlReq.status + ')');
//			_FillElement(target, 'AJAX Error:<BR>' + xmlReq.statusText + '(' + xmlReq.status + ')');
			return false;
/*
   12029       ERROR_INTERNET_CANNOT_CONNECT
               The attempt to connect to the server failed.
   12030       ERROR_INTERNET_CONNECTION_ABORTED
               The connection with the server has been terminated.
   12031       ERROR_INTERNET_CONNECTION_RESET
               The connection with the server has been reset.
*/
	    } else if (xmlReq.status==12029 || xmlReq.status==12030 || xmlReq.status==12031) {
    		throw('#Error#Retry#Unable to reach ' + url + '\n\n' + xmlReq.statusText + ' (' + xmlReq.status + ')');
	    } else {
	    	alert('Unable to reach ' + url + '\n\n' + xmlReq.statusText + ' (' + xmlReq.status + ')');
			return false;
		}
    }
    return false;
}
// This function moves generated scripts with a given function/class name to the page head.
function linkJSFunction(node, fname)
{
  var bSaf = (navigator.userAgent.indexOf('Safari') != -1);
  var bOpera = (navigator.userAgent.indexOf('Opera') != -1);
  var bMoz = (navigator.appName == 'Netscape');
  var sClass = 'function ' + fname;		// matches a function or class name
  var test;
  
  if (!node)
  	return;
  
  try {
  	test = eval(fname);
  } catch (e) {	// If function is undefined the following code tries to find it and link it.
  /* IE wants it uppercase */
  var st = node.getElementsByTagName('SCRIPT');
  var strExec = '';

  for(var i=0;i<st.length; i++)
  {
    if (bSaf) {
      strExec += st[i].innerHTML;     
      if (strExec.indexOf(sClass)!=-1) {
	      st[i].innerHTML = "";
	      break;
	  }
    } else if (bOpera) {
      strExec += st[i].text;
      if (strExec.indexOf(sClass)!=-1) {
	      st[i].text = "";
	      break;
	  }
    } else if (bMoz) {
      strExec += st[i].textContent;
      if (strExec.indexOf(sClass)!=-1) {
	      st[i].textContent = "";
	      break;
	  }
    } else {
      strExec += st[i].text;
      if (strExec.indexOf(sClass)!=-1) {
	      st[i].text = "";
	      break;
	  }
    }
//    alert(strExec);
  }

  try {
      var newScript = document.createElement("script");
      newScript.type = "text/javascript";

      /* In IE we must use .text! */
      if ((bSaf) || (bOpera) || (bMoz))
        newScript.innerHTML = strExec;
      else newScript.text = strExec;

      if (document.getElementsByTagName("head")[0])
        document.getElementsByTagName("head")[0].appendChild(newScript);
  } catch(e) {
      alert(e);
  }
  }
}
function getRandom(max) {
	var rand = Math.floor(Math.random() * max);
	return rand;
}
var ajaxLoader = '<table width="100%" height="100%" border="0" style="background-color: #E6EAF0;"><tr><td align="center" valign="middle"><img src="/images/ajax-loader.gif"/></td></tr></table>'; 
var lastAjaxCall;

function loadMenu(menuUrl, serviceUrl, target) {
  if (serviceUrl)
    $('#Menu').load(menuUrl, {}, function(data){
      if (target && target == 'object')
        loadRemoteService(serviceUrl);
      else
        loadService(serviceUrl);
    });
  else
    $('#Menu').load(menuUrl);
}

// Ensures only the last Ajax user request is loaded asynchronously
function loadService(link) {
  $("#Service").css("height", $("#Center").height()-30);
  $('#Service').html(ajaxLoader);
  var now = new Date();
  link += (link.indexOf('?') != -1 ? '&rand=' : '?rand=') + getRandom(99999999);
  lastAjaxCall = now;
  $.get(link, null, function(data){
    if (now == lastAjaxCall) {
      $("#Service").css("height", "auto");
      $('#Service').html(data);
      $(".email").mailto();
      loadAsyncContent();
    }
  });
}

function loadRemoteService(link) {
  $("#Service").css("height", $("#Center").height()-30);
  $('#Service').html(ajaxLoader);
  $('#Service').html('<object data="' + link + '" type="text/html" width="'+$("#Service").width()+'px" height="'+$("#Service").height()+'px" style="background-color: white;"></object>');
}

function loadAsyncContent() {
  $(".async-content").each(function(i){
    var content = jQuery.trim($(this).text());
    if (content) {
    $(this).html(ajaxLoader).show();
    $(this).load(content, null, function(){
      var value = $("#Initializers").data($(this).attr("id"));
      if (value)
        eval(value);
      });
    }
  });
}
/*
function initSEOLinks(context) {
  $(".seoLink").each(function(i){
    $(this).click(function(){
      var seoLink = $(this).attr("href");
      $(this).
          loadMenu(context + '/Menu.jsp?m=" + itemId + "', '" + link + "', '" + itemTarget + "');";
    });
  });
  if (document.getElementsByTagName) {
    var links = document.getElementsByTagName("a");
    for (var i=0; i < links.length; i++) {
      if (links[i].className.match("seoLink")) {
        links[i].onclick = function() {
          window.open(this.getAttribute("href"));
          return false;
        };
      }
    }
  }
}
*/