﻿/*******************************************************************************
**          Change History
*******************************************************************************
**    Date:       Author:           Description:
**    --------    --------    ---------------------------------------
**    When        WHO         what/why    
        7/8/08      TS          added setLineBreakMessage method as a fix for linebreaks in FireFox (story 2207)
*******************************************************************************/ 


/************************************************************************  
                                    Vars
**************************************************************************/
var confirmDialogElement = null;
var alertDialogElement = null;
var isWaitDialogShowing = false;
var secretQuestionsElement = null;
var defaultTimerIntervalInSeconds = 15;
var uniqueIdPostFixForContentCopy = 0;
var commonNetworkDisplayFormat = '{0} ({1}_{2})';

var hrefVoidLink = 'javascript:void(0);';
var maxEnviromentNameLength = 50;
var minMultiAuthenticationPinLength = 4;

var _isUserAuthenticated = false;
var _isOfficer = false;

var iconPath = '../App_Themes/Standard/Images/Icons/';
var _applicationPhotoGalleryWebPath = 'http://www.secondIInonemc.com/photos/';
var _applicationFilesWebPath = 'http://www.secondIInonemc.com/files/';
var _applicationWebPath = 'http://www.secondIInonemc.com/';
 
/************************************************************************ 
                                    Enums
**************************************************************************/
var SortOrder =
{
    Ascending: 0,
    Descending: 1
};

var CountryCodes =
{
    US : 1
}

var FormatTemplates =
{
    PhoneFormat : '+1 (xxx) xxx-{0}',
    PhoneWithExtensionFormat : '+1 (xxx) xxx-{0}  ext. {1}'
};

var LayoutElementsJQ =
{
    JQDivError: '#divError',
    JQLayoutContent: '#divLayoutContent',
    JQWaitDialog: '#divWaitDialog',
    JQModalDialog: '#modalBackgroundWait',
    JQAlertDialog: '#alertContainer'
}

var LayoutElements =
{
    DivError: 'divError',
    LayoutContent: 'divLayoutContent',
    WaitDialog: 'divWaitDialog',
    ModalDialog: 'modalBackgroundWait',
    AlertDialog: 'alertContainer'
}

var CommonElements =
{
    Body : 'body',
    BtnAlertClose : 'btnAlertClose',
    BtnConfirmCancel : 'btnConfirmCancel',
    BtnConfirmOk : 'btnConfirmOk',
    DivAlertBox : 'divAlertBox',
    DivAlertMessage : 'divAlertMessage',
    DivConfirmationMessage : 'divConfirmationMessage',
    DivInformationMessage : 'divInformationMessage',
    LblWaitOperation : 'lblWaitOperation',
    BtnInformationClose : 'btnInformationClose'
};

var WizardTabNavigation = 
{ 
    Back : 'back', 
    Next : 'next'
};

var CommonImages =
{
    Error : 'error48.gif',
    Completed : 'completed48.gif'
};

var HttpProtocol =
{
    Http : 'http://',
    Https : 'https://'
};

var ConsoleConnectTypes =
{
    ConsoleConnect : 'ConsoleConnect'
};

var AutoRefreshEntityType = 
{
    PublicIPServices : 0,
    ServerNodeServices : 1,
    Servers : 2
};

var ExceptionTypes =
{
    InvalidUserState: 'jitu.secondIInone.Services.UI.ServiceImplementation.InvalidUserStateException'
};

var ButtonAttributes = 
{
    OldTitle : 'oldTitle'
};

var LinkAttributes = 
{
    HrefLink : 'hrefLink'
};

var EnviromentNameAndTooltip = 
{
    Name : '',
    ToolTip : ''
};

var HtmlElementAttributes =
{
    Id : 'id',
    Class : 'class'
}

this.windowsDefaultAlert = window.alert;

/************************************************************************ 
                                   Functions
**************************************************************************/
function capitalizeWords(stringToCapitalize) {
    var tmpStr;
    var tmpChar;
    var preString;
    var postString;
    var strlen;
    
    tmpStr = stringToCapitalize.toLowerCase();
    stringLen = tmpStr.length;
    
    if (stringLen > 0) {
        for (i = 0; i < stringLen; i++) {
            if (i == 0) {
                tmpChar = tmpStr.substring(0, 1).toUpperCase();
                postString = tmpStr.substring(1, stringLen);
                tmpStr = tmpChar + postString;
            }
            else {
                tmpChar = tmpStr.substring(i, i + 1);
                if ((tmpChar == " " || tmpChar == "-") && i < (stringLen - 1)) {
                    tmpChar = tmpStr.substring(i + 1, i + 2).toUpperCase();
                    preString = tmpStr.substring(0, i + 1);
                    postString = tmpStr.substring(i + 2, stringLen);
                    tmpStr = preString + tmpChar + postString;
                }
            }
        }
    }
    
    return tmpStr;
}

function onSecondIINoneCommonError(result) {
    var problems = new Array();
    problems[problems.length] = result.get_message();
    setErrorInformation($get(LayoutElements.DivError), problems);

    hideWaitDialog();
}

function populateSecondIINoneOrganizations(element, organizations) {
    if (organizations.length > 0 && element.options.length == 0) {
        var optOrganizationSelect = new Option(InformationMessages.Select, 0, false, false);
        element.options[element.options.length] = optOrganizationSelect;

        for (var rowCount = 0; rowCount < organizations.length; rowCount++) {

            var optOrganization = new Option(organizations[rowCount], rowCount + 1, false, false);
            element.options[element.options.length] = optOrganization;
        }
    }
}

function populateSecondIINoneOrganizationsWithSelectedOrganizationId(element, organizations, selectedOrganizationId) {
    if (organizations.length > 0 && element.options.length == 0) {
        var optOrganizationSelect = new Option(InformationMessages.Select, 0, false, false);
        element.options[element.options.length] = optOrganizationSelect;

        for (var rowCount = 0; rowCount < organizations.length; rowCount++) {

            if (selectedOrganizationId == rowCount + 1) {
                var optOrganization = new Option(organizations[rowCount], rowCount + 1, false, true);
                element.options[element.options.length] = optOrganization;
            }
            else {
                var optOrganization = new Option(organizations[rowCount], rowCount + 1, false, false);
                element.options[element.options.length] = optOrganization;
            }
        }
    }
}

function checkUserRole(userRole) {

    var showManageLinks = false;

    if(userRole!='court' && userRole!='')
        showManageLinks = true;

    return showManageLinks;
}

