///////////////////////////////////////////////////////////////////////////////
//
// IsEmpty: Check whether string strVal is empty
//
///////////////////////////////////////////////////////////////////////////////

function IsEmpty(strVal)
{
    return ((strVal == null) || (strVal.length == 0));
}

///////////////////////////////////////////////////////////////////////////////
//
// RemoveTrailingSpaces
//
///////////////////////////////////////////////////////////////////////////////

function RemoveTrailingSpaces(strVal)
{
    var nPos = 0;

    if (IsEmpty(strVal))
        return strVal;

    for (nPos = strVal.length-1; nPos >= 0; nPos--)
    {
        if (whitespace.indexOf(strVal.charAt(nPos)) == -1)
            break;
    }

    return (nPos == strVal.length-1 ? strVal.substring(0) : strVal.substring(0, nPos+1));
}

///////////////////////////////////////////////////////////////////////////////
//
// RemoveLeadingSpaces
//
///////////////////////////////////////////////////////////////////////////////

function RemoveLeadingSpaces(strVal)
{
    var nPos = 0;

    if (IsEmpty(strVal))
        return strVal;

    for (nPos = 0; nPos < strVal.length; nPos++)
    {
        if (whitespace.indexOf(strVal.charAt(nPos)) == -1)
            break;
    }

    return strVal.substring(nPos);
}

///////////////////////////////////////////////////////////////////////////////
//
// RemoveSpaces
//
///////////////////////////////////////////////////////////////////////////////

function RemoveSpaces(strVal)
{
    return (IsEmpty(strVal) ? strVal:RemoveLeadingSpaces(RemoveTrailingSpaces(strVal)));
}

///////////////////////////////////////////////////////////////////////////////
//
// IsWhitespace: Check if string strVal has only the whitespace characters
//
///////////////////////////////////////////////////////////////////////////////

// whitespace characters: ' ', '\t', '\r', '\n'
var whitespace = " \t\n\r";

function IsWhitespace(strVal)
{
    var nPos = 0;

    if (IsEmpty(strVal))
        return false;

    for (nPos = 0; nPos < strVal.length; nPos++)
    {
        if (whitespace.indexOf(strVal.charAt(nPos)) == -1)
            return false;
    }

    return true;
}

///////////////////////////////////////////////////////////////////////////////
//
// Replace: replaces one occurrence of strVal with strWith in strSrc
//
///////////////////////////////////////////////////////////////////////////////

function Replace(strSrc, strVal, strWith)
{
    var nPos = 0, strLeft="", strRight="";

    // check if empty (or) no string is found to replace
    if (IsEmpty(strSrc) || (strSrc.indexOf(strVal) < 0))
        return strSrc;

    nPos = strSrc.indexOf(strVal);
    strLeft = strSrc.substring(0, nPos);
    nPos += strVal.length;
    strRight = strSrc.substring(nPos);

    return (strLeft + strWith + strRight);
}

///////////////////////////////////////////////////////////////////////////////
//
// ReplaceAll : replace all occurrences of strVal with strWith in strSrc
//
///////////////////////////////////////////////////////////////////////////////

function ReplaceAll(strSrc, strVal, strWith) {
    var strBuffer=strSrc;

    while (strBuffer.indexOf(strVal) >= 0)
        strBuffer = Replace(strBuffer, strVal, strWith);

    return (strBuffer);
}

///////////////////////////////////////////////////////////////////////////////
//
// Occurs: return no of occurrences of strVal within strSrc
//
///////////////////////////////////////////////////////////////////////////////

function Occurs(strVal, strSrc)
{
    var nCnt = 0, strBuffer=strSrc;

    while (strBuffer.indexOf(strVal) >= 0)
    {
        strBuffer = Replace(strBuffer, strVal, "");
        nCnt++;
    }

    return (nCnt);
}

///////////////////////////////////////////////////////////////////////////////
//
// NOTE: 
//  -- alway RemoveSpaces field value before calling any of these functions
//  -- if field is empty, the function call will return true
//
///////////////////////////////////////////////////////////////////////////////

