var g_isIE = (navigator.appName.indexOf("Microsoft") != -1);

// Create Flash or activex object externally of page to prevent object having to be activated manually be user in IE
function createFlashObject(elemId, objHtml)
{
	var d=document.getElementById(elemId);
	if (d!=null) d.innerHTML = objHtml;
	//else alert("createFlashObject() - cannot find element: " + divId);
}


// Open centered window.
// @param target: Target window
// @param w: Width in pixels or percent (0.01 - 1)
// @param h: Height in pixels or percent (0.01 - 1)
// @param href: Hyperlink
// @param features: optional window features
function openCenteredWindow (target, w, h, href, features)
{
	var sw = screen.availWidth;
	var sh = screen.availHeight;
	if (w==null || w<0) w = 0.85;
	if (h==null || h<0) h = 0.85;
	if (w>0 && w<=1) w = sw * w;
	if (h>0 && h<=1) h = sh * h;

	var left = ((sw - w - 10) * .5);
	var top = ((sh - h - 30) * .5);
	if (left<1) left=1;
	if (top<1) top=1;

	openNewWindow(target, w, h, href, left, top, features);
	return (false);
}


// @param features - optional window features
function openNewWindow (winname, width, height, myurl, xpos, ypos, features)
{
	var winref;
	var options;
	//alert(xpos + "," + ypos);

	if (width == "")
	{
		width = 500;
		//width = window.screen.availWidth - 4;
	}

	if (features != null)
	{
		options = features + ",width=" + width;
	}
	else
	{
		options = "toolbar=no,location=no,resizable=yes,scrollbars=yes,width=" + width;
	}

	if (height != "")
	{
		options += ",height=" + height;
	}
	if (xpos != null && xpos != "")
	{
		options += ",left=" + xpos;
	}
	if (ypos != null && ypos != "")
	{
		options += ",top=" + ypos;
	}
	//alert(options);

	winref = window.open("", winname, options);
	if(winref == null || winref.closed)
	{
		showWinError();
		return null;
	}

	if (myurl != null && myurl.length != 0)
	{
		winref.location.replace(myurl);
	}

	try	{ winref.focus(); }
	catch (e) { showWinError(); }

	return (winref);
}

function showWinError()
{
	alert(g_msg_var_UnableToOpenWindow_Line1 + "\n\n" + g_msg_var_UnableToOpenWindow_Line2 + "\n" + g_msg_var_UnableToOpenWindow_Line3);
}

function shrink(id)
{
	var e=document.getElementById(id);
	if (e!= null) e.style.display="none";
}

function grow(id)
{
	var e=document.getElementById(id);
	if (e!= null) e.style.display="";
}

function getWindowSize()
{
	var d=document;xMax=0;yMax=0;
	if(d.getElementById){
		if(d.documentElement&&d.documentElement.clientHeight)
		{
			xMax=d.documentElement.clientWidth;
			yMax=d.documentElement.clientHeight;
		}
		else
		{
			xMax=(d.all)?d.body.clientWidth:window.innerWidth;
			yMax=(d.all)?d.body.clientHeight:window.innerHeight;
	 	}
	}
	else if(d.layers)
	{
		xMax=window.innerWidth;
		yMax=window.innerHeight;
	}

	//alert("X: "+xMax+", Y: "+yMax);
	return new Array(xMax, yMax);
}

// Get cookie value (value is not unescaped)
function getCookie( name ) {
	var start = document.cookie.indexOf(name + "=");
	if (start == -1) return null;
	var len = start + name.length + 1;
	var end = document.cookie.indexOf(';', len);
	if (end == -1) end = document.cookie.length;
	return document.cookie.substring(len, end );
}

// Sets a cookie value (value not auto escaped)
function setCookie(name, value, expires, path, domain, secure)
{
	var c = name + "=" + value +
	(expires ? "; expires=" + expires.toGMTString() : "") +
	(path ? "; path=" + path : "") +
	(domain ? "; domain=" + domain : "") +
	(secure ? "; secure=" + secure : "");
	//alert(c);
	document.cookie = c;
}