function isZipCodeValid(zipCode) {
    var isZipValid = true;

    if (!RegularExpressions.ZipCode.test(zipCode)) {
        isZipValid = false;
    }
    
    return isZipValid;
}

function isEmailValid(email) {
    var isEmailAddressValid = true;

    if (email.length > 0) {
        if (!RegularExpressions.Email.test(email)) {
            isEmailAddressValid = false;
        }
    }

    return isEmailAddressValid;
}

function isPhoneNumberValid(phoneNumber) {
    var isPhoneValid = true;

    if (phoneNumber.length > 0) {
        if (!RegularExpressions.PhoneNumber.test(phoneNumber)) {
            isPhoneValid = false;
        }
    }

    return isPhoneValid;
}

function isWebAddressValid(webAddress) {
    var isWebSiteAddressValid = true;

    if (webAddress.length > 0) {
        if (!RegularExpressions.URL.test(webAddress)) {
            isWebSiteAddressValid = false;
        }
    }

    return isWebSiteAddressValid;
}

//Script sniffs for IE7 on resize and reminds browser to apply relative positioning
//function positionRelative() {
//	$('.container').attr("style","position:relative;");
//}
//$(window).bind('resize', function () {
//    if ( $.browser.msie ) 
//        { 
//        var version = parseInt( $.browser.version, 10 );
//        if ( version > 7 ) 
//            { 
//                return false; 
//            } 
//        else if ( version == 7 ) 
//            { 
//            positionRelative()
//            } 
//        }
//    return true;
//});

function setSelectedDropDownListIndex(element, selectedValue) {
    for (var i = 0; i < element.length; i++) {
        if (element.options[i].value == selectedValue || element.options[i].text == selectedValue) {
            element.options[i].selected = true;
            break;
        }
    }
    
    return true;
}	

if (document.getElementById) 
{
    window.alert = 
        function(message) 
        {
            showAlert(message);
        }
}

function sortStandardDropDownByDisplayText(dropDownElement, includeFirstItem)
{
    var storedOptions = new Array(); //put dropdown items here so we can sort them
    var startIndex = 0;

    if (includeFirstItem != true)
    {
        var firstOption = dropDownElement.options[0]; // take first option off the list...its a select me option.
        startIndex = 1;
    }

    //loop through all available items options...
    for (i = startIndex; i < dropDownElement.options.length; i++)
    {
        var thisOption = dropDownElement.options[i]; //get the option
        storedOptions[i - 1] = new Array();
        storedOptions[i - 1][1] = thisOption.value; //get its' text and put it in the array
        storedOptions[i - 1][0] = thisOption.text;
    }

    storedOptions.sort(function(x,y){ 
      var a = String(x).toUpperCase(); 
      var b = String(y).toUpperCase(); 
      if (a > b) 
         return 1 
      if (a < b) 
         return -1 
      return 0; 
    }); //sort the array
    
    if (includeFirstItem != true)
    {
        initializeDropDown(dropDownElement, firstOption.text, firstOption.value, false, true);
    }
    else
    {
        dropDownElement.options.length = 0;
    }

    //Pull from the array and start putting them back in the list
    for (i = 0; i < storedOptions.length; i++)
    {
        var newOption = new Option(storedOptions[i][0], storedOptions[i][1], false, false);
        dropDownElement.options[dropDownElement.options.length] = newOption;
    }
}

function showModalPopup(modalPopupBehavior)
{
    //the following fix is put in place b'coz IE acts wierd, 
    //if the window has scroll bar and is not at the top
//    if ( $.browser.msie )
//    {
//        window.scrollTo(0,0);
//    }
    modalPopupBehavior.show();
    //positionDialog($get(modalPopupBehavior._PopupControlID));
}

function isTokenValid(token)
{
    var tokenLength = 36;
    return (trimString(token).length == tokenLength);
}
	
function showAlert(alertMessage, onCloseFunction) 
{
    var bodyElement = document.getElementsByTagName(CommonElements.Body)[0];
    
    if ($get(CommonElements.DivAlertBox) == null)
    {
        alertDialogElement = createTemplateElement_layoutDesigner_alertDialogTemplate_alertDialog(bodyElement, true, iconPath, CommonImages.Error, InformationMessages.ProblemFound);
        appendChildElement(bodyElement, alertDialogElement);
        
        setParagraphMessage($get(CommonElements.DivAlertMessage), alertMessage);
    		
        maskDialog(LayoutElements.AlertDialog);
    	
        positionDialog(alertDialogElement);
	    
        if (onCloseFunction)
        {
            $get(CommonElements.BtnAlertClose).onclick = onCloseFunction;
        }

        $get(CommonElements.BtnAlertClose).focus();
    }
}

function redirectToLoginPage()
{
    window.location.href = "SignIn.aspx";
}

function showSuccessAlert(alertMessage) 
{
    var bodyElement = document.getElementsByTagName(CommonElements.Body)[0];
    
    alertDialogElement = createTemplateElement_layoutDesigner_alertDialogTemplate_alertDialog(bodyElement, true, iconPath, CommonImages.Completed, InformationMessages.Successful);
    
    appendChildElement(bodyElement, alertDialogElement);
    
    setParagraphMessage($get(CommonElements.DivAlertMessage), alertMessage);
		
	maskDialog(LayoutElements.AlertDialog);
	
	positionDialog(alertDialogElement);

	$get(CommonElements.BtnAlertClose).focus();
}

function showInformationDialog(image, title, message, closeButtonImage, closeButtonText, okFunctionName)
{
    var bodyElement = document.getElementsByTagName(CommonElements.Body)[0];

    informationDialogElement = createTemplateElement_layoutDesigner_informationDialogTemplate_informationDialog(bodyElement, true, iconPath, image, title, closeButtonImage, closeButtonText)

    appendChildElement(bodyElement, informationDialogElement);

    setParagraphMessage($get(CommonElements.DivInformationMessage), message);

    maskDialog(LayoutElements.AlertDialog);

    positionDialog(informationDialogElement);

    switch (Sys.Browser.agent)
    {
        case Sys.Browser.InternetExplorer:
            $get(CommonElements.DivInformationMessage).style.width = "auto";
            break;
        case Sys.Browser.Firefox:
            $get(CommonElements.DivInformationMessage).style.width = "100%";
            break;
    }
    
    var btnInformationClose = $get(CommonElements.BtnInformationClose);
    btnInformationClose.focus();

	if (typeof(okFunctionName) != 'undefined')
	{
	    btnInformationClose.onclick = okFunctionName; 
	}
}

