﻿//<![CDATA[

// This function detects the user's browser
var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function isLeapYear(yr) {
    return !(yr % 4) && (yr % 100) || !(yr % 400) ? true : false;
}

// ******************************************************************
// This function accepts a string variable and verifies if it is a
// proper date or not. It validates format matching either
// mm-dd-yyyy or mm/dd/yyyy. Then it checks to make sure the month
// has the proper number of days, based on which month it is.

// The function returns true if a valid date, false if not.
// ******************************************************************
function isDate(d,convert) {
/// <summary>
///     This function accepts a string variable and verifies if it is a proper date.
///     It validates format matching either mm-dd-yyyy or mm/dd/yyyy. Then it checks
///     to make sure the month has the proper number of days, based on which month it is.
/// </summary>
/// <parm name="d" type="String">
///     This is the date to validate.
/// </parm>
/// <parm name="convert" type="Boolean">
///     Convert 2-digit year to 4-digit.
/// </parm>
/// <return type="Boolean"></return>

	var strDatestyle = "US"; //United States date style
	//var strDatestyle = "EU";  //European date style
	var strDate;
	var strDateArray;
	var strDay;
	var strMonth;
	var strYear;
	var intDay;
	var intMonth;
	var intYear;
	var booFound = false;
	var strSeparatorArray = new Array("-"," ","/",".");
	var intElementNr;
	var err = 0;
	var strMonthArray = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
	strDate = new String(d);
	if (strDate.length < 1) {
		return false;
	}
	if (strDate.toLowerCase()=="today" || strDate.toLowerCase()=="now"){return true;}

	for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
		if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
			strDateArray = strDate.split(strSeparatorArray[intElementNr]);
			if (strDateArray.length != 3) 
			{
				err = 1;
				return false;
			}
			else 
			{
				strDay = strDateArray[0];
				strMonth = strDateArray[1];
				strYear = strDateArray[2];
			}
			booFound = true;
		}
	}

	if (booFound == false) {
		if (strDate.length>5) {
			strDay = strDate.substr(0, 2);
			strMonth = strDate.substr(2, 2);
			strYear = strDate.substr(4);
		}
		else
			return false;
	}
	
	// verify year part	2 or 4 digits
	if (strYear.length != 2 && strYear.length != 4) {return false;}
	if (isNaN(strYear)){return false;}
	// US style (swap month and day)
	if (strDatestyle == "US") {
		strTemp = strDay;
		strDay = strMonth;
		strMonth = strTemp;
	}

	// verify 1 or 2 digit integer day
	if (strDay.length<1 || strDay.length>2) {return false;}
	if (isNaN(strDay)){return false;}
	
	// month may be digits of characters, hence following check
	intMonth = parseInt(strMonth, 10);
	if (isNaN(intMonth)) {
		for (i = 0;i<12;i++) {
			if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
				intMonth = i+1;
				strMonth = strMonthArray[i];
				i = 12;
			}
		}
		if (isNaN(intMonth)) {
			err = 3;
			return false;
		}
	}

	intDay=parseInt(strDay,10);
	intYear = parseInt(strYear, 10);
	
	if (intMonth>12 || intMonth<1) {
		err = 5;
		return false;
	}
	
	// day in month check
	if (intDay < 1 || intDay > 31){return false;}
		
	if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30)) {
		return false;
	}
	
	if (intMonth == 2) {
		if (isLeapYear(intYear)) {
			if (intDay > 29) {return false;}
		}
		else 
		{
			if (intDay > 28) {return false;}
		}
	}
	
	if (!convert)
		return true;
	else
	{
		if (intYear<=99){intYear=intYear+2000;}
		return intDay+"/"+intMonth+"/"+intYear;
	}