// IsDigit: check if val has digits (0-9)
function IsDigit(val)
{
    var strBuffer = new String(val);
    var nPos = 0;

    if (IsEmpty(strBuffer))
        return false;

    for (nPos = 0; nPos < strBuffer.length; nPos++)
    {
        if (strBuffer.charAt(nPos) < '0' || strBuffer.charAt(nPos) > '9')
            return false;
    }

    return true;
}

// IsAlpha: check if val has alphabets only (a-z, A-Z)
function IsAlpha(val)
{
    var strBuffer = new String(val);
    var nPos = 0;

    if (IsEmpty(strBuffer))
        return false;

    for (nPos = 0; nPos < strBuffer.length; nPos++)
    {
        if (!((strBuffer.charAt(nPos) >= 'a' && strBuffer.charAt(nPos) <= 'z') ||
            (strBuffer.charAt(nPos) >= 'A' && strBuffer.charAt(nPos) <= 'Z')))
            return false;
    }

    return true;
}

// IsInteger: check if nVal is integer type
function IsInteger(nVal)
{
    var strBuffer = new String(nVal);
    var nPos = 0, nStart = 0;

    if (IsEmpty(strBuffer))
        return true;
    if (IsWhitespace(strBuffer))
        return false;

    // check if -ve or +ve sign occurs in the beginning
    if ((strBuffer.charAt(0) == '-') || (strBuffer.charAt(0) == '+'))
        nStart = 1;
    else
        nStart = 0;

    for (nPos = nStart; nPos < strBuffer.length; nPos++)
    {
        if (strBuffer.charAt(nPos) < '0' || strBuffer.charAt(nPos) > '9')
            return false;
    }
    return true;	
}

// IsFloat: check if fVal is floating-point type
//	LIMITATION: no scientific notation (for eg: xxxx.xxE+xx)
function IsFloat(fVal)
{
    var strBuffer = new String(fVal);
    var nPos = 0, nStart = 0;

    if (IsEmpty(strBuffer))
        return true;
    if (IsWhitespace(strBuffer))
        return false;

    // check if -ve or +ve sign occurs in the beginning
    if ((strBuffer.charAt(0) == '-') || (strBuffer.charAt(0) == '+'))
        nStart = 1;
    else
        nStart = 0;

    for (nPos = nStart; nPos < strBuffer.length; nPos++)
    {
        if ((strBuffer.charAt(nPos) < '0' || strBuffer.charAt(nPos) > '9') && 
            (strBuffer.charAt(nPos) != '.'))
            return false;
    }
    return true;
}


///////////////////////////////////////////////////////////////////////////////
//
// Commify
//
// The following function is used to add commas to a number
//
// Input:  Number to commify
// 
// Return: Commified number
//
///////////////////////////////////////////////////////////////////////////////

function Commify(tNum)
{
    var Num = tNum.toString();
    var newNum = "";
    var newNum2 = "";
    var count = 0;

    //check for decimal number
    //number ends with a decimal point
    if (Num.indexOf('.') != -1)
    {
        if (Num.indexOf('.') == Num.length-1)
            Num += "00";
        if (Num.indexOf('.') == Num.length-2) //number ends with a single digit
            Num += "0";

        var a = Num.split("."); 
        Num = a[0]; //the part we will commify
        var end = a[1]; //the decimal place we will ignore and add back later
    }
    else
    {
        var end = "00";
    }

    //this loop actually adds the commas 
    for (var k = Num.length-1; k >= 0; k--)
    {
        var oneChar = Num.charAt(k);
        if (count == 3)
        {
            newNum += ",";
            newNum += oneChar;
            count = 1;
            continue;
        }
        else
        {
            newNum += oneChar;
            count++;
        }
    }

    //re-reverse the string
    for (var k = newNum.length-1; k >= 0; k--)
    {
        var oneChar = newNum.charAt(k);
        newNum2 += oneChar;
    }

    // add dollar sign and decimal ending from above
    newNum2 = newNum2 + "." + end;
    return newNum2;
}