////////////////////////////////////////////////////////////////////////////
// Multi-select dropdowns - Dashboard/Item filters
////////////////////////////////////////////////////////////////////////////
var g_openMSFilter = null;
var g_openMSFilterFieldName = null;
var g_openMSFilterInititialVals = "";

// Items page - Show checkbox multi-select dropdown box
function onClickMSItemFilterHeader(fldName)
{
	if(_DB_debugging) _DB_debug("onClickMSItemFilterHeader(fldName="+fldName + ")");

	var listBox = document.getElementById(fldName + "_list")
	if (listBox==null) return;
	
	var closingThis= (fldName==g_openMSFilterFieldName);
	
	// hide any visible filter lists, if any hidden then quit
	if (hideMSFilters('onClickMSItemFilterHeader')==true) return;

	if (closingThis) return;
	
	//////////////////////////
	listBox.style.display="block";	
	var itemWidth = document.body.clientWidth;
	var itemHeight = document.body.clientHeight;
	// get position/size of listbox header box
	var hb = document.getElementById(fldName + "_header")
	var hbPos = GetObjectPosition(hb);
	/*
	_DB_debug("----------------------");
	_DB_debug("itemHeight="+itemHeight);	
	_DB_debug("hbLeft="+hbPos.Left);
	_DB_debug("hbTop="+hbPos.Top);
	_DB_debug("hbRight="+hbPos.Right);
	_DB_debug("hbBottom="+hbPos.Bottom);
	_DB_debug("hbWidth="+hbPos.Width);
	_DB_debug("hbHeight="+hbPos.Height);
	*/
	if (!g_isIE)
	{
		hbPos.Width-=2;
		hbPos.Top-=2;
		hbPos.Bottom+=4;
	}

	// work out size/position of listbox	
	var ddLeft=hbPos.Left;
	var ddTop=0;
	var ddHeight=listBox.scrollHeight;
	if (g_isIE) ddHeight+=2;

	var maxWidth=itemWidth-ddLeft;
	if (!g_isIE) maxWidth-=2;
	var ddWidth=listBox.scrollWidth;
	if (ddWidth<hbPos.Width) ddWidth=hbPos.Width;	
	if (ddWidth>maxWidth) ddWidth=maxWidth;

	// show listbox below header box if possible, show above if more space
	var topSpace=hbPos.Top;
	var botSpace=itemHeight-hbPos.Bottom;
	var maxHeight=0;
	if (ddHeight>botSpace && topSpace>botSpace)
	{
		if (ddHeight>topSpace) ddHeight=topSpace
		ddTop=hbPos.Top-ddHeight;
		maxHeight=topSpace;
	}
	else
	{
		ddTop=hbPos.Bottom;
		maxHeight=botSpace;
		if (!g_isIE) maxHeight-=2;		
	}
	if (ddHeight>maxHeight) ddHeight=maxHeight;

	// set listbox size/pos
	listBox.style.left = ddLeft;
	listBox.style.top=ddTop;
	listBox.style.width=ddWidth;
	listBox.style.height=ddHeight;

	/*
	_DB_debug("----------------------");
	_DB_debug("ddWidth="+ddWidth);
	_DB_debug("ddHeight="+ddHeight);
	_DB_debug("listBox.style.width="+listBox.style.width);
	_DB_debug("listBox.style.height="+listBox.style.height);
	_DB_debug("listBox.scrollWidth="+listBox.scrollWidth);
	_DB_debug("listBox.scrollHeight="+listBox.scrollHeight);
	_DB_debug("listBox.clientWidth="+listBox.clientWidth);
	_DB_debug("listBox.clientHeight="+listBox.clientHeight);
	_DB_debug("listBox.scrollLeft="+listBox.scrollLeft);
	_DB_debug("listBox.scrollTop="+listBox.scrollTop);
	*/
	
	// adjust for scrollbars
	if (listBox.scrollWidth>listBox.clientWidth && listBox.scrollHeight>listBox.clientHeight)
	{
		ddHeight+=getScrollBarWidth();
		if (ddHeight>maxHeight) ddHeight=maxHeight;
		listBox.style.height=ddHeight;
	}
	if (listBox.scrollWidth>listBox.clientWidth && listBox.scrollHeight>listBox.clientHeight)
	{
		ddWidth+=getScrollBarWidth();
		if (ddWidth>maxWidth) ddWidth=maxWidth;
		listBox.style.width=ddWidth;
	}
	if (listBox.scrollWidth>listBox.clientWidth)
	{
		ddWidth+=getScrollBarWidth();
		if (ddWidth>maxWidth) ddWidth=maxWidth;
		listBox.style.width=ddWidth;
	}
	if (listBox.scrollHeight>listBox.clientHeight)
	{
		ddHeight+=getScrollBarWidth();
		if (ddHeight>maxHeight) ddHeight=maxHeight;
		listBox.style.height=ddHeight;
	}
	
	// Show blank iframe below listbox to prevent standard dropdown controls from displaying on-top (IE6 problem)
	var iframe = document.getElementById(fldName + "_iframe");
	if (iframe!=null)
	{
		iframe.style.display="block";
		iframe.style.left=ddLeft;
		iframe.style.top=ddTop;
		iframe.style.width=ddWidth;
		iframe.style.height=ddHeight;
	}	

	// store info about open filter
	g_openMSFilter = listBox;
	g_openMSFilterFieldName = fldName;
	g_openMSFilterInititialVals = getMSFieldValues(fldName);
}