function showConfirm(confirmationMessage, okFunctionName, cancelFunctionName)
{
    var bodyElement = document.getElementsByTagName(CommonElements.Body)[0];
      
    confirmDialogElement = createTemplateElement_layoutDesigner_confirmDialogTemplate_confirmDialog(bodyElement, true, iconPath);
        
    appendChildElement(bodyElement, confirmDialogElement);
    
    setParagraphMessage($get(CommonElements.DivConfirmationMessage), confirmationMessage);
    

    
    setConfirmCancelFunction(cancelFunctionName);
	setConfirmOkFunction(okFunctionName);
		
	maskDialog(LayoutElements.AlertDialog);
	
	positionDialog(confirmDialogElement);
	
    switch(Sys.Browser.agent)
	{
        case Sys.Browser.InternetExplorer :
    	    $get(CommonElements.DivConfirmationMessage).style.width = "auto";
    	    break;
        case Sys.Browser.Firefox :
    	    $get(CommonElements.DivConfirmationMessage).style.width = "100%";
    	    break;
	}
	
	$get(CommonElements.BtnConfirmCancel).focus();
}


function clearChildElements(element)
{
    while (element.firstChild)
    {
        element.removeChild(element.firstChild);
    }
}
	
function setParagraphMessage(element, message)
{
    clearChildElements(element);
    
	var lines = message.split(/\n/);
	
	for(var count = 0; count < lines.length; count++)
	{
	    var lineElement = element.appendChild(document.createElement('p'))
	    setElementText(lineElement, lines[count]);
	}
}

/*
7/8/08 TS: added setLineBreakMessage as a fix to line breaks in FireFox
*/
function setLineBreakMessage(element, message)
{
    if(message != null)
    {
	    var lines = message.split(/\n/);

        clearChildElements(element);
    	
	    for(var count = 0; count < lines.length; count++)
	    {
	        element.appendChild(document.createTextNode(lines[count]));
		    element.appendChild(document.createElement('br'));
	    }
	}
}

function setConfirmOkFunction(okFunctionName)
{
	var okButtonElement = $get(CommonElements.BtnConfirmOk);

	if (typeof(okFunctionName) != 'undefined')
	{
	    okButtonElement.onclick = okFunctionName; 
	}
	else 
	{
	    okButtonElement.onclick = 
	        function() 
	        { 
	            removeConfirm();
	            return true; 
	        }
	}
}
	
function setConfirmCancelFunction(cancelFunctionName)
{
	var cancelButtonElement = $get(CommonElements.BtnConfirmCancel);
	
	if (typeof(cancelFunctionName) != 'undefined')
	{
	    cancelButtonElement.onclick = cancelFunctionName;
	}
	else 
	{
	    cancelButtonElement.onclick = 
	        function() 
	        { 
	            removeConfirm();
	            return false; 
	        }
	}
}

function removeConfirm() 
{
    var bodyElement = document.getElementsByTagName(CommonElements.Body)[0];

    bodyElement.removeChild(confirmDialogElement);
	bodyElement.removeChild($get(LayoutElements.AlertDialog));
}

function removeAlert() 
{
    var bodyElement = document.getElementsByTagName(CommonElements.Body)[0];

    bodyElement.removeChild(alertDialogElement);
	bodyElement.removeChild($get(LayoutElements.AlertDialog));
}

function removeInformationDialog()
{
    var bodyElement = document.getElementsByTagName(CommonElements.Body)[0];

    bodyElement.removeChild(informationDialogElement);
    bodyElement.removeChild($get(LayoutElements.AlertDialog));
}
	
function positionDialog(element) {
    if (element != null) {

        var winWidth;
        var winHeight;

        if (typeof (window.innerHeight) == 'number') {
            winWidth = window.innerWidth - 21; //21 is the scrollbar width
            winHeight = window.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientWidth) {
            winWidth = document.documentElement.clientWidth;
            winHeight = document.documentElement.clientHeight;
        }
        else if (document.body && document.body.clientWidth) {
            docElement = document.body;
            winWidth = document.body.clientWidth;
            winHeight = document.body.clientHeight;
        }

        var dialogWidth = element.offsetWidth;
        var dialogHeight = element.offsetHeight;
        var top = (winHeight / 2) - dialogHeight / 2;
        var left = (winWidth / 2) - dialogWidth / 2;

        var scrollTop = document.body.scrollTop;

        if (scrollTop == 0) {
            if (window.pageYOffset)
                scrollTop = window.pageYOffset;
            else
                scrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
        }

        element.style.top = top + document.documentElement.scrollTop - scrollTop + 'px';
        element.style.left = left + document.documentElement.scrollLeft + 'px';
    }
}
	
function maskDialog(elementName)
{
    var element = $get(elementName);
    var winHeight;
    
	if(element == null)
	{
		element = document.getElementsByTagName(CommonElements.Body)[0].appendChild(document.createElement('div'));
		element.id = elementName;
		element.className = elementName;
	}
	
	if(typeof( window.innerWidth ) == 'number' ) 
	{
	    winHeight = window.innerHeight + window.scrollMaxY;
	}
	else if( document.documentElement && document.documentElement.clientHeight ) 
    {
    	winHeightScroll = document.documentElement.scrollHeight;
    	winHeightClient = document.documentElement.clientHeight;
    	winHeight = winHeightScroll > winHeightClient ? winHeightScroll : winHeightClient;
    	//scrollHeightDiff = document.documentElement.scrollHeight - document.documentElement.clientHeight;
    }
	else if( document.body && document.body.clientHeight ) 
	{
	    winHeightScroll = document.body.scrollHeight;
		winHeightClient = document.body.clientHeight;
    	winHeight = winHeightScroll > winHeightClient ? winHeightScroll : winHeightClient;	
		//scrollHeightDiff = document.body.scrollHeight - document.body.clientHeight;
	}
	
	element.style.height = winHeight + 'px';

    if( document.documentElement && document.documentElement.clientWidth ) 
    {
    	winWidthScroll = document.documentElement.scrollWidth;
    	winWidthClient = document.documentElement.clientWidth;
    	winWidth = winWidthScroll > winWidthClient ? winWidthScroll : winWidthClient;
    }
	else if( document.body && document.body.clientHeight ) 
	{
	    winWidthScroll = document.body.scrollWidth;
		winWidthClient = document.body.clientWidth;
    	winWidth = winWidthScroll > winWidthClient ? winWidthScroll : winWidthClient;	
	}
	element.style.width = winWidth + 'px';
	
	showContent(element);
}