///////////////////////////////////////////////////////////////////////////////
//
// RoundNumber
//
// The following function is used to round real numbers to a
// a given precision.
//
// Input:  Number to round
//         Precision
//
// Return: Rounded number
//
///////////////////////////////////////////////////////////////////////////////

function RoundNumber(num, precision)
{
    var roundedNum, sign, oldNum, decimalValue;

    roundedNum = parseFloat(num);
    if (isNaN(roundedNum))
        return num;

    // Change neg numbers to positive for rounding and then change them back
    sign = roundedNum < 0.0? -1.0 : 1.0;
    roundedNum *= sign;

    // Move decimal point to the right according to the precision
    roundedNum *= Math.pow( 10, precision );
    oldNum = roundedNum;
    roundedNum = Math.floor( roundedNum );   
    decimalValue = oldNum - roundedNum;

    if ( decimalValue >= 0.499999999 )
        roundedNum += 1.0;

    // Move decimal point back to the correct position
    roundedNum /= Math.pow( 10, precision );

    // Put the correct sign back on the number
    if ( roundedNum != 0.0 )
        roundedNum *= sign;

    return roundedNum;
}

///////////////////////////////////////////////////////////////////////////////
//
// FormatNumber
//
// The following function is used to format a number to a specified precision.
//
// Input:  Number
//         Precision
//
// Return: Rounded number as a string
//
///////////////////////////////////////////////////////////////////////////////

function FormatNumber(num, precision)
{
    var rNum = RoundNumber( num, precision );
    var strNum = new String(rNum);
    var i = 0, decPos = 0;
    var decimalFound = false;
    var numPlaces = 0;

    for (i = 0; i < strNum.length; i++)
    {
        if (strNum.charAt(i) == '.')
        {
          decPos = i;
          decimalFound = true;
        }
    }

    if ( decimalFound )
        numPlaces = strNum.length - decPos - 1;
    else
        strNum += '.';

    for (i = numPlaces; i < precision; i++)
        strNum += '0';

    return strNum;
}

///////////////////////////////////////////////////////////////////////////////
//
// ConvertNumber
//
// The following function is used to convert a value to a number to a specified precision.
//
// Input:  Number or String
//         Precision
//
// Return: Rounded number as a string
//
///////////////////////////////////////////////////////////////////////////////

function ConvertNumber(objField, precision)
{
    if (IsEmpty(objField.value))
        objField.value = '0.00';

    if (!IsFloat(parseFloat(objField.value)))
        objField.value = "0.00";
    else
        objField.value = FormatNumber( objField.value, precision );
        
    return true;
}

///////////////////////////////////////////////////////////////////////////////
//
// ConvertToFloat
//
// The following function is used to convert a string to a float
//
// Input:  Number
//
// Return: Converted float
//
///////////////////////////////////////////////////////////////////////////////

function ConvertToFloat(str)
{
    var strBuffer = new String(str);
    var nPos = 0;
    var newStr = "";
    var digitFound = false;
    var negNum = false;

    RemoveSpaces( strBuffer );

    if ( IsEmpty( strBuffer ) )
        return( 0.0 );

    for (nPos = 0; nPos < strBuffer.length; nPos++)
    {
        var currChar = strBuffer.charAt(nPos);
        if (currChar != '(' && currChar != '$' &&
            currChar != ','&& currChar != ')')
        {
          if ( currChar >= '0' && currChar <= '9' )
            digitFound = true;
          newStr += currChar;
        }
        else if ( currChar == '(' )
          negNum = true;
    }

    if ( digitFound )
        return( negNum? parseFloat( newStr ) * -1.0 : parseFloat( newStr ) );
    else
        return( 0.0 );
}

///////////////////////////////////////////////////////////////////////////////
//
// CleanNumber
//
// The following function is used to strip dollar signs and commas from number
// strings
//
// Input:  String representation of a number
//
// Return: Rounded number as a string
//
///////////////////////////////////////////////////////////////////////////////

function CleanNumber(numStr)
{
    var strBuffer = new String(numStr);
    var newStr = "";
    var i = 0;

    for (i = 0; i < strBuffer.length; i++)
    {
        var currChar = strBuffer.charAt(i);
        if (currChar != '$' && currChar != ',')
          newStr += currChar;
    }

    return newStr;
}