// Dashboards page - Show checkbox multi-select dropdown box
function onClickMSFilterHeader(fldName)
{
	if (_DB_debugging) _DB_debug("onClickMSFilterHeader(fldName=" + fldName + ")");

	if ($("#" + fldName + "_header input").attr('disabled')) return;

	DashFltDisableAllBtns();

	var listBox = document.getElementById(fldName + "_list")
	if (listBox == null) return;

	var closingThis = (fldName == g_openMSFilterFieldName);

	// hide any visible filter lists, if any hidden then quit
	if (hideMSFilters('onClickMSFilterHeader') == true) return;

	if (closingThis) return;

	/* display transparant area to cover area below Filters - allows checklist to be closed by clicking on Item shown on Dashboard*/
	var dbCover = document.getElementById("dbCover");
	if (dbCover != null)
	{
		// cover dashboard page content pane
		var top = "0px"; height = "100%";
		var cp = document.getElementById("contentPane");
		if (cp != null)
		{
			var cpPos = GetObjectPosition(cp);
			top = cpPos.Top;
			height = cpPos.Height;
		}
		dbCover.style.display = "block";
		dbCover.style.top = top;
		dbCover.style.height = height;
	}

	// work out position and size of list based on text box
	var left = 0, top = 0, width = 0, height = 0, minWidth = 100;
	var headerBox = document.getElementById(fldName + "_header")
	var contextContent = document.getElementById("dbContextContent");
	if (headerBox != null && contextContent != null)
	{
		var headerBoxPosition = GetObjectPosition(headerBox);
		var pageHeadPosition = GetObjectPosition(contextContent);
		left = headerBoxPosition.Left;
		top = headerBoxPosition.Top + headerBox.offsetHeight;
		if (g_isIE)
		{
			top = top - pageHeadPosition.Top;
		}
		width = headerBox.offsetWidth;
		//alert(width);
		if (!g_isIE)
		{
			//firefox adjust
			top += 2;
			width -= 2;
		}
	}

	var maxheight = document.body.clientHeight - top - 2;
	if (maxheight < 0) maxheight = 0;

	// position and show it
	if (width < minWidth) width = minWidth;
	listBox.style.left = left;
	listBox.style.top = top;
	// listBox.style.width=width;
	listBox.style.display = "block";

	var isVertScrollbar = false;
	// make sure height fits on screen
	height = listBox.scrollHeight;
	if (height > maxheight)
	{
		height = maxheight;
		listBox.style.height = height;
		isVertScrollbar = true;
	}

	// set width
	var preferredWidth = listBox.clientWidth;
	if (isVertScrollbar) preferredWidth += getScrollBarWidth();
	if (preferredWidth > width) width = preferredWidth;
	//alert(width);
	listBox.style.width = width;

	// adjust for scrollbars
	if (listBox.scrollWidth > listBox.clientWidth)
	{
		width += getScrollBarWidth();
		listBox.style.width = width;
	}
	if (listBox.scrollHeight > listBox.clientHeight)
	{
		height += getScrollBarWidth();
		if (height > maxheight) height = maxheight;
		listBox.style.height = height;
	}

	// Show blank iframe below listbox to prevent standard dropdown controls from displaying on-top (IE6 problem)
	var iframe = document.getElementById(fldName + "_iframe");
	if (iframe != null)
	{
		iframe.style.display = "block";
		iframe.style.left = left;
		iframe.style.top = top;
		iframe.style.width = width;
		iframe.style.height = listBox.clientHeight + 2;
	}

	// store info about open filter
	g_openMSFilter = listBox;
	g_openMSFilterFieldName = fldName;
	g_openMSFilterInititialVals = getMSFieldValues(fldName);
}

