// cross-browser javascript library

// variables for the whole system
var ns4 = document.layers;
var ns6 = document.getElementById && !document.all;
var ie4 = document.all;
var sys_WebAppName = "";

// variables for the tool tip.
var offsetX = 10;
var offsetY = 10;
var toolTipSTYLE = "";
var toolTipBody = "";
var isToolTipOn = false;
var fixToolTipPos = false;

// variables for safe onload and onunload
var sys_SafeOnload = new Array();
var sys_SafeOnunload = new Array();
var sys_SafeOnresize = new Array();

// Safe onload
function SafelyAddOnload(f)
{
    if  (window.onload)
	{
		if (window.onload != SafeOnload)
		{
			sys_SafeOnload[0] = window.onload;
			window.onload = SafeOnload;
		}		
		sys_SafeOnload[sys_SafeOnload.length] = f;
	}
	else
		window.onload = f;
}

function SafeOnload()
{
	for (var i=0;i<sys_SafeOnload.length;i++)
		sys_SafeOnload[i]();
}

// Safe onunload
function SafelyAddOnunload(f)
{
    if  (window.onunload)
	{
		if (window.onunload != SafeOnunload)
		{
			sys_SafeOnunload[0] = window.onunload;
			window.onunload = SafeOnunload;
		}		
		sys_SafeOnunload[sys_SafeOnunload.length] = f;
	}
	else
		window.onunload = f;
}

function SafeOnunload()
{
	for (var i=0;i<sys_SafeOnunload.length;i++)
		sys_SafeOnunload[i]();
}

// Safe onresize
function SafelyAddOnresize(f)
{
    if  (window.onresize)
	{
		if (window.onresize != SafeOnresize)
		{
			sys_SafeOnresize[0] = window.onresize;
			window.onresize = SafeOnresize;
		}		
		sys_SafeOnresize[sys_SafeOnresize.length] = f;
	}
	else
		window.onresize = f;
}

function SafeOnresize()
{
	for (var i=0;i<sys_SafeOnresize.length;i++)
		sys_SafeOnresize[i]();
}

// Example: preloadImages('file.gif', 'http://www.x.com/y.gif');
function preloadImages()
{
  if(document.images)
  {
    if(!document.imageArray) document.imageArray = new Array();
    var i,j = document.imageArray.length, args = preloadImages.arguments;
    
    for(i=0; i<args.length; i++)
    {
      if (args[i].indexOf("#")!=0)
      {
        document.imageArray[j] = new Image;
        document.imageArray[j++].src = args[i];
      }
    }
  }
}


// Example: obj = findObj("image1");
function findObj(theObj, theDoc)
{
  var p, i, foundObj;
  
  if(!theDoc) theDoc = document;
  if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
  {
    theDoc = parent.frames[theObj.substring(p+1)].document;
    theObj = theObj.substring(0,p);
  }
  if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
  for (i=0; !foundObj && i < theDoc.forms.length; i++) 
    foundObj = theDoc.forms[i][theObj];
  for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) 
    foundObj = findObj(theObj,theDoc.layers[i].document);
  if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
  
  return foundObj;
}

// * Dependencies * 
// this function requires the following snippets:
// JavaScript/readable_MM_functions/findObj
//
// Accepts a variable number of arguments, in triplets as follows:
// arg 1: simple name of a layer object, such as "Layer1"
// arg 2: ignored (for backward compatibility)
// arg 3: 'hide' or 'show'
// repeat...
//
// Example: showHideLayers(Layer1,'','show',Layer2,'','hide');
function showHideLayers()
{ 
  var i, visStr, obj, args = showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3)
  {
    if ((obj = findObj(args[i])) != null)
    {
      visStr = args[i+2];
      if (obj.style)
      {
        obj = obj.style;
        if(visStr == 'show') visStr = 'visible';
        else if(visStr == 'hide') visStr = 'hidden';
      }
      obj.visibility = visStr;
    }
  }
}


// Example:
// onMouseOver="toolTip('tool tip text here')";
// onMouseOut="toolTip()";
// -or-
// onMouseOver="toolTip('more good stuff', '#FFFF00', 'orange')";
// onMouseOut="toolTip()"; 