///////////////////////////////////////////////////////////////////////////////
//
// PreLoadImage
//
// Preload the image for later use
//
// Input:  Image to preload
//
///////////////////////////////////////////////////////////////////////////////

function PreLoadImage(image)
{
    if ( document.images )
    {
        img = new Image();
        img.src = image;
    }
}

///////////////////////////////////////////////////////////////////////////////
//
// DisableField
//
// The following function disables the given element
//
///////////////////////////////////////////////////////////////////////////////

function DisableField ( field )
{
    field.disabled = !(field.disabled);
}

///////////////////////////////////////////////////////////////////////////////
//
// CancelEvent
//
// The following function cancels a window event
//
///////////////////////////////////////////////////////////////////////////////

function CancelEvent( bubble )
{
      window.event.returnValue = false;
      if ( bubble ) window.event.cancelBubble = true;
}

///////////////////////////////////////////////////////////////////////////////
//
// GetContainerWith
//
// Starting with the given node, find the nearest containing element
// with the specified tag name and style class.
//
///////////////////////////////////////////////////////////////////////////////

function GetContainerWith(node, tagName, className)
{
    while (node != null)
    {
        if (node.tagName != null && node.tagName == tagName &&
            HasClassName(node, className))
            return node;
        node = node.parentNode;
    }
    return node;
}

///////////////////////////////////////////////////////////////////////////////
//
// HasClassName
//
// Return true if the given element currently has the given class name.
//
///////////////////////////////////////////////////////////////////////////////

function HasClassName(el, name)
{
    var i, list;

    list = el.className.split(" ");
    for (i = 0; i < list.length; i++)
    {
        if (list[i] == name)
            return true;
    }
    return false;
}

///////////////////////////////////////////////////////////////////////////////
//
// RemoveClassName
//
// Remove the given class name from the element's className property.
//
///////////////////////////////////////////////////////////////////////////////

function RemoveClassName(el, name)
{
    var i, curList, newList;

    if (el.className == null)
        return;

    newList = new Array();
    curList = el.className.split(" ");
    for (i = 0; i < curList.length; i++)
    {
        if (curList[i] != name)
          newList.push(curList[i]);
    }
    el.className = newList.join(" ");
}

///////////////////////////////////////////////////////////////////////////////
//
// GetPageOffsetLeft
//
// Return the x coordinate of an element relative to the page.
//
///////////////////////////////////////////////////////////////////////////////

function GetPageOffsetLeft(el)
{
    var x;

    x = el.offsetLeft;
    if (el.offsetParent != null)
        x += GetPageOffsetLeft(el.offsetParent);

    return x;
}

///////////////////////////////////////////////////////////////////////////////
//
// GetPageOffsetTop
//
// Return the x coordinate of an element relative to the page.
//
///////////////////////////////////////////////////////////////////////////////

function GetPageOffsetTop(el)
{
    var y;

    y = el.offsetTop;
    if (el.offsetParent != null)
        y += GetPageOffsetTop(el.offsetParent);

    return y;
}

///////////////////////////////////////////////////////////////////////////////
//
// GetCurrentStyle
//
// Return the rendered style of the given element
//
///////////////////////////////////////////////////////////////////////////////

function GetCurrentStyle(el, strCssRule)
{
    var strValue = "";
    if (document.defaultView && document.defaultView.getComputedStyle)
        strValue = document.defaultView.getComputedStyle(el, "").getPropertyValue(strCssRule);
    else if (el.currentStyle)
    {
        strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1) { return p1.toUpperCase(); });
        strValue = el.currentStyle[strCssRule];
    }
    return strValue;
}

///////////////////////////////////////////////////////////////////////////////
//
// CheckElHidden
//
// Check to see if the given element is contained within a hidden object.  It
// traverses up the object tree until no parent is found, or until it finds
// a parent that is hidden.
//
// Input:  Element to check
//
// Return: true if 'hidden' found in object tree
//         false otherwise
//
///////////////////////////////////////////////////////////////////////////////