// Handle (Select All) being ticked/unticked
function onClickMSFilterSelectAll(cb,fldName)
{
	if(_DB_debugging) _DB_debug("onClickMSFilterSelectAll(fldName="+fldName + ")");
	
	var flds =cb.form[fldName];
	if (flds!=null && flds.length!=0)
	{
		for (var i=0,c=cb.checked,l=flds.length; i<l; i++) flds[i].checked=c;
	}
}

// Get string consisting of 1's and 0's for each checkbox ticked/unticked
function getMSFieldValues(fldName)
{
	var flds=document.getElementsByName(fldName);
	var s="";
	if (flds!=null && flds.length!=0)
	{
		for (var i=0,l=flds.length; i<l; i++) s += (flds[i].checked ? "1" : "0");
	}
	return s;
}

// Get string consisting of comma separated ticked labels
function getMSFieldSelectedLabels(fldName)
{
	var flds=document.getElementsByName(fldName);
	var s="";
	if (flds!=null && flds.length!=0)
	{
		for (var i=0,l=flds.length; i<l; i++)
		{
			if(flds[i].checked)
			{
				if(s.length!=0) s+= ", ";
				s+=flds[i].value;
			}
		}
	}
	return s;
}
// Hide current visible checkbox multi-select dropdown list
// returns true if one is visible and has changed - if this is case will also resubmit page form
function hideMSFilters(callStr)
{
	if(_DB_debugging) _DB_debug("hideMSFilters("+callStr + ")");
	var submit=false;
	
	// if no filter open then quit
	if (g_openMSFilter==null) return submit;

	// populate item filters header box with items ticked
	var headerBox = document.getElementById(g_openMSFilterFieldName + "_headtxt");
	if (headerBox!=null)
	{
		headerBox.value=getMSFieldSelectedLabels(g_openMSFilterFieldName);
	}	

	// hide filter
	g_openMSFilter.style.display="none";
	var iframe=document.getElementById(g_openMSFilterFieldName+"_iframe");
	if (iframe!=null) iframe.style.display="none";

	var dbCover=document.getElementById("dbCover");
	if (dbCover!=null) dbCover.style.display="none";
	
	// if filter's checkboxes have changed since filter was shown then submit page
	if (g_openMSFilterInititialVals != getMSFieldValues(g_openMSFilterFieldName)) submit=true;

	// clear down info on open filter
	g_openMSFilter = null;	
	g_openMSFilterInititialVals = "";
	g_openMSFilterFieldName = null;

	// if dashboard page enable/disable filters
	if (document.db_page != null)
	{
		if (submit)
		{
			DashFltDisableAllBtns();
			DashFltUpdFiltersArea(this);
		}
		else
		{
			DashFltEnableAllBtns();
		}
	}
	
	return submit;
}