function getMenuItems(elem) 
{
    var menuElement = igmenu_getMenuById(elem);
    
    if (menuElement != null)
    {
        return menuElement.getItems();
    }
    else
    {
        return null;
    }
}

function isEmptyElement(elem)
{
    return (getCount(elem) == 0);
}

function MoveHtmlElement(element, direction)
{
    var sibling;
    
    if (direction == 1) // Moved up / left
    {
        sibling = element.previousSibling;
    }
    else if (direction == 2) // Moved Down / right
    {
        sibling = element.nextSibling;
    }
    
    if(sibling == null || sibling == element)
    {   
        return;
    }

    if(direction == 1)
    {
        element.parentNode.insertBefore(element, sibling);
    }
    else
    {
        element.parentNode.insertBefore(sibling, element);  
    }
}

function cancelEventBubbling(ev)
{
	if(ev != null && typeof(ev.stopPropagation) != 'undefined')
	{
		ev.stopPropagation();
	}
	else if(typeof(event) != 'undefined')
	{
		event.cancelBubble = true;
	}
}

function incrementItemCount(srcElement)
{
    var count = getCount(srcElement);
    
    count++;
    
    srcElement.setAttribute(ElementAttributes.Count, count);
}

function decrementItemCount(srcElement)
{
    var count = getCount(srcElement);
    
    count--;
    
    srcElement.setAttribute(ElementAttributes.Count, count);
}

function getElementText(element, removeWhitespace)
{
	var text = null;
	
	if(element)
    {
	    if (element.value != null)
	    {
	        text = element.value;
	    }
	    else if(element.innerText != null)
	    {
		    text = element.innerText;
		}
	    else if (element.textContent != null)
	    {
		    text = element.textContent;
    	}
    	
	    if(typeof(removeWhitespace) != 'undefined' && removeWhitespace == true)
	    {
		    text = trimString(text);
		}
	}	
	return text;
}

function getSelectedText(element)
{
    if (element == null)
    {
        return null;
    }
    
    if (element.options.length > 0)
    {
        return trimString(element.options[element.options.selectedIndex].text);
    }
    else
    {
        return '';
    }
}

function getSelectedValue(element)
{
    if (element == null || element.options.length == 0) return null;
    
    return element.options[element.options.selectedIndex].value;
}

function getSelectedIndex(element, searchText)
{
    var returnValue;

    if (element == null || element.options.length == 0) 
    {
        returnValue = 0;
    }
    else if (element.options.length > 0)
    {
        for (var optionsCount = 0; optionsCount < element.options.length; optionsCount++) 
        {
            if (element.options[optionsCount].text == searchText)
            {
                returnValue = optionsCount;
                break;
            }
        }
    }

    return returnValue;
}

function setElementText(element, text)
{
    if(element)
    {
	    if (element.value != null)
	    {
	        element.value = text;
	    }
	    else if(element.innerText != null)
	    {
		    element.innerText = text;
		}
	    else
	    {
		    element.textContent = text;
		}
    }
}

function setElementTitle(element, text)
{
    if(element)
    {
       element.title = text;
    }
}

function setElementInnerHTML(element, textHTML) 
{
    if (element) 
    {
        if (element.innerHTML != null)
        {
            element.innerHTML = textHTML;
        }
    }
}

function setElementClassName(element, className) 
{
    if (element) 
    {
        if (element.className != null) {
            element.className = className;
        }
    }
}

function trimString(string)
{
    if(string != null)
    {
	    string = string.replace(new RegExp(RegularExpressions.LeadingBlanks), '');
	    string = string.replace(new RegExp(RegularExpressions.TrailingBlanks), '');
    }
    	
	return string;
}

/*	*******************************************************
	Layout Popup menu interaction functions 
	*******************************************************		*/
function showWaitDialog(operation)
{
    var waitOperationElement = $get(CommonElements.LblWaitOperation);
    var waitElement = $get(LayoutElements.WaitDialog);

    document.body.style.cursor = CursorStyles.Wait;
    
    setElementText(waitOperationElement, operation);
    
    showContent(waitElement);
    
    maskDialog(LayoutElements.ModalDialog);

    positionDialog(waitElement);

    isWaitDialogShowing = true;
}

function hideWaitDialog()
{
    var backgroundElement = $get(LayoutElements.ModalDialog);

    document.body.style.cursor = CursorStyles.Blank;
    
    if (backgroundElement != null)
    {
        backgroundElement.parentNode.removeChild(backgroundElement);
    }
    
    hideContent($get(LayoutElements.WaitDialog));
    
    isWaitDialogShowing = false;
}

function enableButton(name, toggleImage)
{
    var buttonElement = $get(name);

    if (buttonElement != null)
    {
        if (buttonElement.getAttribute(ButtonAttributes.OldTitle) != undefined)
           buttonElement.title = buttonElement.getAttribute(ButtonAttributes.OldTitle);
               
        buttonElement.disabled = false;
        buttonElement.style.cursor = CursorStyles.Pointer; 
    }
    
    if ( toggleImage != null )
    {
        enableIcon(toggleImage);
    }
}

function disableButton(name, toggleImage, keepTitle)
{
    var buttonElement = $get(name);
    
    if (buttonElement != null)
    {
        buttonElement.disabled = true;
        if (keepTitle != true && buttonElement.title != '')
        {
            buttonElement.setAttribute(ButtonAttributes.OldTitle, buttonElement.title);
            buttonElement.title = '';
        }
        else
        {
            if (keepTitle && buttonElement.title == '' && buttonElement.getAttribute(ButtonAttributes.OldTitle) != undefined)
               buttonElement.title = buttonElement.getAttribute(ButtonAttributes.OldTitle);        
        }
        buttonElement.style.cursor = CursorStyles.Default;
    }

    if ( toggleImage != null )
    {
        disableIcon(toggleImage, keepTitle);
    }
}