function CheckElHidden( el )
{
    if ( el )
    {
        if ( GetCurrentStyle(el, 'visibility') == 'hidden' )
            return true;

        var parentEl =  el.parentNode;
        while ( parentEl )
        {
            if ( GetCurrentStyle(parentEl, 'visibility') == 'hidden' )
                return true;
            parentEl = parentEl.parentNode;
        }
    }
    return false;
}

///////////////////////////////////////////////////////////////////////////////
//
// CheckElDisplay
//
// Check to see if the given element is contained within an object with the display
// set to none.
//
// Input:  Element to check
//
// Return: true if display none found in object tree false otherwise
//
///////////////////////////////////////////////////////////////////////////////

function CheckElDisplay(el, maxLevels)
{
    maxLevels = maxLevels? maxLevels : 100;

    if ( el )
    {
        if ( GetCurrentStyle(el, 'display') == 'none' )
            return true;

        var parentEl = el.parentNode;
        var levels = 1;
        while ( parentEl )
        {
            if (levels > maxLevels) break;

            if ( GetCurrentStyle(parentEl, 'display') == 'none' )
                return true;
            parentEl = parentEl.parentNode;
            levels++;
        }
    }
    return false;
}

///////////////////////////////////////////////////////////////////////////////
//
// GetEventSrc
//
// Get the source of the current window event
//
// Input:  Event
// 
// Return: event element
//
///////////////////////////////////////////////////////////////////////////////

function GetEventSrc(e)
{
    if (!e) e = window.event;
    if (e.target)
        return e.target;
    else if (e.srcElement)
        return e.srcElement;
}

///////////////////////////////////////////////////////////////////////////////
//
// GetObjPosition
//
// Get the position of the given object
//
// Input:  Object
// 
// Return: position structure
//
///////////////////////////////////////////////////////////////////////////////

function GetObjPosition( el )
{
    var SL = 0, ST = 0;
    var is_div = /^div$/i.test(el.tagName);
    if (is_div && el.scrollLeft)
        SL = el.scrollLeft;
    if (is_div && el.scrollTop)
        ST = el.scrollTop;
    var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
    if (el.offsetParent)
    {
        var tmp = GetObjPosition(el.offsetParent);
        r.x += tmp.x;
        r.y += tmp.y;
    }
    return r;
};

///////////////////////////////////////////////////////////////////////////////
//
// GetObjVisibility
//
// Get the visibility of the given object
//
// Input:  Object
// 
// Return: visibility
//
///////////////////////////////////////////////////////////////////////////////

function GetObjVisibility(obj)
{
    var value = obj.style.visibility;
    if (!value)
    {
        if (document.defaultView && typeof (document.defaultView.getComputedStyle) == "function")
        {
            value = '';
        }
        else if (obj.currentStyle)
            value = obj.currentStyle.visibility;
        else
            value = '';
    }
    return value;
}

///////////////////////////////////////////////////////////////////////////////
//
// HideShowCovered
//
// Set the visibility to 'hidden' for all tags that show through objects that
// draw over them
//
// Input:  Object that will be visible
// 
///////////////////////////////////////////////////////////////////////////////

function HideShowCovered( obj, saveName )
{
    var tags = new Array("applet", "iframe", "select");
    saveName = saveName? saveName : '__save_visibility';

    var p = GetObjPosition(obj);
    var EX1 = p.x;
    var EX2 = obj.offsetWidth + EX1;
    var EY1 = p.y;
    var EY2 = obj.offsetHeight + EY1;

    for (var k = tags.length; k > 0; )
    {
        var ar = document.getElementsByTagName(tags[--k]);
        var cc = null;

        for (var i = ar.length; i > 0;)
        {
            cc = ar[--i];
            if (!IsChildOfParent(cc, obj))
            {
                p = GetObjPosition(cc);
                var CX1 = p.x;
                var CX2 = cc.offsetWidth + CX1;
                var CY1 = p.y;
                var CY2 = cc.offsetHeight + CY1;

                if (self.hidden || (CX1 > EX2) || (CX2 < EX1) || (CY1 > EY2) || (CY2 < EY1))
                {
                    if (!cc[saveName])
                        cc[saveName] = GetObjVisibility(cc);
                    cc.style.visibility = cc[saveName];
                }
                else
                {
                    if (!cc[saveName])
                        cc[saveName] = GetObjVisibility(cc);
                    cc.style.visibility = "hidden";
                }
            }
        }
    }
}