/*
MOVE this to the <body>:
<div id="Bubble" style="position:absolute; visibility: hidden"></div>
<script language="JavaScript"><!--
initToolTips(); //--></script>
*/


function initToolTips()
{
  if(ns4||ns6||ie4)
  {
    if(ns4) {
		toolTipSTYLE = document.Bubble;
		//toolTipBody = document.BubbleBody;
	}
    else if(ns6) {
		toolTipSTYLE = document.getElementById("Bubble").style;
		toolTipBody = document.getElementById("BubbleBody");
	}
    else if(ie4) {
		toolTipSTYLE = document.all.Bubble.style;
		toolTipBody = document.all.BubbleBody;
	}
	
    if(ns4) {
		document.captureEvents(Event.MOUSEMOVE);
	} else {
      toolTipSTYLE.visibility = "visible";
      toolTipSTYLE.display = "none";
    }
    document.onmousemove = moveToMouseLoc;
  }
}

function toolTip(msg, fg, bg)
{
  if(toolTip.arguments.length < 1) // hide
  {
    if(ns4) toolTipSTYLE.visibility = "hidden";
    else toolTipSTYLE.display = "none";
	
	isToolTipOn = false;
	fixToolTipPos = false;
  }
  else // show
  {
    
	if(!fg) fg = "#990000";	// dark red
    if(!bg) bg = "#FFFFFF";	// white
    var content = "";
	
	if(ns4) {
		// use tables to re-create the tool tip border and background color.
		// do not use CCS for the font
		content =
			'<table border="0" cellspacing="0" cellpadding="1" bgcolor="' + fg + '"><td>' +
			'<table border="0" cellspacing="0" cellpadding="1" bgcolor="' + bg + 
			'"><td align="center"><font face="sans-serif" color="' + fg +
			'" size="-2">&nbsp\;' + msg +
			'&nbsp\;</font></td></table></td></table>';
	} else {
		// use the existing bubble for the border and background color
		// use CSS for the font
		content =
			'<font color="' + fg + '" class="a11">' + msg + '</font>';
	}
	
    if(ns4)
    {
      // the bubble decoration will be lost
	  toolTipSTYLE.document.write(content);
      toolTipSTYLE.document.close();
      toolTipSTYLE.visibility = "visible";
    }
    if(ns6)
    {
      toolTipBody.innerHTML = content;
      toolTipSTYLE.display = 'block';
    }
    if(ie4)
    {
      toolTipBody.innerHTML = content;
      toolTipSTYLE.display = 'block';
    }
	
	isToolTipOn = true;
	fixToolTipPos = true;
  }
}

function moveToMouseLoc(e)
{
  if (!fixToolTipPos)
  {
	  var x, y;
	  if(ns4||ns6)
	  {
		x = e.pageX;
		y = e.pageY;
	  }
	  else
	  {
		x = event.x + document.body.scrollLeft;
		y = event.y + document.body.scrollTop;
	  }
	  
	  // if x exceeds a certain range, show it to the left of the pointer.
	  // note the display is not symmetric to the left and right of the action point.
	  // this is by design for optimal readability.
	  var xThreshold = 400;
	  var bubbleWidth = parseInt(toolTipSTYLE.width);
	  var bubbleX, bubbleY;
	  if (x >= xThreshold)
	  {
		  bubbleX = x - bubbleWidth;
	  }
	  else
	  {
		  bubbleX = x + offsetX;
	  }
	  bubbleY = y + offsetY;
	  
	  toolTipSTYLE.left = bubbleX;
	  toolTipSTYLE.top = bubbleY;
  }
  
  return true;
}

function toolTipWithOffset(msg, xOffset, yOffset)
{
	toolTip(msg);
	if (xOffset != null) {toolTipSTYLE.left = parseInt(toolTipSTYLE.left) + xOffset}
	if (yOffset != null) {toolTipSTYLE.top = parseInt(toolTipSTYLE.top) + yOffset}
}