// }

    if (month == 2) { // check for february 29th
    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
        if (day > 29 || (day==29 && !isleap)) {
            alert("February " + year + " doesn`t have " + day + " days!");
            return false;
        }
    }
    return true; // date is valid
}
//=========================================================================
// Checks if time is in HH:MM:SS AM/PM format.
// The seconds and AM/PM are optional.
//=========================================================================
function isTime(timeStr, cutOffHour, useMilitaryTime) {
/// <summary>
///     Checks if time is in HH:MM:SS AM/PM format.
///     The seconds and AM/PM are optional.
/// </summary>
/// <parm name="timeStr" type="String">
///     This is the time string to validate.
/// </parm>
/// <parm name="cutOffHour" type="Integer">
///     Used to default am/pm.
/// </parm>
/// <return type="Boolean"></return>
    var timePat = /^(\d{1,2}):(\d{2})(:(\d{2}))?(\s?(AM|am|PM|pm))?$/;

    var matchArray = timeStr.match(timePat);
    if (matchArray == null) {
        alert("Time is not in a valid format.");
        return false;
    }
    
    if (cutOffHour < 0 || cutOffHour > 12)
        {cutOffHour = 7;}
    hour = matchArray[1];
    minute = matchArray[2];
    second = matchArray[4];
    ampm = matchArray[6];

    if (second=="") { second = null; }
    if (ampm=="") { ampm = null; }

    // try to put default am or pm
    if (hour < cutOffHour && hour > 0 && ampm==null)
        {ampm = "pm";}
    if (hour >= cutOffHour && hour < 13 && ampm==null)
        {ampm = "am";}
    
    if (hour < 0  || hour > 23) {
        alert("Hour must be between 1 and 12. (or 0 and 23 for military time)");
        return false;
    }
    if (useMilitaryTime == true)
    {
		if (hour <= 12 && ampm == null)
			ampm = "am";
    }
    else
    {
	    if (hour <= 12 && ampm == null) {
		    if (confirm("Please indicate which time format you are using.  OK = Standard Time, CANCEL = Military Time")) {
			    alert("You must specify AM or PM.");
				return false;
			}
	    }
    }
    if  (hour > 12 && ampm != null) {
        alert("You can't specify AM or PM for military time.");
        return false;
    }
    if (minute<0 || minute > 59) {
        alert ("Minute must be between 0 and 59.");
        return false;
    }
    if (second != null && (second < 0 || second > 59)) {
        alert ("Second must be between 0 and 59.");
        return false;
    }
    // if all OK-
    return true;
}

//=================================================================================
function isControlValidDateTime (source, arguments)
{
/// <summary>
///     This function is specifically called from controls such as text boxes.
///     It will check the data for valid date or time.
/// </summary>
/// <parm name="source" type="Object">
///     This is the the control object - not used by this function , but must be declared.
/// </parm>
/// <parm name="arguments" type="Object">
///     This is a structure that includes the Value passed, and IsValid boolean flag.
/// </parm>
/// <return type="Boolean"></return>

    if (isDate(arguments.Value, false))
    {
        arguments.IsValid = true;
    }
    else
    {
        // if it is not a date, try time
        if (isTime(arguments.Value, 7))
        {
            arguments.IsValid = true;
        }
        else 
            arguments.IsValid = false;
    }
}

//=================================================================================
function isControlValidPassword (source, arguments)
{
/// <summary>
///     This function is specifically called from controls such as text boxes.
///     It will check the data for valid password.
/// </summary>
/// <parm name="source" type="Object">
///     This is the the control object - not used by this function , but must be declared.
/// </parm>
/// <parm name="arguments" type="Object">
///     This is a structure that includes the Value passed, and IsValid boolean flag.
/// </parm>
/// <return type="Boolean"></return>

    if (isPasswordValid(arguments.Value) == true)
    {
        arguments.IsValid = true;
    }
    else
    {
        arguments.IsValid = false;
    }
}

//=================================================================================
function SetFocus (controlName)
{
/// <summary>
///     Set focus to a specific control.
/// </summary>
/// <parm name="controlName" type="Object">
///     This is the the control object.
/// </parm>

    if (controlName != null) {
        controlName.focus();
    }   
}