function enableIconButton(name, toggleImage)
{
    var buttonIconElement = $get(name);

    if (buttonIconElement != null)
    {
        buttonIconElement.disabled = false;
        
        if (buttonIconElement.className != ButtonStyles.Default)
        {
            buttonIconElement.className = ButtonStyles.IconOnlyButton;
        }
               
        buttonIconElement.style.cursor = CursorStyles.Pointer; 
    }
    
    if ( toggleImage != null )
    {
        enableIcon(toggleImage);
    }
}

function disableIconButton(name, toggleImage)
{
    var buttonIconElement = $get(name);
    
    if (buttonIconElement != null)
    {
        buttonIconElement.disabled = true;
        
        if (buttonIconElement.className != ButtonStyles.Default)
        {
            buttonIconElement.className = ButtonStyles.IconOnlyButtonDisabled;
        }
        
        buttonIconElement.style.cursor = CursorStyles.Default;
    }

    if (toggleImage != null )
    {
        disableIcon(toggleImage);
    }
}

function enableIcon(name)
{
	var toggleImageElement = $find(name);
	
	if(toggleImageElement != null)
	{
		toggleImageElement.set_enabled(true);
	    toggleImageElement._element.style.cursor = CursorStyles.Pointer; 
	    
        if (toggleImageElement._element.getAttribute(ButtonAttributes.OldTitle) != undefined)
           toggleImageElement._element.alt = toggleImageElement._element.getAttribute(ButtonAttributes.OldTitle);    
	}
}

function disableIcon(name, keepTitle)
{
	var toggleImageElement = $find(name);
	
	if(toggleImageElement != null)
	{
		toggleImageElement.set_enabled(false);
	    toggleImageElement._element.style.cursor = CursorStyles.Default; 
	    if (keepTitle != true && toggleImageElement._element && toggleImageElement._element.alt)
	    {
	        toggleImageElement._element.setAttribute(ButtonAttributes.OldTitle, toggleImageElement._element.alt);
	        toggleImageElement._element.alt = '';
	    }
	}

}

function disableTab(tabName, linkName)
{
    var tabElement = $get(tabName);
    var linkElement = $get(linkName);
    if (tabElement != null)
    {
        tabElement.className = TabStyles.Disabled;
    }
    
    if (linkElement != null)
    {
        linkElement.href = hrefVoidLink;
    }
}

function enableTab(tabName, linkName, selected)
{
    var tabElement = $get(tabName);
    var linkElement = $get(linkName);
    
    if (tabElement != null)
    {
        if (selected)
            tabElement.className = TabStyles.Selected;
        else
            tabElement.className = TabStyles.Default;
    }
    
    if (linkElement != null)
    {
        linkElement.href = linkElement.getAttribute(LinkAttributes.HrefLink);
    }
}


function getElementTitleByName(elementName)
{
    return getElementText($get(elementName), true);
}


/******************************************************************************

    Functions that provide fading effects

******************************************************************************/

function setOpacity(elementName) 
{
	var speed = Math.round(250 / 100);//speed for each frame
	
	var timer = 0;
	
	for(i=0; i <= 100; i++)
	{
		setTimeout("changeOpacity(" + i + ",'" + elementName + "')", (timer * speed));
		timer ++;
	}
}
	
function changeOpacity(opacity, elementName) 
{
    var element = $get(elementName);
    
    if (element != null)
    {
	    var elementStyle = element.style; 
	    elementStyle.opacity = (opacity / 100);
	    elementStyle.MozOpacity = (opacity / 100);
	    elementStyle.KhtmlOpacity = (opacity / 100);
    }
}

function deleteRowsFromTable(parentElement)
{
    var tableBody;

    if(parentElement.tagName == 'TBODY')
    {
        tableBody = parentElement;
    }
    else if (parentElement.tagName == 'TABLE')
    {
        tableBody = parentElement.tBodies[0];
    }

    if (tableBody != null)
    {
        var rowCount = tableBody.rows.length;
        var index = 1;
        
        while (index <= rowCount)
        {
            tableBody.removeChild(tableBody.rows[0]);
            index ++;
        }    
    }
}

function openDialog(url, windowName, name, width, height, canScroll, canResize)
{
	var win;
	var scrollValue = (canScroll == false) ? 'no' : 'yes';//Scrollbar?
	var resizableValue = (canResize == false) ? 'no' : 'yes'; //resize?
	var left = (screen.width/2) - width / 2;
	var top = (screen.height/2) - height / 2;
	
	win = window.open(url, windowName, 'toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=' + scrollValue + ',resizable=' + resizableValue + ',copyhistory=no,width=' + width + ',height=' + height + ',left=' + left + ',top=' + top + ',screenX=' + left + ',screenY=' + top);
	
	//set the name after the window opens, because the name might
	//contains hypens, and IE complains about it.. by setting it afterwards, IE does not care
	if(win != null)
	{
	    win.name = name;
    	
	    //prevent duplicate window
	    if (window.focus) 
	    {
	        win.focus();//if window exists and minimized, re-focus
	    }
	}
}

function insertAfter(newElement, targetElement) 
{	
    //target is what you want it to go after. Look for this elements parent.	
    var parent = targetElement.parentNode;		
    
    //if the parents lastchild is the targetElement...	
    if(parent.lastchild == targetElement) 
    {		
        //add the newElement after the target element.		
        parent.appendChild(newElement);		
    } 
    else 
    {		
        // else the target has siblings, insert the new element between the target and it's next sibling.		
        parent.insertBefore(newElement, targetElement.nextSibling);		
    }
}

function onJituApplicationError(exception)
{
    hideWaitDialog();

    if (isSystemException(exception))
        showAlert(exception.get_message(), redirectToLoginPage);
    else
        alert(exception.get_message());
}

function isSystemException(exception) 
{
    return (exception.get_exceptionType() == ExceptionTypes.InvalidUserState);
}

function getLocalTime(utcTime)
{
    var localTime = new Date();
    
    return new Date(utcTime - (localTime.getTimezoneOffset() * 60000));
}

function getFormattedUtcDateTime(localTime)
{
    var result = "";
    var utcDate = new Date();
    var newTime = localTime.getTime();
    
    newTime += (localTime.getTimezoneOffset() * 60000);
    
    utcDate.setTime(newTime);
    
    result = utcDate.format('MM/dd/yyyy HH:mm:ss');
    
    return result;
}