// Find Left and Top position of object
function GetObjectPosition(obj) 
{
	var w=obj.offsetWidth;
	var h=obj.offsetHeight;

	var x=0, y=0;
	while (obj != document.body)
	{
		x+=obj.offsetLeft;
		y+=obj.offsetTop;
		obj = obj.offsetParent;
	}
	x+=obj.offsetLeft;
	y+=obj.offsetTop;
	
	var x2=x+w;
	var y2=y+h;
	
	return {Left:x, Top:y, Right:x2, Bottom:y2, Width:w, Height:h};
}

// Try and determine width of scrollbar for browser
function getScrollBarWidth () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild (inner);
document.body.appendChild (outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild (outer);
return (w1 - w2 + 2); // add 2 for firefox
}

////////////////////////////////////////////////////////////////////////////
//Debug window
////////////////////////////////////////////////////////////////////////////
var _DB_debugging=false;
var _DB_console=null;
function _DB_debug(msg)
{
	if (_DB_console == null || _DB_console.closed)
	{
		_DB_console = window.open("","DIF_console","width=800,height=100,resizable,scrollbars=yes,left=0,top=0");
		_DB_console.document.open("text/plain");
		_DB_console.focus();
	}
	
	if (msg==null)
	{
		_DB_console.document.open("text/plain");
	}
	else
	{
		var d=new Date();
		var h=d.getHours();
		if (h<10) h= "0" + h;
		var m=d.getMinutes();
		if (m<10) m= "0" + m;		
		var s=d.getSeconds();
		if (s<10) s= "0" + s;		
		var ms=d.getMilliseconds();
		if (ms<10) ms= "00" + ms;
		else if (ms<100) ms= "0" + ms;
		var s = h + ":" + m  + ":" +  s  + ":" +  ms + " " + msg;
		_DB_console.document.writeln(s);
		_DB_console.scrollBy(0,50);
	}
}

////////////////////////////////////////////////////////////////////////////

function checkint(input, vf)
{
	var rval = true;
	if (vf != null && input.value == '')
	{
		if (input.value == null || input.value == '')
		{
			alert(g_msg_flt_ValueMustBeEntered);
			input.focus();
			return false;
		}
	}

	if (input.value != '')
	{
		var objRegExp = /(^-?\d\d*$)/;
		rval = objRegExp.test(input.value);

		if (rval == false)
		{
			alert(g_msg_flt_InvalidNumber + " " + input.value);
			input.focus();
		}
	}
	return rval;
}

function checkdate(input, vf)
{
	var rval = true;
	if (vf != null && input.value == '')
	{
		alert(g_msg_flt_ValueMustBeEntered);
		input.focus();
		return false;
	}

	if (input.value != '')
	{
		var validformat = /^\d{2}\/\d{2}\/\d{4}$/
		if (!validformat.test(input.value))
		{
			alert(g_msg_flt_InvalidDate_Line1 + " " + input.value + "\n\n" + g_msg_flt_InvalidDate_Line2);
			rval = false;
			input.focus();
		}
		else
		{
			var dayfield = input.value.split("/")[0];
			var monthfield = input.value.split("/")[1];
			var yearfield = input.value.split("/")[2];
			var dayobj = new Date(yearfield, monthfield - 1, dayfield)
			if ((dayobj.getMonth() + 1 != monthfield) || (dayobj.getDate() != dayfield) || (dayobj.getFullYear() != yearfield))
			{
				alert(g_msg_flt_InvalidDayMonthRange);
				rval = false;
				input.focus();
			}
		}
	}
	return rval;
}

function checkDecimal(input, vf)
{
	var rval = true;
	if (vf != null && vf == true)
	{
		if (input.value == null || input.value == '')
		{
			alert(g_msg_flt_ValueMustBeEntered);
			input.focus();
			return false;
		}
	}

	if (input.value != '')
	{
		var objRegExp = /^-?[0-9]+(\.[0-9]+)?$/;
		rval = objRegExp.test(input.value);

		if (rval == false)
		{
			alert(g_msg_flt_InvalidNumber + " " + input.value);
			input.focus();
		}
	}
	return rval;
}