///////////////////////////////////////////////////////////////////////////////
//
// MoveChildren
//
// Move the e_from object to be a child of e_to
//
///////////////////////////////////////////////////////////////////////////////

function MoveChildren(e_from, e_to)
{
    while(e_from.childNodes.length)
        e_to.appendChild(e_from.removeChild(e_from.childNodes[0]));
}

///////////////////////////////////////////////////////////////////////////////
//
// GetMouseCoords
//
// Get the mouse coordinates
//
// Input:  event
//
///////////////////////////////////////////////////////////////////////////////

function GetMouseCoords( e )
{
    if (!e)
        return { x:0, y:0 }

    if (e.pageX || e.pageY)
        return { x:e.pageX, y:e.pageY };

    var docScrollLeft = (document.documentElement)? document.documentElement.scrollLeft : document.body.scrollLeft;
    var docClientLeft = (document.documentElement)? document.documentElement.clientLeft : document.body.clientLeft;
    var docScrollTop = (document.documentElement)? document.documentElement.scrollTop : document.body.scrollTop;
    var docClientTop = (document.documentElement)? document.documentElement.clientTop : document.body.clientTop;

    return { x:e.clientX + docScrollLeft - docClientLeft,
             y:e.clientY + docScrollTop - docClientTop };
}

///////////////////////////////////////////////////////////////////////////////
//
// IsChildOfParent
//
// Check to see if the given element is a child of the given parent
//
// Input:  Element to check, parent
// 
// Return: true if element is a child of the parent false otherwise
//
///////////////////////////////////////////////////////////////////////////////

function IsChildOfParent( el, parent )
{
    if ( el && parent )
    {
        if ( el == parent )
            return true;

        var parentEl =  el.parentElement;
        while ( parentEl )
        {
            if ( parentEl == parent )
                return true;
            parentEl = parentEl.parentElement;
        }
    }
    return false;
}

///////////////////////////////////////////////////////////////////////////////
//
// FindPositionX
//
// Find the x position of the given object
//
///////////////////////////////////////////////////////////////////////////////

function FindPositionX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.x)
        curleft += obj.x;
    return curleft;
}

///////////////////////////////////////////////////////////////////////////////
//
// FindPositionY
//
// Find the y position of the given object
//
///////////////////////////////////////////////////////////////////////////////

function FindPositionY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    } else if (obj.y)
        curtop += obj.y;
    return curtop;
}

///////////////////////////////////////////////////////////////////////////////
//
// SetOpacity
//
///////////////////////////////////////////////////////////////////////////////

function SetOpacity(obj, opacity)
{
    opacity = (opacity == 100)? 99.999 : opacity;

    // IE/Win
    obj.style.filter = "alpha(opacity:"+opacity+")";

    // Safari < 1.2, Konqueror
    obj.style.KHTMLOpacity = opacity / 100;

    // Older Mozilla and Firefox
    obj.style.MozOpacity = opacity / 100;

    // Safari 1.2, newer Firefox and Mozilla, CSS3
    obj.style.opacity = opacity / 100;
}

///////////////////////////////////////////////////////////////////////////////
//
// WindowOpen
//
// Open a javascript window centered on the screen
//
///////////////////////////////////////////////////////////////////////////////