function getFormattedDateTime(dateTime, localize)
{
    var minDate = new Date();
    var result;
    
    minDate.setFullYear(1,0,1);
    minDate.setHours(0,0,0,0);
    
    if (dateTime <= minDate) 
    {
        result = '';
    }
    else
    {
        if (localize == true)
        {
            result = getLocalTime(dateTime).format('MM/dd/yyyy HH:mm:ss');
        }
        else
        {
            result = dateTime.format('MM/dd/yyyy HH:mm:ss');
        }
    }
    
    return result;
}

function getFormattedDateTimeAMPM(dateTime)
{
    return dateTime.format('MM/dd/yyyy hh:mm tt');
}

function getFormattedTimeAMPM(dateTime)
{
    return dateTime.format("hh:mm tt");
}

function getFormattedTime(dateTime)
{
    return dateTime.format('HH:mm');
}

function getFormattedDate(dateTime)
{
    return dateTime.format('MM/dd/yyyy');
}


function getDateDifferenceInDays(fromDate, toDate)
{
    var one_day=1000*60*60*24
    return Math.ceil((fromDate.getTime()-toDate.getTime())/(one_day));
}

function hideContent(element)
{
    if (element != null)
    {
        element.style.display = ContentStyles.None;
    }
}

function showContent(element)
{
    if (element != null)
    {
        element.style.display = ContentStyles.Block;
    }
}

function showTableRow(rowElement)
{
    if (rowElement != null)
    {
        rowElement.style.display = GetBrowserTableRowDisplayValue();
    }
}

function showTableCell(cellElement)
{
    if (cellElement != null)
    {
        cellElement.style.display = GetBrowserTableCellDisplayValue();
    }
}

function GetBrowserTableRowDisplayValue()
{
    var displayValue = "";
    
    switch(Sys.Browser.agent)
    {
        case Sys.Browser.InternetExplorer :
            displayValue = ContentStyles.Block;
            break;
            
        case Sys.Browser.Firefox :
            displayValue = ContentStyles.TableRow;
            break;
    }
    
    return displayValue;
}

function GetBrowserTableCellDisplayValue()
{
    var displayValue = "";

    switch (Sys.Browser.agent)
    {
        case Sys.Browser.InternetExplorer:
            displayValue = ContentStyles.Block;
            break;

        case Sys.Browser.Firefox:
            displayValue = ContentStyles.TableCell;
            break;
    }

    return displayValue;
}

function inlineContent(element)
{
    if (element != null)
    {
        element.style.display = ContentStyles.Inline;
    }
}

function hideElement(element)
{
    if ( element != null && element.style != undefined )
    {
        element.style.visibility = VisibleStyles.Hidden;
    }
}

function showElement(element)
{
    if (element != null && element.style != undefined)
    {
        element.style.visibility = VisibleStyles.Visible;
    }
}

function inheritElementVisiblity(element)
{
    if ( element != null )
    {
        element.style.visibility = VisibleStyles.Inherit;
    }
}

function clearTabItemsSelection(tabItems)
{
	Array.forEach
	(
	    tabItems, 
	    
	    function (tabItem)
	    {
	        var tabItemElement = $get(tabItem);
	        if(tabItemElement != null)
	        {
	            if (tabItemElement.className != TabStyles.Disabled)
	            {
	                tabItemElement.className = TabStyles.Default;
	            }
	        }
	    }
	)
}

function hideContentItems(contentItems)
{
	Array.forEach
	(
	    contentItems, 
	    
	    function (contentItem)
	    {
	        hideContent($get(contentItem));
	    }
	)
}

function showContentItems(contentItems)
{
	Array.forEach
	(
	    contentItems, 
	    
	    function (contentItem)
	    {
	        showContent($get(contentItem));
	    }
	)
}

function showContentItemsInline(contentItems)
{
	Array.forEach
	(
	    contentItems, 
	    
	    function (contentItem)
	    {
	        inlineContent($get(contentItem));
	    }
	)
}

function selectTabAndDisplayContent(tabItem, contentItem)
{
    if (tabItem != null)
    {
        $get(tabItem).className = TabStyles.Selected;
    }
	
    if (contentItem != null)
    {
        $get(contentItem).style.display = ContentStyles.Block;
    }
}

function formatCurrency(nStr,prefix)
{    
    return String.localeFormat("{0:c}",parseFloat(nStr));
}

function formatCurrencyWith3Decimal(nStr, prefix)
{
    var value = to3Decimal(nStr)

    return String.localeFormat("{0:c3}", value);
}

function to3Decimal(val)
{
    val = parseFloat(val);

    val = Math.ceil(val * 1000) / 1000;

    return val;
}

//CREATES A DateValidatorResult OBJECT USED TO HOUSE ANY ERROR MESSAGES STEMMING FROM AN INCORRECT DATE
function DateValidatorResult()
{
    this.IsValid = true; 
    this.Message = "";
    this.AddReason = AddReason;
}

function AddReason(newReason)
{
    this.Message = (this.Message.length > 0) ? this.Message + '\n' + newReason : newReason;

    //the first time a message is added, flip the IsValid to false
    if(this.Message.length > 0)
    {
        this.IsValid = false;
    }
}