function showCalendar(controlName)
{
    // Check if the web application name has been set.
    if (sys_WebAppName == "")
    {
        alert("Web application name is empty!");
        return;
    }
  	
  var ctrl = document.forms[0].elements[controlName];
  var url = (sys_WebAppName == "/" ? "" : sys_WebAppName) + 
	  "/Common/DateSelector.aspx?ControlName=" + controlName;
  if (ctrl.value != "")
  {
	  url += "&SelectedDate=" + ctrl.value;
  }

  var iframeHTML = 
	"<iframe src='" + url + "'" +
	" width='185' height='175' border='0' frameborder='0'>" +
	"</iframe>" +
	"<div align='center'><a href='javascript:hideCalendar()'>Close Calendar</a></div>";
  
  // display the calendar
  toolTip(iframeHTML);
  
  // fine-tune the position of the calendar for better viewability
  var winWidth = document.body.clientWidth;
  var winHeight = document.body.clientHeight;
  var calWidth = 200;
  var calHeight = 190;
  var curCalX = parseInt(toolTipSTYLE.left);
  var curCalY = parseInt(toolTipSTYLE.top);
  var newCalX, newCalY;
  if (curCalX + calWidth > winWidth)
  {
	  toolTipSTYLE.left = curCalX - (curCalX + calWidth - winWidth + 30);
  }
  if (curCalY + calHeight > winHeight)
  {
	  toolTipSTYLE.top = curCalY - (curCalY + calHeight - winHeight + 30);
  }
  
  return true;	
}

function hideCalendar(controlName, newValue)
{
	if (hideCalendar.arguments.length > 0)
	{
		document.forms[0].elements[controlName].value = newValue;
	}
	toolTip();
	//return true;
}

function openInBackground(url)
{
  	// open the url in the background
	var content = 
		"<iframe src='" + url + "'" +
		" width='100' height='100' border='0' frameborder='0'>" +
		"</iframe>";
	var container = document.getElementById("sys_BkgPageOpener");
	container.innerHTML = content;
}

function showStatus(msg)
{
    window.status = msg ;
    return true ;
}

function highlightFirstFormElement()
{
	try {
		for (var i=0; i<document.forms[0].elements.length; i++) {
			if (document.forms[0].elements[i].type != "hidden") {
				//document.forms[0].elements[i].select();
				document.forms[0].elements[i].focus();
				break;
			}
		}
	}
	catch(e) {}
}

function afterLoadingWorkLayout()
{
	loadCommunicator();
}

function afterLoadingDialogLayout()
{
	highlightFirstFormElement();
	loadCommunicator();
}

function loadCommunicator()
{
    // Check if the web application name has been set.
  	if (sys_WebAppName == "")
  	{
  	    alert("Web application name is empty!");
  	    return;
  	}
  	
    // open the Communicator in the background
    var content = 
	    "<iframe src='" + (sys_WebAppName == "/" ? "" : sys_WebAppName) + 
	    "/Common/UserCommunicator.aspx'" +
	    " width='100' height='100' border='0' frameborder='0'>" +
	    "</iframe>";
    var container = document.getElementById("sys_CommunicatorContainer");
    container.innerHTML = content;
}

function showContactSelector(controlName, isPerson, parentControlName)
{
    // Check if the web application name has been set.
    if (sys_WebAppName == "")
    {
        alert("Web application name is empty!");
        return;
    }
  	
    var ctrl = document.forms[0].elements[controlName];
  	var parentCtrl = null, parentContactID = "";
  	if (parentControlName != "")
  	{
  	    parentCtrl = document.forms[0].elements[parentControlName];
  	    parentContactID = (parentCtrl ? parentCtrl.value : "");
  	}
  	
    var url = (sys_WebAppName == "/" ? "" : sys_WebAppName) + 
        "/Modules/ContactMgmt/" +
        (isPerson ? "SelectPerson.aspx" : "SelectOrganization.aspx") +
        "?ControlName=" + controlName + "&SelectedContactID=" + ctrl.value +
        (isPerson ? ("&ParentContactID=" + parentContactID) : "");
      
    var iframeHTML = 
        "<iframe src='" + url + "'" +
        " width='400' height='300' border='0' frameborder='0'>" +
        "</iframe>" +
        "<div class='a11' align='center'>" +
        "<input type='button' onclick='javascript:hideContactSelector();' " + 
        "class='a11' value='CANCEL'></div>";

    // display the calendar
    toolTip(iframeHTML);

    // optimize the position of the selector
    var winWidth = document.body.clientWidth;
    var winHeight = document.body.clientHeight;
    var calWidth = 400;
    var calHeight = 300;
    var curCalX = parseInt(toolTipSTYLE.left);
    var curCalY = parseInt(toolTipSTYLE.top);
    var newCalX, newCalY;
    if (curCalX + calWidth > winWidth)
    {
        toolTipSTYLE.left = curCalX - (curCalX + calWidth - winWidth + 30);
    }
    if (curCalY + calHeight > winHeight)
    {
        toolTipSTYLE.top = curCalY - (curCalY + calHeight - winHeight + 30);
    }

    return true;	
}