//=================================================================================
function newWindow (sURL, sTarget, options)
{
/// <summary>
///     Open a new window.
/// </summary>
/// <parm name="sURL" type="String">
///     This is the URL for the page.
/// </parm>
/// <parm name="sTarget" type="String">
///     Optional. String that specifies the name of the window. This name is used as the value for the TARGET attribute on a form or an a element._blank The sURL is loaded into a new, unnamed window. 
///     _media: The url is loaded in the Media Bar in Microsoft Internet Explorer 6. Microsoft Windows XP Service Pack 2 (SP2) and later. This feature is no longer supported. By default the url is loaded into a new browser window or tab. 
///     _parent: The sURL is loaded into the current frame's parent. If the frame has no parent, this value acts as the value _self. 
///     _search: Disabled in Windows Internet Explorer 7, see Security and Compatibility in Internet Explorer 7 for details. Otherwise, the sURL is opened in the browser's search pane in Internet Explorer 5 or later. 
///     _self: The current document is replaced with the specified sURL . 
///     _top: sURL replaces any framesets that may be loaded. If there are no framesets defined, this value acts as the value _self. 
/// </parm>
/// <parm name="options" type="String">
///     channelmode = { yes | no | 1 | 0 }
///     directories = { yes | no | 1 | 0 }
///     fullscreen = { yes | no | 1 | 0 }
///     height = number
///     left = number
///     location = { yes | no | 1 | 0 }
///     menubar = { yes | no | 1 | 0 }
///     resizable = { yes | no | 1 | 0 }
///     scrollbars = { yes | no | 1 | 0 }
///     status = { yes | no | 1 | 0 }
///     titlebar = { yes | no | 1 | 0 }
///     toolbar = { yes | no | 1 | 0 }
///     top = number
///     width = number
/// </parm>
/// <return type="Object"></return>
    var w = window.open(sURL, sTarget, options);
    return w;
}

//=================================================================================
function isPasswordValid (sPassword)
{
/// <summary>
///     Check if password is valid
/// </summary>
/// <parm name="sPassword" type="String">
///     Password to validate.
/// </parm>
/// <return type="Boolean"></return>

    var s = new String(sPassword);
    if (s.length < 7)
        {return false;}
    var nonWordChar = /[\W]/i;
    if (nonWordChar.test(s) == true)
        {return true;}
}

//=================================================================================
// The next 3 functions work together to create an XmlHttp call to server, which
// call the specified page, and should return a value, that is placed in variable
// resultText.
var resultText;
var elemObj;

function doXmlHttp (url, elemName)
{
/// <summary>
///     create an XmlHttp call to server, which call the specified page, and should 
///     return a value, that is placed in variable resultText.
/// </summary>
/// <parm name="url" type="String">
///     Page URL to call.
/// </parm>
/// <parm name="elemName" type="String">
///     Element name whose innerText will be modified with the return text.
/// </parm>

    resultText = "";
    elemObj = document.getElementById(elemName);
    
    var xmlHttp=GetXmlHttpObject();
    if (xmlHttp==null)
    {
        alert ("Browser does not support HTTP Requests.");
        return;
    }
    xmlHttp.onreadystatechange=stateChanged 
    xmlHttp.open("GET",url,true)
    xmlHttp.send(null)
}

function stateChanged()
{
    if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
    { 
        resultText = xmlHttp.responseText;
        if (elemObj != null)
        {
            elemObj.innerHTML = resultText;
        }
    }
}

function GetXmlHttpObject(handler)
{
    var req = null;
    
	try
	{
		req = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(oc)
		{
			req = null;
		}
	}

	if(!req && typeof XMLHttpRequest != "undefined")
	{
		req = new XMLHttpRequest();
	}
		
	return req;
}

