//INDEX OF FUNCTIONS
//	- MakeFullyVisible
//	- setDropDownSelectedValue
//	- bitSelected
//  - setElementID
//	- showHideControl
//	- showHideDiv
//	- showDiv
//	- hideDiv
//	- toggleDivVisibility
//	- toggleHiddenBool
//	- toggleElementText
//	- toggleAttributeText
//	- setElementValue
//	- setAttributeValue
//	- IsDateWithFourDigitYear
//	- ConvertDurationOut
//  - parseJson

//Add Common Java Script Functions Here
var u   = "undefined";
var n = null;

var CONST = {}
CONST.invalidChars = "<>{}^~";
    

// Finds and returns an element with the specified ID...  even if we are on a master page
function FlFind(name) {

    var el  = document.getElementById(name);
    if (el != n) return el;

    var pre = new Array('ctl00_', 'ctl00_ctl00_', '_ctl0_', '_ctl0_FrontlineBody_', '_ctl0__ctl0_FrontlineBody_', '_ctl0__ctl0_FrontlineBody_AdvanceSearchOption_', 'xctl0xFrontlineBodyx', '_ctl0_LoginBody_',
						'ctl00_FrontlineBody_', 'ctl00__ctl0_FrontlineBody_','ctl00__ct10_FrontlineBody_AdvanceSearchOption_','xct00xFrontlineBodyx','ctl00_LoginBody_');
    for (var i=0; i< pre.length; i++) {
        el = document.getElementById(pre[i] + name);
        if (el != n) break;
    }
    
    return el;

}

// _Utils_MakeFullyVisible
//
// Make the selected HTML object completely visible including adjustments 
// for scroll bars.  Usually used for hidden DIVs.
//
function MakeFullyVisible(itemname) 
{
	var item = FlFind(itemname);
	MakeElementFullyVisible(item);
}
function MakeElementFullyVisible(item)
{
    var body = (document.documentElement && document.documentElement.clientHeight ? document.documentElement : document.body);
    //var body = document.body;

	// Make the item visible.
	item.style.top		= 0;
	item.style.left		= 0;
	item.style.position = "absolute";
	item.style.display	= "block";	
	item.style.zIndex   = 9;	
	
	//Once the item is made visible, it's clientWidth and clientHeight are set.
	var expectedWidth	= item.clientWidth;
	var expectedHeight	= item.clientHeight;

	// Relocate the item to an offset from the mouse position.
	// This resets the item.clientWidth and item.clientHeight.
	//item.style.pixelTop = event.clientY + body.scrollTop + 10;
	//item.style.pixelLeft = event.clientX + body.scrollLeft + 10;
	
	if (event != null)
	{
	    item.style.top       = event.clientY + body.scrollTop + 3;
        item.style.left      = event.clientX + body.scrollLeft + 3;
    }
    else
    {
        item.style.top  = (body.clientHeight / 2) - (expectedHeight / 2);
        item.style.left = (body.clientWidth / 2) - (expectedWidth / 2);
    }
	
	// Make sure the item doesn't appear off the visible screen
	/*
	alert("pixTop: " + item.style.pixelTop + "\n" +
				"posTop: " + item.style.posTop + "\n" + 
				"dHeight: " + item.clientHeight + "\n" +
				"pixBot: " + item.style.pixelBottom + "\n" +
				"posBot: " + item.style.posBottom + "\n" +
				"bHeight: " + body.clientHeight + "\n" 
				);
	*/
	//Adjust the position of the item so that it is fully displayed with it's 
	//expected width and height.
	if (item.style.pixelTop + expectedHeight > body.clientHeight + body.scrollTop) {
		item.style.top = body.clientHeight - expectedHeight - 15 + body.scrollTop;
	}
	
	if (item.style.pixelLeft + expectedWidth > body.clientWidth + body.scrollLeft) { 
		item.style.left = body.clientWidth - expectedWidth - 15 + body.scrollLeft;
	}
}
function confirmDelete(objectType)
{
	return confirm("Are you sure you want to delete this " + objectType + "?");
}
function setDropDownSelectedValue(ddl, value)
{
	var options = ddl.getElementsByTagName("OPTION");
	for (i=0; i < options.length; i++)
	{
		var option = options[i];
		if (option.value == value)	option.selected = true;
		else						option.selected = false;
	}
}
function bitSelected(valueToCheck, bitToCheck)
{
	return ((valueToCheck & bitToCheck) == bitToCheck);
}
//This function is used in conjunction with the FLShowHide control
function ShowHideControl(img, showImg, hideImg, ctrlName, hiddenCtrlName)
{
	toggleDivVisibility(ctrlName);			//Normally a div
	toggleHiddenBool(hiddenCtrlName);		//Hidden field to hold the state of the ctrl...
	toggleAttributeText(img.id, "src", showImg, hideImg);
}
function showHideDiv(divName, show)
{
	if (show)	showDiv( divName )
	else		hideDiv( divName );
}