function WindowOpen(url, name, w, h)
{
    var wleft, wtop;
    if (w > screen.width)
    {
        w = screen.width;
        wleft = 0;
    }
    else
        wleft = (screen.width - w) / 2;

    if (h > (screen.height - 60))
    {
        h = screen.height - 60;
        wtop = 0;
    } else
        wtop = (screen.height - h) / 2;


    // IE5 and other old browsers might allow a window that is
    // partially offscreen or wider than the screen. Fix that.
    // (Newer browsers fix this for us, but let's be thorough.)
    if (wleft < 0)
    {
        w = screen.width;
        wleft = 0;
    }
    if (wtop < 0)
    {
        h = screen.height;
        wtop = 0;
    }

    var win = window.open(url, name,
    'width=' + w + ', height=' + h + ', ' +
    'left=' + wleft + ', top=' + wtop + ', ' +
    'location=yes, menubar=no, titlebar=no, directories=no ' +
    'status=yes, toolbar=no, scrollbars=yes, resizable=yes');

    // Just in case width and height are ignored
    win.resizeTo(w, h);

    // Just in case left and top are ignored
    win.moveTo(wleft, wtop);
    win.focus();

    return win;
}

///////////////////////////////////////////////////////////////////////////////
//
// BrowserDetect
//
///////////////////////////////////////////////////////////////////////////////

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: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			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();

///////////////////////////////////////////////////////////////////////////////
//
// GrayOutScreen
//
// Gray out / ungray the entire browser window
//
// Parameters:  vis      - true to gray out screen, false to ungray
//
//              options  - (optional)  This is a JSON object with the following (optional) properties
//                         opacity:0-100 (Lower number = less grayout higher = more of a blackout)
//                         zindex: # (HTML elements with a higher zindex appear on top of the gray out)
//                         bgcolor: (#xxxxxx) (Standard RGB Hex color code)
//
// Example:     GrayOutScreen(true, {'zindex':'50', 'bgcolor':'#0000FF', 'opacity':'70'});
//
///////////////////////////////////////////////////////////////////////////////

function GrayOutScreen(vis, options)
{
    var options = options || {};
    var zindex = options.zindex || 10000;
    var opacity = options.opacity || 60;
    var opaque = (opacity / 100);
    var bgcolor = options.bgcolor || '#000000';
    var dark=document.getElementById('darkScreenObj');
    var bodyObj = (document.documentElement)? document.documentElement : document.body;
    
    if (!dark)
    {
        // The dark layer doesn't exist, it's never been created.  So we'll
        // create it here and apply some basic styles.
        // If you are getting errors in IE see: http://support.microsoft.com/default.aspx/kb/927917
        var tbody = document.getElementsByTagName("body")[0];
        var tnode = document.createElement('div');        // Create the layer.
        tnode.style.position='absolute';                  // Position absolutely
        tnode.style.top='0px';                            // In the top
        tnode.style.left='0px';                           // Left corner of the page
        tnode.style.overflow='hidden';                    // Try to avoid making scroll bars
        tnode.style.display='none';                       // Start out Hidden
        tnode.id='darkScreenObj';                         // Name it so we can find it later
        tbody.appendChild(tnode);                         // Add it to the web page
        dark=document.getElementById('darkScreenObj');    // Get the object.
    }
    
    if (vis)
    {
        // Calculate the page height
        var browserWidth = CalculateBrowserWidth();
        var browserHeight = CalculateBrowserHeight();

        //Specific code needed for Triple Tree website
        var homePopup = document.getElementById('darkScreenObj');
        $(".homePopup").css("left", parseInt((browserWidth - 430) / 2) + "px");
        
        //set the shader to cover the entire page and make it visible.
        dark.style.opacity=opaque;
        dark.style.MozOpacity=opaque;
        dark.style.filter='alpha(opacity='+opacity+')';
        dark.style.zIndex=zindex;
        dark.style.backgroundColor=bgcolor;
        dark.style.width = browserWidth + 'px';
        dark.style.height= browserHeight + 'px';
        dark.style.display='block';
        
        //window.onscroll = function () { CancelEvent(); }
        //if (document.documentElement)
        //    document.documentElement.style.overflow = 'hidden';
        //else
        //    document.body.style.overflow = 'hidden';
        //ScrollFreeze.on();
    }
    else
    {
        dark.style.display='none';
        //if (document.documentElement)
        //    document.documentElement.style.overflow = '';
        //else
        //    document.body.style.overflow = '';
        //ScrollFreeze.off();
    }
}