//=================================================================================
function rgbToHex (red, green, blue)
{
/// <summary>
///     Convert RGB values to hex.
/// </summary>
/// <parm name="red" type="Integer">
///     Red value (0-255).
/// </parm>
/// <parm name="green" type="Integer">
///     Green value (0-255).
/// </parm>
/// <parm name="blue" type="Integer">
///     Blue value (0-255).
/// </parm>
/// <return type="String"></return>

    var rr;
    var gg;
    var bb;
    
    // Check for valid numbers
    if (isNaN(red))
        red = 255;
    if (isNaN(green))
        green = 255;
    if (isNaN(blue))
        blue = 255;
    // check ranges
    if (red < 0)
        red = 0;
    if (red > 255)
        red = 255;
    if (green < 0)
        green = 0;
    if (green > 255)
        green = 255;
    if (blue < 0)
        blue = 0;
    if (blue > 255)
        blue = 255;
    
    var hexColor = "#FFFFFF";
    var RGB = new Array(256);
    var k = 0;
    var hex = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F");
    // Initialize arrays
    for (i = 0; i < 16; i++)
    {	
    	for (j = 0; j < 16; j++)
    	{		
		    RGB[k] = hex[i] + hex[j];
		    k++;
	    }
    }
    
    // Convert
	rr = dropLeadingZeros(red.toString());
	gg = dropLeadingZeros(green.toString());
	bb = dropLeadingZeros(blue.toString());
	rr = RGB[rr]
	gg = RGB[gg]
	bb = RGB[bb]
	hexColor = "#" + rr + gg + bb;
    
    return hexColor;
}

//=================================================================================
function dropLeadingZeros(num)
{
/// <summary>
///     Drop leading zeros from number.
/// </summary>
/// <parm name="num" type="String">
///     The number to use.
/// </parm>
/// <return type="String"></return>

	while (num.charAt(0) == "0")
	{
		newTerm = num.substring(1, num.length);
		num = newTerm;
	}
	if (num == "") 
		num = "0";
	return num;
}