function showDiv(divName)
{
	try
	{
		var div = FlFind(divName);
		div.style.display = "";
	}
	catch(ex) {}
}
function hideDiv(divName)
{
	try
	{
		var div = FlFind(divName);
		div.style.display = "none";
	}
	catch(ex) {}
}
function toggleDivVisibility(divName)
{
	try
	{
		var hiddenDiv = FlFind(divName);
		var style = hiddenDiv.style;
		style.display = (style.display == "none" ? "" : "none");	
	}
	catch(ex) {}
}
function toggleHiddenBool(elName)
{
	try
	{
		var element = FlFind(elName);
		//alert(element.value);
		element.value = (element.value == "false" ? "true" : "false");
		//alert(element.value);
	}
	catch(ex) {}
}
function toggleElementText(elName, text1, text2)
{
	try
	{
		var element = FlFind(elName);
		var iText = element.innerText;
		if (iText.indexOf(text1) > -1)	
		{
			iText = iText.replace(text1, text2);
		}
		else 
		{
			iText = iText.replace(text2, text1);
		}
		element.innerText = iText;
	}
	catch(ex) {}

}
function toggleAttributeText(elName, attrName, text1, text2)
{
	try
	{
		var element = FlFind(elName);
		var attr = element.getAttribute(attrName);
		var newAttrText;
		if (attr.indexOf(text1) > -1)
		{
			newAttrText = attr.replace(text1, text2);
		}
		else
		{
			newAttrText = attr.replace(text2, text1);
		}
		element.setAttribute(attrName, newAttrText);
	}
	catch(ex) {}
}
function setElementValue(elName, value)
{
	try
	{
		var element = FlFind(elName);
		element.value = value;
	}
	catch(ex) {}
}
function setElementClass(elName, className)
{
	try
	{
		var element = FlFind(elName);
		element.className = className;
	}
	catch(ex) {}
}
function setAttributeValue(elName, attrName, value)
{
	try
	{
		var element = FlFind(elName);
		alert(element);
		var attr	= element.getAttribute(attrName);
		alert(attr);
		attr.value	= value;
	}
	catch(ex) {}
}
//Find the first ancestor element of type <tagName> that has an id specified
function getNamedAncestorElement(el, tagName)
{
	parNode = el.parentNode;
	while (parNode != null)
	{
		if (parNode.tagName == tagName && parNode.id != "") break;
		parNode = parNode.parentNode;
	}
	return parNode;		//Might return NULL
}
//Find the first ancestor element of type <tagname>
function getAncestorElement(el, tagName)
{
	parNode = el.parentNode;
	while (parNode != null)
	{
		if (parNode.tagName == tagName) break;
		parNode = parNode.parentNode;
	}
	return parNode;		//Might return NULL
}
// Find the index into an array based on a specified value
function findDropDownOptionIndex( ddl, value )
{
	for (var i=0; i<ddl.options.length; i++)
	{
		if (ddl.options[i].value == value)	return i;
	}
	return -1;
}

// Find the index into an array based on a specified value
function findArrayIndex( array, value )
{
	for (var i=0; i<array.length; i++)
	{
		if (array[i] == value)	return i;
	}
	return -1;
}
function IsDateWithFourDigitYear(text)
{
	//Accepts 1 or 2 digit month followed by 1 or 2 digit day followed by 4 digit year.
	//This regx does NOT validate combinations of month day
	var regx_mmddyyyy = new RegExp("^[0-9]{1,2}/[0-9]{1,2}/[2][0-9]{3}$");
	var regx_yyyymmdd = new RegExp("^[2][0-9]{3}/[0-9]{1,2}/[0-9]{1,2}$");
	var OK = regx_mmddyyyy.test(text);
	if (!OK)
	{
	    var OK = regx_yyyymmdd.test(text);
	}
	return OK;
}
function UltraWebGrid1_CellClickHandler(gridName, cellId, button){}

function UltraWebGrid1_BeforeCellUpdateHandler(gridName, cellId, value){
	var oGrid = igtbl_getGridById(gridName);
	var oRow = igtbl_getRowById(cellId);
	var chckedRowCount = 0;
	for(var i = 0; i < oRow.ParentRow.Rows.length; i++)
	{
		if(oRow.ParentRow.Rows.getRow(i).getCellFromKey("chk").getValue() == true)
		{
			chckedRowCount++;			
		}	
	}
	switch (chckedRowCount){
		case 0: 
			oRow.ParentRow.getCellFromKey("chked").setValue("One");
		break;
		case 1: 
			oRow.ParentRow.getCellFromKey("chked").setValue("Some");
		break;
		case 3: 
			oRow.ParentRow.getCellFromKey("chked").setValue("A Few");
		break;			
		default : 
		oRow.ParentRow.getCellFromKey("chked").setValue("A lot.");
	}
}