function checkDate(thisInput, compareWithCurrent, amountOfYearsBackToVerify )
{
    var dateValidator = new DateValidatorResult();
	var thisDate = thisInput.value;
	
	thisInput.className = '';

	//starts with 1-2 digits, followed by / or -, followed by 1-2 digits, followed by / or -, and ends with 2 or 4 digits
	if (thisDate == '')
	{
	    dateValidator.AddReason(ErrorMessages.InvalidDateFormat);
	}
	else
	{
		var matchArray = thisDate.match(RegularExpressions.Date); // compare thisDate to the valid pattern
        var match2DigitsYear = thisDate.match(RegularExpressions.DateYear2Digits);
        var match4DigitsYear = thisDate.match(RegularExpressions.DateYear4Digits);
		
		//if it doesn't match...
		if ( match2DigitsYear == null && match4DigitsYear == null)
		{
	        dateValidator.AddReason(ErrorMessages.InvalidDateFormat);
	    }
		else
		{
		    var month = matchArray[1]; // parse date into variables 
		    var day = matchArray[3]; 
		    var year = matchArray[5]; 
		    
		    // check month range 
		    if (month < 1 || month > 12)
		    {
	            dateValidator.AddReason(ErrorMessages.InvalidMonthFormat);
	        }

		    if (day < 1 || day > 31)
		    {
	            dateValidator.AddReason(ErrorMessages.InvalidDayFormat);
	        }

		    if ((month==4 || month==6 || month==9 || month==11) && day==31)
		    {
	            dateValidator.AddReason(ErrorMessages.InvalidMonth31DaysFormat);
	        }
		    
		    var todayDate = new Date();
		    if (year.length==2)
		    {
			    var todayYear = todayDate.getYear();
			    todayYear = todayYear.toString();
			    todayYear = todayYear.substring(2,4);
			    year = (year > Number(todayYear) + 10) ? '19' + year : '20'+ year;//10 years in the future
		    }

		    if (year.length==4 && (year < 1900 && (amountOfYearsBackToVerify == undefined || amountOfYearsBackToVerify == null || amountOfYearsBackToVerify == 0)) )
		    {
	            dateValidator.AddReason(String.format(ErrorMessages.InvalidYearFormat, year));
	        }

		    if (month == 2)
		    {
			    var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); 
			    if (day>29 || (day==29 && !isleap))
			    {
	                dateValidator.AddReason(String.format(ErrorMessages.InvalidFebruaryFormat, year, day));
	            }
		    }

		    // Initialize the inputDate as todayDate because we want to keep the hours/minutes/milliseconds info the same.
            // Otherwise there is a slight chance that the date comparison can fail
		    var inputDate = new Date(todayDate);
		    inputDate.setYear(year);
		    inputDate.setMonth(month-1);
		    inputDate.setDate(day);
	
		    //compare dates if its in future
		    if( compareWithCurrent && dateValidator.IsValid && inputDate > todayDate )
		    {
		        dateValidator.AddReason(ErrorMessages.DateInFuture);
		    }

		    //compare dates if its not in past	    
		    if (dateValidator.IsValid && amountOfYearsBackToVerify != null && amountOfYearsBackToVerify > 0)
            {
                var yearsOldDate = new Date();
                yearsOldDate.setFullYear(yearsOldDate.getFullYear() - amountOfYearsBackToVerify);
                yearsOldDate.setHours(0);
                yearsOldDate.setMinutes(0);
                yearsOldDate.setSeconds(0);
                yearsOldDate.setMilliseconds(0);
                
                if (inputDate < yearsOldDate)
                {
                    if(amountOfYearsBackToVerify == 1)
                    {
                        dateValidator.AddReason(String.format(ErrorMessages.DateOlderFormat, '', ErrorMessages.DateOlderYear ));
                    }
                    else
                    {
                        dateValidator.AddReason(String.format(ErrorMessages.DateOlderFormat, amountOfYearsBackToVerify, ErrorMessages.DateOlderYears ));
                    }
                }                 
            }
   		
		    //reformat the date into MM/DD/YYYY
		    month = month.length < 2 ? '0' + month : month;
		    day = day.length < 2 ? '0' + day : day;
		    thisInput.value = month + '/' + day + '/' + year;
		    thisInput.className = '';//clear any errors
        }
	}
	
	if(!dateValidator.IsValid)
	{
	    thisInput.className = TextStyles.Error;
	}

	return dateValidator;
}

function checkDates(startDate, endDate, compareWithCurrent, amountOfYearsBackToVerify )
{
    var error = '';
    var startdateValidator = checkDate(startDate, compareWithCurrent, amountOfYearsBackToVerify);
    var enddateValidator = checkDate(endDate, compareWithCurrent, amountOfYearsBackToVerify);
    
    if(!startdateValidator.IsValid)
    {
        error = (error.length > 0) ? error + '\n'+ErrorMessages.StartDate + startdateValidator.Message : ErrorMessages.StartDate + startdateValidator.Message;
    }    
    if(!enddateValidator.IsValid)
    {
        error = (error.length > 0) ? error + '\n'+ ErrorMessages.EndDate + enddateValidator.Message : ErrorMessages.EndDate + enddateValidator.Message;
    }    

    //checking if start date not greated than end date
    if (startdateValidator.IsValid && enddateValidator.IsValid)
    {
        transactionSummaryStartDate = new Date(startDate.value);
        transactionSummaryEndDate = new Date(endDate.value);
        if (transactionSummaryStartDate > transactionSummaryEndDate)
        {
            error = ErrorMessages.StartDateGreaterThanEndDate;
            startDate.className = TextStyles.Error;
        }
    }
    return error;       
}





function setErrorInformation(errorElement, problems)
{
	if (problems.length > 0)
	{
		showContent(errorElement);
		
		var thisList = errorElement.getElementsByTagName('ul')[0];//get the ul tag
		var allLIs = thisList.getElementsByTagName('li');
		var l = allLIs.length;
		
		//if there are items already there...
		if(l > 0)
		{
			while (l > 0)
			{//clear them out
				thisList.removeChild(allLIs[0]);
				l--;
			}
		}
		
		for(i=0; i<problems.length; i++)
		{
			var newItem =  document.createElement('li');
			newItem.innerHTML = problems[i];
			thisList.appendChild(newItem);
		}
	} 
	else 
	{
	    hideContent(errorElement);
	}
}

function clearErrorInformation(errorElement)
{
	var thisList = errorElement.getElementsByTagName('ul')[0];//get the ul tag
	var allLIs = thisList.getElementsByTagName('li');
	var l = allLIs.length;
		
	//if there are items already there...
	if(l > 0)
	{
		while (l > 0)
		{//clear them out
			thisList.removeChild(allLIs[0]);
			l--;
		}
	}

	hideContent(errorElement);
}

function getSecretQuestionsUsingService(secretQuestionTargetElement, infoMessage)
{
    secretQuestionsElement = secretQuestionTargetElement;
    
    if ( !isWaitDialogShowing && infoMessage != null )
    {
        showWaitDialog(infoMessage);  
    }
    
    RegistrationUIService.GetSecretQuestions(onGetSecretQuestionsCompleted, onJituApplicationError);
}

function onGetSecretQuestionsCompleted(questions)
{   
    initializeDropDown(secretQuestionsElement,InformationMessages.Select,InformationMessages.Blank,false,true);
    
    for(var counter = 0; counter < questions.length; counter++)
    {
        secretQuestionsElement.options[counter + 1] = new Option(questions[counter], questions[counter], false, false);
    }
    
    hideWaitDialog();

}

/************************************************************************ 
        FUNCTION FOR INITIALIZING A DROP DOWN BOX ELEMENT
**************************************************************************/
function initializeDropDown(element,text,value,isDefaultSelected,isSelected)
{
    element.options.length = 0;
    
    addDropDownOption(element,text,value,isDefaultSelected,isSelected);
}