//=================================================================================
function getWindowHeight()
{
/// <summary>
///     Get window height.
/// </summary>
/// <return type="Integer"></return>

    var windowHeight = 0;
    if ( typeof( window.innerHeight ) == 'number' )
    {
        //Non-IE
        windowHeight = window.innerHeight;
    }
    else if( document.documentElement && document.documentElement.clientHeight )
    {
        //IE 6+ in 'standards compliant mode
        windowHeight = document.documentElement.clientHeight;
    }
    else if( document.body && document.body.clientHeight )
    {
        //IE 4 compatible
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}

//=================================================================================
function getWindowWidth()
{
/// <summary>
///     Get window width.
/// </summary>
/// <return type="Integer"></return>

    var windowWidth = 0;
    if( typeof( window.innerWidth ) == 'number' )
    {
        //Non-IE. 16 takes into account scrollbars.
        windowWidth = window.innerWidth - 16;
    }
    else if( document.documentElement && document.documentElement.clientWidth )
    {
        //IE 6+ in 'standards compliant mode
        // 20 takes into account scrollbars.
        windowWidth = document.documentElement.clientWidth - 20;
    }
    else if( document.body && document.body.clientWidth  )
    {
        //IE 4 compatible
        // 20 takes into account scrollbars.
        windowWidth = document.body.clientWidth - 20;
    }
    return windowWidth;
}


function positionDiv (divName, offsetMore)
{
    var w;
    var myDiv = null;
    myDiv = document.getElementById(divName);
    if (myDiv != null)
    {
        myDiv.style.width = "30%";
        myDiv.style.pixelTop = 205;
        myDiv.style.position = "fixed";
        myDiv.style.backgroundColor = "White";

        w = getWindowWidth() - myDiv.style.pixelWidth - 25;
        if (offsetMore == 1)
        {
            w = w - 15;
        }
        myDiv.style.pixelLeft = w;
        return true;
    }
    else
    {
        return false;
    }   
}

function doOnResize (divName)
{
    window.onresize = function ()
    {
        positionDiv (divName,0);
    }
}

function getClientDateTime(delimiter)
{
	///<summary>Get the Client's date and time.</summary>
	///<param name="" type="">Delimiter character. If non specified, default is #.</param>
	///<return type="string">Returns the client's date and time in the format #mm/dd/yyyy hh:mm:ss#</return>
	
    // get current date and time
    var now = new Date();
    if (delimiter == null)
		delimiter = "#";
    // format is #mm/dd/yyyy hh:mm:ss#
	var ret = delimiter + (now.getMonth()+1) + "/" + now.getDate() + "/" + now.getFullYear() + " " + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds() + delimiter;
	// return the formatted string
    return ret;
}

function resizeContentPanel(panelID, minContentHeight)
{
    if ((minContentHeight == undefined) || (minContentHeight == null) || (isNaN(minContentHeight)) || (minContentHeight<=0))
		minContentHeight = 332;
	var p = document.getElementById(panelID);
	if (BrowserDetect.browser == "Firefox")
		minContentHeight = 332;
	if (parseInt(p.offsetHeight) < minContentHeight) {
	    p.style.minHeight = minContentHeight + "px";
	}
}

function changeProgressText(newText, divName)
{
    if (divName == undefined || divName == null || divName == "")
		divName = "ProgressTextDiv";
	var divObj = document.getElementById(divName);
	if (divObj)
	{
		if (newText == null || newText == "")
			newText = "Working . . .";
		divObj.innerText = newText;
	}
	return true;
}

var doNotOverlay;
function doOverlayPage()
{
	var oDiv;
	var upDiv;
	oDiv = document.getElementById("MasterOverlayPage");
	upDiv = document.getElementById("UpdateProgressDiv");
	if (oDiv)
	{
		if (doNotOverlay == true)
		{
			oDiv.style.opacity = 0.0;
			oDiv.style.filter = 'alpha(opacity=0)';
			if (upDiv)
				upDiv.style.visibility = "hidden";
		}
		else
		{
			// Toggle the value of visibility.
			if (oDiv.style.visibility == "visible")
				oDiv.style.visibility = "hidden";
			else
				oDiv.style.visibility = "visible";
		}
	}
	else
	{
		if (doNotOverlay == true)
		{
			if (upDiv)
				upDiv.style.visibility = "hidden";
		}
	}
	return true;
}

function BeginPageRequest(sender, args)
{
		doOverlayPage();
}

function EndPageRequest(sender, args)
{
	doOverlayPage();
	changeProgressText("");
}

function dateDiff(fromDate, fromTime, toDate, toTime, militaryTime)
{
	// NOTE: lblXXXXXXX variables are defined adn set in server VB.
	date1 = new Date();
	date2 = new Date();
	diff  = new Date();

	if (isDate(fromDate) && isTime(fromTime, -1, militaryTime))
	{ // Validates first date 
		date1temp = new Date(fromDate + " " + fromTime);
		date1.setTime(date1temp.getTime());
	}
	else return false; // otherwise exits

	if (isDate(toDate) && isTime(toTime, -1, militaryTime))
	{ // Validates second date 
		date2temp = new Date(toDate + " " + toTime);
		date2.setTime(date2temp.getTime());
	}
	else return false; // otherwise exits

	// sets difference date to difference of first date and second date

	diff.setTime(Math.abs(date1.getTime() - date2.getTime()));
	timediff = diff.getTime();

	return timediff;
		
}

function startUp()
{
	// This little block prevents a bug in IE7 that causes an infinite loop on
	// window.resize when the document is first loaded (i.e., onload).
	if (navigator.userAgent.indexOf('MSIE') != -1)
	{
	    var newobject = document.createElement('DIV');
	    if (newobject) {
		    newobject.id = 'blankregion';
		    newobject.style.position = 'absolute';
		    newobject.style.visibility = 'visible';
		    newobject.style.display = 'block';
		    newobject.style.height = '0px';
		    newobject.style.width = '0px';
		    newobject.innerHTML = '&nbsp;';
		    document.body.appendChild(newobject);
	    }
	}
	// Detect and disable Right-Click
	detectRclick();
}

function setItemDesc(hfName) {
    var hf;
    var itemObj;
    itemObj = document.getElementById("itemDesc");
    if (hfName) {
        if (hfName != "") {
            hf = document.getElementById(hfName);
            itemObj.innerHTML = hf.value;
        }
        else {
            itemObj.innerHTML = "";
        }
    }
    else {
        itemObj.innerHTML = "";
    }
}

//]]>