// Setup Tree
function SetupTree_NodeClicked(treeID, nodeID){
	var cancel = false;	// postback by default
	
	var oTree = igtree_getTreeById(treeID);
	var oNode = igtree_getNodeById(nodeID);

	if (oNode != null){	
		var oDataKey = oNode.getDataKey();

		if (oDataKey == null) {
			// cancel postback
			cancel = true;
			oNode.setExpanded(!oNode.getExpanded());
		}
		
		if (oDataKey == "") {
			// cancel postback
			cancel = true;
			oNode.setExpanded(!oNode.getExpanded());
		}
	}

	return cancel;
}

// ****************************
// Convert Duration
// ****************************
function ConvertDaysOut(Days, Hours, Minutes)
{
	var s = "";
	if (Days == 1)
	{
		s = "1 day " + ConvertHoursOut(Hours, Minutes, false);
	}
	else
	{
		s = Days.toString() + " days " + ConvertHoursOut(Hours, Minutes, false);
	}
	return s;
}
function ConvertHoursOut(Hours, Minutes, showIfZero)
{
	var s = "";
	if (Hours == 0)
	{
		return ConvertMinutesOut(Minutes, showIfZero);
	}
	if (Hours == 1)
	{
		if (Minutes == 0)				s = "1 hour";
		//else if ((Minutes % 15) == 0)	s = "1 " + ConvertMinutesOut(Minutes, false) + "s";
		else							s = "1 hour " + ConvertMinutesOut(Minutes, false);
	}
	else
	{
		if (Minutes == 0)				s = Hours.toString() + " hours";
		//else if ((Minutes % 15) == 0)	s = Hours.toString() + " " + ConvertMinutesOut(Minutes, false) + "s";
		else							s = Hours.toString() + " hours " + ConvertMinutesOut(Minutes, false);
	}
	return s;
}
function ConvertMinutesOut(Minutes, showIfZero)
{
	var s = "";
	if (Minutes < 60)
	{
		if (Minutes == 0)		s = (showIfZero ? "0 minutes" : "");
		else if (Minutes == 1)	s = "1 minute";
		//else if (Minutes == 15)	s = "1/4 hour";
		//else if (Minutes == 30) s = "1/2 hour";
		//else if (Minutes == 45) s = "3/4 hour";
		else					s = Minutes.toString() + " minutes";	
	}
	return s;
}
//Convert a Duration to an Integer Minute value and then call
//the ConvertDurationOut routine that handles Minutes...
/*
function ConvertDurationOut(Duration, durAmt)
{
	switch (durAmt)
	{
		case DurationAmount.Days:
			return ConvertDurationOut( Convert.ToInt32(Duration * 1440));

		case DurationAmount.Hours:
			return ConvertDurationOut( Convert.ToInt32(Duration * 60));

		case DurationAmount.Minutes:
			return ConvertDurationOut( Convert.ToInt32(Math.Floor(Duration)) );

		default:
			return "";
	}	
}
*/
function ConvertDurationOut(DurationMinutes)
{
	var Days = 0;
	var HRs  = 0;
	var Mins = 0;

	if (DurationMinutes < 0) DurationMinutes *= -1;

	//Less than 1 hour
	if (DurationMinutes < 60)
	{
		return ConvertMinutesOut(DurationMinutes, true);
	}

	//Less than 1 day
	
	else if ((DurationMinutes >= 60) && (DurationMinutes < 1440))
	{
		HRs = Math.floor( DurationMinutes / 60 );
		Mins = DurationMinutes - (HRs * 60);
		return ConvertHoursOut(HRs, Mins, false);
	}
	
	//More than 1 day
	else 
	{	
		Days	= Math.floor( DurationMinutes / 1440 );
		HRs		= Math.floor( (DurationMinutes - (Days * 1440)) / 60);
		Mins	= DurationMinutes - (Days * 1440) - (HRs * 60);
		return ConvertDaysOut(Days, HRs, Mins);
	}
}

// This function calls the derived page's java function Page_Load(),
// if the fn doesn't exist, the catch keeps things ticking
function BasePage_Load(){
	try {
		Page_Load();
	}
	catch (e) {}
}