function hideContactSelector(controlName, contactID, contactDscr)
{
	if (hideContactSelector.arguments.length > 0)
	{
		document.forms[0].elements[controlName].value = contactID;
		// Note: Firefox doesn't support innerText property. 
		// Use innerHTML for cross-browser compatibility.
		document.getElementById("sys_ContactLabel_" + controlName).innerHTML = contactDscr;
	}
	toolTip();
}

function TranslateDateShortcuts(ctrl)
{
    if (ctrl)
    {
        var val = ctrl.value;
        if (val.indexOf("/") == -1)
        {
            if (val.length == 4)
            {
                ctrl.value = val.substring(0, 2) + "/" + val.substring(2, 4);
            }
            else if (val.length == 6)
            {
                ctrl.value = val.substring(0, 2) + "/" + val.substring(2, 4) + "/" + val.substring(4, 6);
            }
        }
    }
    else
    {
        alert(ctrl + " doesn't exist.");
    }
}

function TranslateSelfDateShortcuts(e)
{
	var ctrl = GetEventSource(e);
    TranslateDateShortcuts(ctrl);
}

function TranslateDateShortcutsByName(controlName)
{
	var ctrl = document.forms[0].elements[controlName];
    TranslateDateShortcuts(ctrl);
}

function GetEventSource(e)
{
    var ctrl;
	if (!e) var e = window.event;
	if (e.target) ctrl = e.target;
	else if (e.srcElement) ctrl = e.srcElement;
	if (ctrl.nodeType == 3) ctrl = ctrl.parentNode; // defeat Safari bug
    return ctrl;
}

function ResetAutoSubmitTimeout(autoSubmitButtonId, e)
{
    // Exclude PageUp, PageDown, Home, End, Up, Down, Left, Right keys.
    if (e.keyCode >= 33 && e.keyCode <= 40) { return; }
    
    if (this.autoSubmitHandle)
    {
        clearTimeout(this.autoSubmitHandle);
        this.autoSubmitHandle = 0;
    }
    this.autoSubmitHandle = setTimeout("document.getElementById('" + autoSubmitButtonId + "').click()", 1000);
}

function SetSelectionRange(input, selectionStart, selectionEnd)
{
    if (input.setSelectionRange)
    {
       input.focus();
       input.setSelectionRange(selectionStart, selectionEnd);
    }
    else if (input.createTextRange)
    {
       var range = input.createTextRange();
       range.collapse(true);
       range.moveEnd('character', selectionEnd);
       range.moveStart('character', selectionStart);
       range.select();
    }
}

function SetFocusToTextBox(textbox)
{
    var text = textbox.value;
    if (text.length == 0)
    {
        textbox.focus();
    }
    else
    {
        SetSelectionRange(textbox, text.length, text.length);
    }
}

function InsertAtCursor(myField, myValue)
{
    if (document.selection)
    {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    else if (myField.selectionStart || myField.selectionStart == '0')
    {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.value.substring(0, startPos)
            + myValue
            + myField.value.substring(endPos, myField.value.length);
    } 
    else 
    {
        myField.value += myValue;
    }
}
// calling the function
// InsertAtCursor(document.formName.fieldName, 'this value');