function CalculateBrowserWidth()
{
    var browserWidth = 0;
    var pWidth1 = (window.innerWidth)? window.innerWidth : 0;
    var pWidth2 = (document.documentElement)? document.documentElement.clientWidth : 0;
    var pWidth3 = (document.body)? document.body.clientWidth : 0;
    var pWidth4 = (document.documentElement)? document.documentElement.scrollWidth : 0;
    var pWidth5 = (document.body)? document.body.scrollWidth : 0;
    
    browserWidth = (pWidth1 > pWidth2)? pWidth1 : pWidth2;
    browserWidth = (pWidth3 > browserWidth)? pWidth3 : browserWidth;
    browserWidth = (pWidth4 > browserWidth)? pWidth4 : browserWidth;
    browserWidth = (pWidth5 > browserWidth)? pWidth5 : browserWidth;
    
	return browserWidth;
}
        
function CalculateBrowserHeight()
{
    var browserHeight = 0;
    var pHeight1 = (window.innerHeight)? window.innerHeight : 0;
    var pHeight2 = (document.documentElement)? document.documentElement.clientHeight : 0;
    var pHeight3 = (document.body)? document.body.clientHeight : 0;
    var pHeight4 = (document.documentElement)? document.documentElement.scrollHeight : 0;
    var pHeight5 = (document.body)? document.body.scrollHeight : 0;
    
    browserHeight = (pHeight1 > pHeight2)? pHeight1 : pHeight2;
    browserHeight = (pHeight3 > browserHeight)? pHeight3 : browserHeight;
    browserHeight = (pHeight4 > browserHeight)? pHeight4 : browserHeight;
    browserHeight = (pHeight5 > browserHeight)? pHeight5 : browserHeight;
    
    return browserHeight;
}

function CalculateVisibleWidth()
{
    var visibleWidth = 0;
    var pWidth1 = (window.innerWidth && window.innerWidth > 0)? window.innerWidth : 9999999;
    var pWidth2 = (document.documentElement && document.documentElement.clientWidth > 0)? document.documentElement.clientWidth : 9999999;
    var pWidth3 = (document.body && document.body.clientWidth > 0)? document.body.clientWidth : 9999999;
    
    //alert("window.innerWidth = " + pWidth1 + " docElement.clientWidth = " + pWidth2 + " body.clientWidth = " + pWidth3);
    visibleWidth = (pWidth1 > pWidth2)? pWidth2 : pWidth1;
    visibleWidth = (pWidth3 > visibleWidth)? visibleWidth : pWidth3;
    
	return visibleWidth;
}
        
function CalculateVisibleHeight()
{
    var visibleHeight = 0;
    var pHeight1 = (window.innerHeight && window.innerHeight > 0)? window.innerHeight : 9999999;
    var pHeight2 = (document.documentElement && document.documentElement.clientHeight > 0)? document.documentElement.clientHeight : 9999999;
    var pHeight3 = (document.body && document.body.clientHeight > 0)? document.body.clientHeight : 9999999;
    
    //alert("window.innerHeight = " + pHeight1 + " docElement.clientHeight = " + pHeight2 + " body.clientHeight = " + pHeight3);
    visibleHeight = (pHeight1 > pHeight2)? pHeight2 : pHeight1;
    visibleHeight = (pHeight3 > visibleHeight)? visibleHeight : pHeight3;
    
    return visibleHeight;
}

function CalculateScrollLeft()
{
    var left = 0;
    var pLeft1 = (document.documentElement)? document.documentElement.scrollLeft : 0;
    var pLeft2 = (document.body)? document.body.scrollLeft : 0;
    
    left = (pLeft1 > pLeft2)? pLeft1 : pLeft2;
	return left;
}
        
function CalculateScrollTop()
{
    var top = 0;
    var pTop1 = (document.documentElement)? document.documentElement.scrollTop : 0;
    var pTop2 = (document.body)? document.body.scrollTop : 0;
    
    top = (pTop1 > pTop2)? pTop1 : pTop2;
    return top;
}