function collapseTaskPad(el, hide) {

	var tpTable = FlFind("EmployeeTaskPad");
	var sideBar = tpTable.parentNode.parentNode;

	document.cookie = "tp=" + hide.toString() + "; ";

	if (hide) {
		tpTable.rows[0].style.display = "none";
		tpTable.rows[1].style.display = "none";
		tpTable.rows[2].cells[0].className = "inverseHeader";
		tpTable.rows[2].style.display = "";
		tpTable.width = 30;
	} else {
		tpTable.rows[0].style.display = "";
		tpTable.rows[0].cells[0].width = 30;
		tpTable.rows[1].style.display = "";
		tpTable.rows[2].style.display = "none";
		tpTable.width = 180;
	}	
}

function popUp(strURL,strType,strHeight,strWidth) 
{
	var strOptions="";
	if (strType=="console") strOptions="resizable,height="+strHeight+",width="+strWidth;
	if (strType=="fixed") strOptions="status,height="+strHeight+",width="+strWidth;
	if (strType=="elastic") strOptions="toolbar,menubar,scrollbars,resizable,location,height="+strHeight+",width="+strWidth;
	window.open(strURL, 'newWin', strOptions);
}

function popUpModal(strURL,strHeight,strWidth) 
{
	var strOptions="toolbar=no,menubar=no,scrollbars=no,resizable=no,status=no,height="+strHeight+",width="+strWidth;
	window.open(strURL, 'newWin', strOptions);
}
function popUpModalResizeable(strURL,strHeight,strWidth) 
{
	var strOptions="toolbar=no,menubar=no,scrollbars=no,resizable=yes,status=no,height="+strHeight+",width="+strWidth;
	window.open(strURL, 'newWin', strOptions);
}

// Browser-agnostic factory function
function createXMLHttpRequest() {
   if (window.XMLHttpRequest) {
     return new window.XMLHttpRequest();
   } else if (window.ActiveXObject) {
     return new ActiveXObject("Microsoft.XMLHTTP")
   } else {
     window.status = "Could not create XMLHttpRequest on this browser";
     return null;
   }
 };

function parseJson(jsonText)
{
    try
    {
        return eval('(' + jsonText + ')');
    }
    catch (ex) { alert("ParseJson exception: " + ex.message);}
}

function addShadow(idToShadow, color)
{
    var x = $('#' + idToShadow);
    if (x.length == 0) return;

	var h = x.height();
	var w = x.width();
	var pos = x.offset();

    //alert(pos.left + "..." + pos.top + "..." + w + "..." + h + "..." );

	x.css("z-index", 100);
    
    //alert(x.selector);

	addShadowLayer(idToShadow, 1, color, pos, h, w, 98);
	addShadowLayer(idToShadow, 2, color, pos, h, w, 98);
	addShadowLayer(idToShadow, 3, color, pos, h, w, 98);
	addShadowLayer(idToShadow, 4, color, pos, h, w, 98);
	addShadowLayer(idToShadow, 5, color, pos, h, w, 98);
	addShadowLayer(idToShadow, 6, color, pos, h, w, 98);
	addShadowLayer(idToShadow, 7, color, pos, h, w, 98);
	addShadowLayer(idToShadow, 8, color, pos, h, w, 98);
}
	
function addShadowLayer(idToShadow, level, color, pos, height, width)
{
    var opacity = 1 - (level * .1);
	var ieOpacity = 100 * opacity;
	var id = idToShadow + 'shad' + level;
	//--alert(opacity + "..." + ieOpacity + "..." + id);

	var div = "<DIV class='dshad' id='" + id + "' style='border:solid 1px gray;position:absolute;background-color: " + color + "; filter:alpha(opacity=" + ieOpacity + "); opacity:" + opacity + "'></DIV>";
	//alert(div)
	$('body').append(div);

	$('#' + id)
		.css("top", (pos.top+level) + "px")
		.css("left", (pos.left+level) + "px")
		.css("height", height)
		.css("width", width)
		.css("z-index", 98)
		;
}

function ShowJqueryEvent(event) {
    alert(
        "type: " + event.type + "\n" +
        "target: " + event.target + "\n" +
        "data: " + event.data + "\n" +
        "pageX: " + event.pageX + "\n" +
        "pageY: " + event.pageY + "\n" +
        "result: " + event.result + "\n" +
        "timeStamp: " + event.timeStamp + "\n"
    );
}

function AsDBSmallDateTime(datetime) {
    var mn = datetime.getMonth() + 1;
    var template = "yyyy-mm-dd hh:mn";
    template = template.replace("yyyy", datetime.getYear());
    template = template.replace("mm", datetime.getMonth() + 1);    //Javascript months are 0 based
    template = template.replace("dd", datetime.getDate());
    template = template.replace("hh", datetime.getHours());
    template = template.replace("mn", datetime.getMinutes());
    return template;
}