function addDropDownOption(element,text,value,isDefaultSelected,isSelected)
{
    var optSelect = new Option(text,value,isDefaultSelected,isSelected);
    element.options[element.options.length] = optSelect; 
}

/************************************************************************ 
        FUNCTIONS FOR VALIDATING DATA ENTRY ELEMENTS IN AN ARRAY
**************************************************************************/
function addValidElement(elementsArray,element,className)
{
    if (elementsArray != null && element != null)
    {
        var found = false;
        for(var i = 0; i < elementsArray.length; i++ )
        {
            if ( elementsArray[i] == element.id )
            {
                found = true;
                break;
            }
        }
        
        if(!found)
        {
            elementsArray[elementsArray.length] = element.id;
        }
        
        if(className)
        {
            element.className = className;
        }
    }
}

function removeInValidElement(elementsArray,element,className)
{
    if (elementsArray != null && element != null)
    {
        if(Array.indexOf(elementsArray,element.id) >= 0)
        {
            elementsArray.splice(Array.indexOf(elementsArray,element.id), 1);
        }
    
        if(className)
        {
            element.className = className;    
        }
    }
}

/************************************************************************ 
        FUNCTIONS FOR AUTO REFRESHING THE ELEMENTS
**************************************************************************/


function addEntityForAutoRefresh(entityId, callbackFunction, interval)
{
    var isAlreadyMonitored = Array.contains(refreshElements, entityId);
    
    var timerInterval = defaultTimerIntervalInSeconds * 1000;
    
    if (! isNaN(interval))
    {
        timerInterval = interval * 1000;
    }
    
    if (!isAlreadyMonitored)
    {
        if (callbackFunction)
        {
            refreshElements[refreshElements.length] = entityId;
            
            if (refreshIntervalId == 0)
            {
                refreshIntervalId = setInterval ( "autoRefreshElements(" + callbackFunction + ")", timerInterval );
            }
        }
    }
}
function autoRefreshElements(callbackFunction)
{
    if (refreshElements.length > 0 && callbackFunction != 'undefined')
    {
        function anon() {eval(callbackFunction);};
    }
    else
    {
        clearInterval(refreshIntervalId);
        refreshIntervalId = 0;
    }
}

function clearRefreshElements()
{
    refreshElements = new Array();
    
    if (refreshIntervalId > 0)
    {
        clearInterval(refreshIntervalId);
        refreshIntervalId = 0;
    }
}

//============================================================
// usage:
//          Move.element('source', (into)'destination', 'copy' );
//
//=============================================================
var Content =	{

  copy	:   function(e, target)	
            {
                uniqueIdPostFixForContentCopy++;
	            var eId      = $get(e);
	            var copyE    = eId.cloneNode(true);
	            var cLength  = copyE.childNodes.length -1;
	            copyE.id     = e + uniqueIdPostFixForContentCopy;

	            for(var i = 0; cLength >= i;  i++)	
	            {
	                if(copyE.childNodes[i].id) 
	                {
	                    var cNode   = copyE.childNodes[i];
	                    var firstId = cNode.id;
	                    cNode.id    = firstId + uniqueIdPostFixForContentCopy; 
	                }
	            }
	    
	            $get(target).appendChild(copyE);
	        },
  move:  function(e, target)	
            {
	            var eId =  $get(e);

	            $get(target).appendChild(eId); 
	        }
}

function copyPasteContent( sourceId, targetId )
{
    Content.copy(sourceId, targetId);
}

function removeAndInsertContent(sourceId, targetId )
{
   //make sure target is clear before copying
    var targetElement = $get(targetId);
    
    clearChildElements(targetElement);
    
    Content.copy(sourceId, targetId);
}

function resetRowStyles(tBodyElement)
{
    if (tBodyElement != null)
    {
        for(i = 0; i < tBodyElement.rows.length; i++)
        {
            tBodyElement.rows[i].className = (i % 2 == 0) ? '' : RowStyles.Even;
        }
    }
}

function resetAndDisableElement(element)
{
    element.disabled = true;
    element.className = TextStyles.Blank;
}

function getNameAndTooltipForEnviroment( enviromentName )
{
    var enviromentNameAndTooltip = EnviromentNameAndTooltip;
    if (enviromentName.length > maxEnviromentNameLength)
    {
        enviromentNameAndTooltip.Name = enviromentName.substr(0,maxEnviromentNameLength) + "...";
        enviromentNameAndTooltip.ToolTip = enviromentName;        
    }   
    else
    {
        enviromentNameAndTooltip.Name = enviromentName;
        enviromentNameAndTooltip.ToolTip = ''; 
    }
    return enviromentNameAndTooltip;
} 

function checkPhoneMask(phoneElement)
{
    var phoneText = removePhoneMask(phoneElement.value);

    if (phoneText.length == 0)
    {
        phoneElement.value = '';
        return;
    }

    if (phoneText.length <= 3)
    {
        phoneElement.value = '(' + phoneText;
    }
    if (phoneText.length > 3 && phoneText.length <= 6)
    {
        phoneElement.value = '(' + phoneText.substring(0, 3) + ') ' + phoneText.substring(3, 6);
    }
    if (phoneText.length > 6)
    {
        phoneElement.value = '(' + phoneText.substring(0, 3) + ') ' + phoneText.substring(3, 6) + '-' + phoneText.substring(6, 10);
    }
}

function formatPhoneForMask(phoneNumber)
{
    if (phoneNumber == null || isNaN(phoneNumber) || phoneNumber.length < 10)
    {
        return '';
    }

    return '(' + phoneNumber.slice(0, 3) + ') ' + phoneNumber.slice(3, 6) + '-' + phoneNumber.slice(6, 10)
}

function removePhoneMask(phoneNumberWithMask)
{
    return phoneNumberWithMask.replace(/[^\d]/g, '');
}

function getPhoneFormat(extension)
{
    extension = extension == null ? '' : extension;
    return extension.length > 0 ? FormatTemplates.PhoneWithExtensionFormat : FormatTemplates.PhoneFormat;
}

function getEnumKeyFromValue(targetEnum, value)
{
    var targetKey;

    for(key in targetEnum)
    {
        if(targetEnum[key] == value)
        {
            targetKey = key;
            break;
        }
    }
    
    return targetKey;
}  

//String Trim Function
String.prototype.trim = function() {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}