﻿/*
 * <pre>
 *  Accela Citizen Access
 *  File: CapDetail.aspx.cs
 * 
 *  Accela, Inc.
 *  Copyright (C): 2008-2011
 * 
 *  Description:
 * 
 *  Notes:
 *      $Id: Global.js 77905 2007-10-15 12:49:28Z ACHIEVO\lytton.cheng $.
 *  Revision History
 *  &lt;Date&gt;,    &lt;Who&gt;,    &lt;What&gt;
 * </pre>
*/

function hideMessage()
{
   showMessage("messageSpan","","",true,0);
}

function showMessage4Popup(msg, msgtype) {
    showMessage("messageSpan", msg, msgtype, true, 1, true);
    window.scrollTo(0, 0);
}

function showNormalMessage(msg, msgtype)
{
    showMessage("messageSpan",msg,msgtype,true,1);
}

function showMessage(containerId, msg, msgtype, candelete, maxmsgcount, notScrollIntoView)
{
    //get the container object.
    var container = document.getElementById(containerId);
   
    if (container == null ||typeof (container) == "undefined") 
    {
        return;
    }

    var parentDiv = container.parentNode;
    if (typeof (parentDiv) != 'undefined' && parentDiv.tagName.toUpperCase() == 'DIV') {
        if (msg == '' && msgtype == '' && maxmsgcount == 0) {
            if ((' ' + parentDiv.className + ' ').indexOf(' ACA_Hide ', 0) < 0) {
                parentDiv.className += ' ACA_Hide';
            }
        }
        else {
            parentDiv.className = (' ' + parentDiv.className + ' ').replace(/\s+ACA_Hide\s+/gi, ' ').replace(/^\s+/, '').replace(/\s+$/, '');
        }
    }

    //get msgdiv's class, icon's class, icon's title, icon's alt,message.
    var msgclass = "";
    var iconclass = "";
    var icontitle = "";
    var iconalt = "";
    var iconsrc = "";
    var message = "";

    if (msgtype == "Success")
    {
        msgclass  = "ACA_Message_Success ACA_Message_Success_FontSize";
        iconclass = "ACA_Success_Icon";
        icontitle = getText.global_js_showConfirm_title;
        iconalt   = getText.global_js_showConfirm_title;
        iconsrc   = getText.global_js_showConfirm_src;
        message   = msg;
    }
    else if (msgtype == "Error")
    {
        msgclass  = "ACA_Message_Error ACA_Message_Error_FontSize";
        iconclass = "ACA_Error_Icon";
        icontitle = getText.global_js_showError_title;
        iconalt   = getText.global_js_showError_title;
        iconsrc = getText.global_js_showError_src;
        
        if (msg!="")
        {
            message = icontitle + '<br/>' + msg;
        }
    }
    else if (msgtype == "Notice")
    {
        msgclass  = "ACA_Message_Notice ACA_Message_Notice_FontSize";
        iconclass = "ACA_Notice_Icon";
        icontitle = getText.global_js_showNotice_title;
        iconalt   = getText.global_js_showNotice_title;
        iconsrc = getText.global_js_showNotice_src;
        
        if (msg!="")
        {
            message = icontitle + ':<br/>' + msg;
        }
    }

    // create one message bar
    var messageBar = null;
    
    if (msg != '') {
        messageBar = createOneMessageBar(message, icontitle, iconalt, msgclass, iconclass, iconsrc, candelete);
    }
                
    if (container.childNodes.length == 0 ) 
    {
       //CREATE MESSAGE BAR
       if(msg != '' && maxmsgcount != 0 && messageBar != null)
       {
           var divMessages = document.createElement('div');
           divMessages.id = containerId + '_messages';
           divMessages.appendChild(messageBar);       
           container.appendChild(divMessages);
       }
    }
    else
    {
        var divMessages = document.getElementById(containerId + '_messages');
    
        if (divMessages == null || typeof (divMessages) != "undefined")
        {
            if (msg != '' && messageBar != null)
            {
                if (divMessages.childNodes.length > 0)
                {
                    messageBar.style.marginBottom = '5px';
                    divMessages.insertBefore(messageBar, divMessages.childNodes[0]);

                }
                else
                {
                    divMessages.appendChild(messageBar);
                }   
            }
            
            var canDelDivCount = 0; 
              
            //if there are messages that can be deleted(Attribute(CanDelete)="true") 
            //and the messages'count bigger than the parameter(maxmsgcount).
            
            for(var i = 0; i < divMessages.childNodes.length;i++)
            {
                if(typeof(divMessages.childNodes[i].getAttribute("candelete")) != "undefined" && divMessages.childNodes[i].getAttribute("candelete") =="candelete")
                {
                    canDelDivCount = canDelDivCount + 1;
                    
                    if (maxmsgcount >=0 && canDelDivCount > maxmsgcount)                   
                    {
                        divMessages.removeChild(divMessages.childNodes[i]);
                        i = i -1;
                    }
                }
            }
        }
        
        if (divMessages.childNodes.length > 0)
        {
            divMessages.childNodes[divMessages.childNodes.length -1].style.marginBottom ="0px";
        }
    }

    if (containerId == "messageSpan" && msg != '' && maxmsgcount != 0) {
        if (!notScrollIntoView) {
            goToMessageBlock();
        }

        $(document).ready(function() {
            showMessageForSection508(message);
        });
    }
}

// create div for message
function createOneMessageBar(message, icontitle, iconalt, divclass, iconclass, iconsrc, candelete, needbottom) 
{
    // create the outer message div
    var divMessage = document.createElement('div');
    divMessage.className = divclass;
    if (candelete)
    {
            divMessage.setAttribute("candelete","candelete");    
    }
//    divMessage.setAttribute("divtype","onemessage");

    // create notice icon
    var divMessageIcon = document.createElement('div');
    divMessageIcon.className = iconclass;
    
    //create img icon
    var imgMessageIcon = document.createElement('img');
    imgMessageIcon.title = icontitle;
    imgMessageIcon.alt = iconalt;
    imgMessageIcon.src = iconsrc;
    
    // create space div
    var divSpace = document.createElement('div');
    divSpace.innerHTML = "&nbsp;";
    var divMessageInfo = document.createElement('div');
    
    divMessageInfo.innerHTML = message;

    var table = document.createElement("table");
    table.setAttribute("border","0");
    table.setAttribute("cellpadding","0");
    table.setAttribute("cellspacing","0");
    table.setAttribute("table-layout", "fixed");
   
    var tbody = document.createElement("tbody");
    var tr = document.createElement("tr");
    var tdIcon = document.createElement("td");
    tdIcon.setAttribute('vAlign', 'top');
    tdIcon.setAttribute("width", "25px");
    tdIcon.style.paddingTop = "2px";
        
    var tdSpace = document.createElement("td");
    tdSpace.setAttribute("width","15px");
    var tdMessage = document.createElement("td");
    tdMessage.setAttribute('vAlign', 'middle');
    
    // the first td loads the notice icon, the second loads the message.
    divMessageIcon.appendChild(imgMessageIcon);
    tdIcon.appendChild(divMessageIcon);
    tdSpace.appendChild(divSpace);
    tdMessage.appendChild(divMessageInfo);
    tr.appendChild(tdIcon);
    tr.appendChild(tdSpace);
    tr.appendChild(tdMessage);
    tbody.appendChild(tr);
    table.appendChild(tbody);

    divMessage.appendChild(table);
    
    return divMessage;
}

function goToMessageBlock()
{
    var a = $get('goTOMessage');
    if(a)
   {
        a.scrollIntoView();
   }  
}

function show(obj)
{
    var div = document.getElementById(obj);
    
    if (div != null)
    {
        div.style.display = "block";
    }
}

function SetNotAsk() {
    NeedAsk = false;
    window.setTimeout('NeedAsk=true', 1500);
}

function hide(obj)
{
    var div = document.getElementById(obj);
    
    if (div != null)
    {
        div.style.display = "none";
    }
} 

// true: browser's type is fireFox
// false: browser's type isn't fireFox
function isFireFox()
{
    if(navigator.userAgent.indexOf("Firefox")>0)
    {
        return true;
    } 
    else
    {
        return false; 
    }  
}

// true: browser's type is Safari
// false: browser's type isn't Safari
function isSafari()
{
    if(navigator.userAgent.indexOf("Safari")>0)
    {
        return true;
    } 
    else
    {
        return false; 
    }  
}

// true: browser's type is Chrome
// false: browser's type isn't Chrome
function isChrome() {
    if (navigator.userAgent.indexOf("Chrome") > 0) {
        return true;
    }

    return false;   
}

//parse currency from formatted value for JavaScript calculation, such as from 123,45.67 to 12345.67 in german culture
function I18nParseCurrencyForJS(formattedCurrency){
    //if GLOBAL_SERVICE_PROVIDER_CULTURE etc. is not defined, return original value
    if(formattedCurrency==null
        || formattedCurrency.replace(/ /g,'')==''
        || typeof(GLOBAL_SERVICE_PROVIDER_CULTURE)=="undefined"
        || typeof(GLOBAL_CURRENCY_SYMBOL)=="undefined"
        || typeof(GLOBAL_CURRENCY_GROUP_SEPARATOR)=="undefined"
        || typeof(GLOBAL_CURRENCY_DECIMAL_SEPARATOR)=="undefined"
       )
    {
        return formattedCurrency;
    }
    var result = formattedCurrency.replace(new RegExp("(\\" + GLOBAL_CURRENCY_SYMBOL + ")", "g"), "");
    result = result.replace(new RegExp("(\\" + GLOBAL_CURRENCY_GROUP_SEPARATOR + ")", "g"), "") + '';
    result = result.replace(new RegExp("(\\" + GLOBAL_CURRENCY_DECIMAL_SEPARATOR + ")", "g"), ".") + '';
    return parseFloat(result);
}

//parse currency from formatted value by culture, such as from 123,45.67 to 12345,67 in german culture
function I18nParseCurrencyForCulture(formattedCurrency){
    var result = I18nParseCurrencyForJS(formattedCurrency); // refers to I18nParseCurrencyForJS
    return result.toString().replace(new RegExp("(\\.)", "g"), GLOBAL_CURRENCY_DECIMAL_SEPARATOR);
}

//format number to I18n style with group symbol, such as from 12345.67 to $12,345.67 in English culture
function I18nFormatCurrencyWithGroupSymbol(num)
{
    //if GLOBAL_SERVICE_PROVIDER_CULTURE etc. is not defined, return original value
    if(num==null
        || num.replace(/ /g,'')==''
        || typeof(GLOBAL_SERVICE_PROVIDER_CULTURE)=="undefined"
        || typeof(GLOBAL_CURRENCY_SYMBOL)=="undefined"
        || typeof(GLOBAL_CURRENCY_GROUP_SEPARATOR)=="undefined"
        || typeof(GLOBAL_CURRENCY_DECIMAL_SEPARATOR)=="undefined"
       )
    {
        return num;
    }
    if(num<0) num=0-num;
    
    num = I18nParseCurrencyForJS(num); // refers to I18nParseCurrency
    
    num = Math.floor(num*100+0.50000000001);
    var cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+GLOBAL_CURRENCY_GROUP_SEPARATOR+
    num.substring(num.length-(4*i+3));

    return  GLOBAL_CURRENCY_SYMBOL + num + GLOBAL_CURRENCY_DECIMAL_SEPARATOR + cents;
}

//format number to I18n style with group symbol, such as from 12345.67 to $12345.67 in English culture
function I18nFormatCurrencyWithoutGroupSymbol(num)
{
    var result = I18nFormatCurrencyWithGroupSymbol(num); // refers to I18nParseCurrency
    return result.replace(new RegExp("(\\" + GLOBAL_CURRENCY_GROUP_SEPARATOR + ")", "g"), "") + '';
}

// adjust the IFrame height according to the page height.
function AdjustHeight(newHeight)
{
    if(typeof(newHeight)=="undefined" || parseFloat(newHeight)<=0)
    {
        return false;
    }
    if(window.parent!=window)
    {
        var ifrm = parent.document.getElementById("ACAFrame");
        var h=newHeight;
        if(ifrm != null && ifrm.contentWindow==window)
        {
            if(isFireFox() == false)
            {
                ifrm.style.height = ifrm.parentNode.style.height = h +"px";
            }
            else
            {
                ifrm.height = h;
            }
            return true;
        }
    }
    return false;
}

//disable/enable a button
function DisableButton(buttonId, disabled)
{
    if (buttonId != '') {
        var button = $get(buttonId);
        if (button) {
            if (button.tagName.toUpperCase() == 'A') {
                if (disabled && button.getAttribute('href') != null && typeof (button.getAttribute('href')) != 'undefined') {
                    if (button.getAttribute('href_disabled') == null || typeof (button.getAttribute('href_disabled')) == 'undefined') {
                        button.setAttribute('href_disabled', button.getAttribute('href'));
                    }

                    button.setAttribute('href', 'javascript:void(0);');
                }
                else if (button.getAttribute('href_disabled') != null && typeof (button.getAttribute('href_disabled')) != 'undefined') {
                    button.setAttribute('href', button.getAttribute('href_disabled'));
                }
            }

            if (disabled) {
                button.setAttribute('disabled', 'disabled');
                button.style.color = "Gray";
                button.style.cursor = "default";
                button.style.textDecoration = "none";
            }
            else {
                button.removeAttribute('disabled', 0);
                button.style.color = "";
                button.style.textDecoration = "";
                if (!document.all) {
                    button.style.cursor = "pointer";
                }
                else {
                    button.style.cursor = "hand";
                }
            }
        }
    }
}

function KeyValuePair() {
    var ArrayList = new Array();
    
    this.GetArray = function(){
        return ArrayList;
    }

    this.Add = function(key, value) {
        if (value) {
            var index = this.IndexOf(key);
            if (index > -1) {
                ArrayList[index].value = value;
            }
            else {
                var obj = new Object();
                obj.key = key;
                obj.value = value;
                ArrayList.push(obj);
            }
        }
    }

    this.IndexOf = function(key) {
        for (var i = 0; i < ArrayList.length; i++) {
            if (ArrayList[i].key == key) {
                return i;
            }
        }

        return -1;
    }

    this.GetByKey = function(key) {
        var index = this.IndexOf(key);
        if (index > -1) {
            return ArrayList[index].value;
        }

        return null;
    }
}

///<Summary>
///this js class is used in SPEAR form and Confirmation page to validate multiple-supported comonent
///such as multiple contacts, multiple address
///</Summary>
function ValidationHelper() {
    var SectionIDs = new Array();
    var CurrentValidationSectionID;

    this.AddSectionID = function(sectionId) {
        SectionIDs.push(sectionId);
    }

    this.SetCurrentValidationSectionID = function(sectionId) {
        CurrentValidationSectionID = sectionId;
    }

    this.IsNeedValidate = function(controlId) {
        if (SectionIDs.length == 0) {
            return true;
        }

        if (CurrentValidationSectionID == null || CurrentValidationSectionID == '')//don't need to validate the field in editor form
        {
            if (controlId.indexOf('4ValidateGridView') > -1) {
                return true;
            }

            for (var i = 0; i < SectionIDs.length; i++) {
                if (controlId.indexOf(SectionIDs[i]) > -1) {
                    return false;
                }
            }

            return true;
        }
        else// validate the fields of section which indicated by "CurrentValidationSectionID"
        {
            if (controlId.indexOf('4ValidateGridView') > -1) {
                return false;
            }

            return controlId.indexOf(CurrentValidationSectionID) > -1;
        }
    }
}

var ValidationHelperInstance = null;

//Add the section ID which need to support multiple
function AddValidationSectionID(sectionID) {
    if (!ValidationHelperInstance) {
        ValidationHelperInstance = new ValidationHelper();
    }
    ValidationHelperInstance.AddSectionID(sectionID);
}

//Set current validation section ID to indicate current only validate that section
function SetCurrentValidationSectionID(sectionID) {
    if (!ValidationHelperInstance) {
        ValidationHelperInstance = new ValidationHelper();
    }
    ValidationHelperInstance.SetCurrentValidationSectionID(sectionID);
}

//check if the control need to validate
function IsNeedValidation(controlId) {
    if (ValidationHelperInstance) {
        return ValidationHelperInstance.IsNeedValidate(controlId);
    }

    return true;
}

function getElementTop(obj) {
    var top = obj.offsetTop;

    var parentobj = obj.offsetParent;
    while (parentobj) {
        if (parentobj.offsetTop == undefined) break;
        top += parentobj.offsetTop;
        parentobj = parentobj.offsetParent;
    }

    return top;
}

//only validate section in SPACE Form.
function Section_ClientValidate(sectionID, validationGroup) 
{
    //if control array length is not 0.
    if (typeof(Page_Validators) != "undefined" && Page_Validators !=  null && Page_Validators.length > 0) 
    {
        for (var i = 0; i < Page_Validators.length; i++)
        {
            var controlValidator = Page_Validators[i];
            if ( controlValidator!= null && controlValidator.id != null && controlValidator.id.indexOf(sectionID) != -1 && typeof(ValidatorValidate) != "undefined")
            {
                ValidatorValidate(controlValidator, validationGroup, null);

                if (controlValidator.id.indexOf("strRequiredMK_") == 0) {
                    // Expression Validator is always displayed
                    controlValidator.style.visibility = "visible";
                }
            }
        }
    }
}

function getElementLeft(obj)
{
    var left = obj.offsetLeft;
    
    var parentobj = obj.offsetParent;
    while (parentobj)
    {
        if (parentobj.offsetLeft == undefined) break;
        left += parentobj.offsetLeft;
        parentobj = parentobj.offsetParent;
    }
    return left;
}

//Break word of text of HTML element in IE, Opera, Safari and Firefox.
function breakWord(element) {
    if (!element) {
        return false;
    }
    else if (element.currentStyle && typeof element.currentStyle.wordBreak === 'string') {
        breakWord = function(element) {
            //For Internet Explorer
            element.runtimeStyle.wordBreak = 'break-all';
            return true;
        }

        return breakWord(element);
    }
    else if (document.createTreeWalker) {
        var trim = function(str) {
            str = str.replace(/^\s\s*/, '');
            var ws = /\s/,
            i = str.length;
            while (ws.test(str.charAt(--i)));
            return str.slice(0, i + 1);
        }

        breakWord = function(element) {
            //For Opera, Safari, and Firefox
        var dWalker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, false);
            //'8203' is line break.
            var node, s, c = String.fromCharCode('8203');

            while (dWalker.nextNode()) {
                node = dWalker.currentNode;
                //we need to trim String otherwise Firefox will display 
                //incorect text-indent with space characters
                s = trim(node.nodeValue).split('').join(c);
                node.nodeValue = s;
            }

            return true;
        }

        return breakWord(element);
    }
    else {
        return false;
    }
}

//check spell
function DoSpellCheck(relativePath, elementId, e) {
    var height = 200;
    var width = 270;
    
    if (navigator.userAgent.indexOf("Safari") >= 0) {
        width = 275;
    }

    var element = document.getElementById(elementId);

    if ($(element).attr('disabled')) {
        return;
    }

    var left;
    var top;

    if (e) {
        left = e.screenX;
        top = e.screenY;
    }

    if (this.screen.availHeight < top + height + 80) {
        top -= (element.offsetHeight + height + 100);

        if (Sys.Browser.name == "Safari") {
            top -= 25;
        }
    }

    if (relativePath.length > 0 && relativePath.substr(relativePath.length - 1, 1) != '/') {
        relativePath += '/';
    }
    
    var wind = window.open(relativePath + 'SpellCheck/SpellChecker.aspx?id=' + elementId, elementId, "height=" + height + ",width=" + width + ",left=" + left + ",top=" + top + ",location=yes,menubar=no,resizable=no,scrollbars=no,status=yes,titlebar=yes,toolbar=no");
    wind.focus();
}

function JsonDecode(json) {
    if (!json || json == "") {
        return '';
    }

    return json.replace(/&#92;r&#92;n/g, "\r\n").replace(/&#92;n/g, "\n").replace(/&#91;/g, "[").replace(/&#93;/g, "]").replace(/&#123;/g, "{").replace(/&#125;/g, "}").replace(/&quot;/g, "\"").replace(/&acute;/g, "´").replace(/&#39;/g, "'").replace(/&sbquo;/g, ",").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&#47;/g, "/").replace(/&#92;/g, "\\").replace(/&#94;/g, "^").replace(/&#42;/g, "*");
}

function JsonEncode(json) {
    if (json == null || json == undefined || json == '') {
        return '';
    }

    return json.replace(/\[/g, "&#91;").replace(/\]/g, "&#93;").replace(/\{/g, "&#123;").replace(/\}/g, "&#125;").replace(/\"/g, "&quot;").replace(/\´/g, "&acute;").replace(/\'/g, "&#39;").replace(/\,/g, "&sbquo;").replace(/\</g, "&lt;").replace(/\>/g, "&gt;").replace(/\//g, "&#47;").replace(/\\/g, "&#92;").replace(/\^/g, "&#94;").replace(/\*/g, "&#42;");
}

String.IsNullOrEmpty = function(value) {
    var isNullOrEmpty = false;

    if (value == null || value == "") {
        isNullOrEmpty = true;
    }

    return isNullOrEmpty;
}

// Sample: GetSiblingNode("ddl_id","div_id","div[attr='contact']");
function GetSiblingNode(sourceId,targetId, pattern,type) {
    var parentDom = null;
    var targetDom = null;
    var nodeType = type || "div";

    if (typeof(sourceId) =="string") {
         $("#"+sourceId).parents(pattern).each(function () {
            parentDom=this;
            return false;
        });
    }else{
        $(sourceId).parents(pattern).each(function () {
            parentDom=this;
            return false;
        });
    }
    
    if (parentDom != null) {
        $(parentDom).find(nodeType).each(function () {
            if (this.id == targetId) {
                targetDom=this;
                return false;
            }
        });
    }
    
    return targetDom;
}

function expandComment(obj, oLink, lnkObj)
{
    if(obj=='undefined') return;
    
    var patt = "[attr='condition_notice']";
    if (typeof(oLink) == "undefined") {
        oLink = "lnkToggle" + obj;
    }
  
    var div = null;
    
    if ($("#"+obj).length != 1) {
        div = GetSiblingNode(oLink,obj,patt);
    }else{
        div = $get(obj);
    }
    
    if (typeof(oLink) == "string") {
        oLink = $get(oLink);
    }
    
    if (div.style.display == "none")
    {
        div.style.display = "";
        Expanded(oLink, imgExpanded, altCollapsed);
        AddTitle(lnkObj, altCollapsed, null);
    }
    else
    {
        div.style.display = "none";
        Collapsed(oLink, imgCollapsed, altExpanded);
        AddTitle(lnkObj, altExpanded, null);
    }
}

//Invoke click event for control
function invokeClick(element)
{
    if (element.click) 
    {
        element.click();
    }
    else if (element.fireEvent) 
    {
       element.fireEvent('onclick');
    }
    else if (document.createEvent)
    {
        var evt = document.createEvent("MouseEvents");
        evt.initEvent("click", true, true);
        element.dispatchEvent(evt);
    }
}

//Expand status
function Expanded(obj, src, alt){
    if (obj){
        obj.src = src;
        obj.alt = alt;
    }
}

//Collapse status
function Collapsed(obj, src, alt){
    if (obj){
        obj.src = src;
        obj.alt = alt;
    }
}

function AddTitle(obj, alt, lblValue) {
    if (obj) {
        obj.title = alt;
        if (lblValue && lblValue.innerHTML != "") {
            obj.title = RemoveHTMLFlag(alt + " " + lblValue.innerHTML);
        }
    }
}

// section header manager
var SectionHeaderManager = function (sectionHeaderID) {
    this.sectionHeader = $get(sectionHeaderID + "_divSectionHeader");
    this.collapsible = this.sectionHeader ? this.sectionHeader.getAttribute("collapsible").toUpperCase() == "TRUE" : false;
    this.collapsed = this.sectionHeader ? this.sectionHeader.getAttribute("collapsed").toUpperCase() == "TRUE" : false;
    this.sectionBody = this.sectionHeader ? $get(this.sectionHeader.getAttribute("sectionBodyID")) : null;
    this.titleLabel = this.sectionHeader ? $get(this.sectionHeader.getAttribute("titleLabelID")) : null;
    this.instruction = this.sectionHeader ? $get(this.sectionHeader.getAttribute("instructionID")) : null;
    this.instructionHiddenCssClass = this.instruction ? this.instruction.getAttribute("HiddenCssClass") : null;
    this.instructionShownCssClass = this.instruction ? this.instruction.getAttribute("ShownCssClass") : null;
    this.link = this.sectionHeader ? $get(this.sectionHeader.getAttribute("linkID")) : null;
    this.image = this.sectionHeader ? $get(this.sectionHeader.getAttribute("imageID")) : null;
    this.collapsedImageURL = this.image ? this.image.getAttribute("CollapsedImageURL") : null;
    this.expandedImageURL = this.image ? this.image.getAttribute("ExpandedImageURL") : null;
    this.collapsedAltTex = this.image ? this.image.getAttribute("CollapsedAltText") : null;
    this.expandedAltText = this.image ? this.image.getAttribute("ExpandedAltText") : null;
}

//toggle method of section header manager
SectionHeaderManager.prototype.toggle = function (toCollapseExplicitly) {
    if (this.sectionHeader && this.collapsible) {
        var toCollapse = !(this.sectionHeader.getAttribute("collapsed").toUpperCase() == "TRUE");
        toCollapse = typeof (toCollapseExplicitly) != "undefined" ? toCollapseExplicitly : toCollapse;
        this.sectionHeader.setAttribute("collapsed", toCollapse.toString());
        var targetAltText = toCollapse ? this.expandedAltText : this.collapsedAltTex;
        var targetImageURL = toCollapse ? this.collapsedImageURL : this.expandedImageURL;

        //set instruction
        if (this.instruction) {
            var toggleCssClass = toCollapse == true ? this.instructionHiddenCssClass : this.instructionShownCssClass;
            this.instruction.setAttribute("className", toggleCssClass);//for IE 7 className
            this.instruction.setAttribute("class", toggleCssClass);

            if (this.instruction.innerHTML == "") {
                this.instruction.setAttribute("className", this.instructionHiddenCssClass); //for IE 7 className
                this.instruction.setAttribute("class", this.instructionHiddenCssClass);
            }
        }

        //set section body
        if (this.sectionBody) {
            var sectionBodyVisible = !toCollapse;
            Sys.UI.DomElement.setVisible(this.sectionBody, sectionBodyVisible);

            if (sectionBodyVisible && Sys.UI.DomElement.containsCssClass(this.sectionBody, "ACA_Hide")) {
                Sys.UI.DomElement.removeCssClass(this.sectionBody, "ACA_Hide");
            }
            else if (!sectionBodyVisible && !Sys.UI.DomElement.containsCssClass(this.sectionBody, "ACA_Hide")) {
                Sys.UI.DomElement.addCssClass(this.sectionBody, "ACA_Hide");
            }
        }

        //set image
        if (this.image) {
            this.image.src = targetImageURL;
            this.image.alt = targetAltText;
        }

        //set link
        if (this.link) {
            AddTitle(this.link, targetAltText, this.titleLabel);
        }
    }
}

//collapse method of section header manager
SectionHeaderManager.prototype.collapse = function () {
    this.toggle(true);
}

//expand method of section header manager
SectionHeaderManager.prototype.expand = function () {
    this.toggle(false);
}


/*
*	Get byte length for UTF-8 coded chars.
*/
function getByteLength4String(value) {
    var totalLength = 0;
    var charCode;

    for (var i = 0; i < value.length; i++) {
        charCode = value.charCodeAt(i);

        if (charCode < 0x007f) {
            totalLength++;
        }
        else if ((0x0080 <= charCode) && (charCode <= 0x07ff)) {
            totalLength += 2;
        }
        else if ((0x0800 <= charCode) && (charCode <= 0xffff)) {
            totalLength += 3;
        }
        else {
            totalLength += 4;
        }
    }

    return totalLength;
}

// show message for sectino 508
function showMessageForSection508(message) {
    var isAccessibilityEnabled = typeof (accessibilityEnabled) == "function" ? accessibilityEnabled() : false;
    if (isAccessibilityEnabled) {
        alert($("<span>" + message + "</span>").text());
    }
}

//skip to target for section 508, iframeID parameter is for cross iframe invocation.
function skipTo(iframeID) {
    var expectedArgLength = skipTo.length;
    var oIframe = null;
    var oDoc = document;

    if (iframeID) {
        oIframe = window.frames[iframeID] ? window.frames[iframeID] : document.getElementById(iframeID);
        oDoc = oIframe ? oIframe.document || oIframe.contentDocument : null;
    }
    else {
        oIframe = window;
        oDoc = window.document;
    }

    var oAnchor = null;
    if (oDoc && arguments.length > expectedArgLength) {
        for (i = expectedArgLength; i < arguments.length; i++) {
            oAnchor = oDoc.getElementById(arguments[i]);
            if (oAnchor != null) {
                break;
            }
        }
    }

    var originalNeedAsk = oIframe && oIframe.NeedAsk ? oIframe.NeedAsk : null;
    if (originalNeedAsk != null) {
        oIframe.SetNotAsk(false);
    }
    if (oAnchor) {
        //oAnchor.scrollIntoView();
        oAnchor.focus();
    }
    if (originalNeedAsk != null) {
        oIframe.SetNotAsk(originalNeedAsk);
    }
}

//skip to beginning of ACA for section 508
function skipToBeginningOfACA() {
    skipTo(null, "ctl00_hlSkipToolBar", "SecondAnchorInACAMainContent");
}

//skip to main content for section 508
function skipToMainContent() {
    skipTo(null, "SecondAnchorInACAMainContent", "FirstAnchorInACAMainContent");
}

function skipToAdminMainContent() {
    var tabs = Ext.getCmp('tabs');
    var activeTab = tabs ? tabs.activeTab : null;
    if (activeTab) {
        var theIframe = activeTab.getEl().child("iframe");
        if (theIframe != null) {
            skipTo(theIframe.id, "FirstAnchorInAdminMainContent");
        }
    }
}

// true: support
// false: unsupport
function accessibilityEnabled() {
    var result = false;

    if (typeof (GLOBAL_ACCESSIBILITY_ENABLED) != "undefined") {
        result = GLOBAL_ACCESSIBILITY_ENABLED;
    }

    return result;
}

function OverrideTabKey(e, shitValue, focusId) {
   if (e.shiftKey == shitValue && e.keyCode == 9) {
       if (window.event) {
           window.event.returnValue = false;
       }
       else {
           e.preventDefault();  //for firefox
       }

       var focusObj = document.getElementById(focusId);
       if (focusObj != null) {
           focusObj.focus();
       }
   }
}

function confirmMsg(message) {
    return confirm(message.replace(/<br>|<br\/>|<br \/>/gi, '\r'));  
}

function CheckAndSetNoAsk() {
    if (typeof (SetNotAsk) != "undefined") {
        SetNotAsk(true);
    }
}

// ---Get/Set field value Form/To Watermarked fields---
function GetValue(control) {
    if (control) {
        if (typeof (AjaxControlToolkit) != 'undefined' && typeof (AjaxControlToolkit.TextBoxWrapper) != 'undefined') {
            var wrapper = AjaxControlToolkit.TextBoxWrapper.get_Wrapper(control)
            if (wrapper && wrapper.get_IsWatermarked()) {
                return '';
            }
            else {
                return control.value;
            }
        }
        else {
            return control.value;
        }
    }
    else {
        return '';
    }
}

function GetValueById(id) {
    return GetValue($get(id));
}

function SetValue(control, value) {
    if (control) {
        var watermarkBhv = $find(control.id + '_watermark_bhv');
        if (watermarkBhv) {
            watermarkBhv._onFocus();
        }

        control.value = value;

        if (watermarkBhv) {
            watermarkBhv._onBlur();
        }
    }
}

function SetValueById(id,value) {
    SetValue($get(id), value);

    // Update expression readOnly Value
    var control = $get(id);
    if (control != null
        && control.readOnly == true
        && typeof(GetReadOnlyControlById) == "function") {

        var objControl = GetReadOnlyControlById(id);
        if (objControl != null) {
            objControl.Value = value;
        }
    }
}

function SetRadioListValue(id, value) {
    var control = $get(id);
    if (control) {
        control = control.getElementsByTagName("input");
        var optionLength = control.length;
        for (var i = 0; i < optionLength; i++) {
            control[i].checked = control[i].value == value;
        }
    }
}
//------------------------------------------------------

//remove html flag from content
function RemoveHTMLFlag(strHTML) {
    strHTML = strHTML.replace(/<\/?[^>]*>/g, ''); //remove HTML tag
    strHTML = strHTML.replace(/[ | ]*\n/g, '\n'); //remove blank content
    strHTML = strHTML.replace(/\n[\s| | ]*\r/g, '\n'); //remove null row
    return strHTML;
}

function EnforceFocus(obj) {
    if (obj == null || !$(obj).is(':visible') || $(obj).is(':disabled')) {
        return;
    }

    obj.focus();
    $(document.body).unbind('focus');
}

function SupportFocus(obj) {
    if (obj == null || !$(obj).is(':visible') || $(obj).is(':disabled')) {
        return;
    }

    if (navigator.userAgent.indexOf("Firefox") > 0 || navigator.userAgent.indexOf('Safari') > 0)
    {
        obj.focus();
    }
    else
    {
       document.body.focus();
       $(document.body).bind('focus', function() { EnforceFocus(obj); });
    }
}

function FormatToFullName(firstName, middleName, lastName) {
    var fullName = '';

    switch (GLOBAL_TEXT_CULTURE.toLowerCase()){
        case "zh-cn":
        case "zh-hk":
        case "zh-mo":
        case "zh-sg":
        case "zh-tw":
            if (lastName.length > 0) {
                fullName = lastName;
            }
            if (middleName.length > 0) {
                fullName = fullName + ' ' + middleName;
            }
            if (firstName.length > 0) {
                fullName = fullName + ' ' + firstName;
            }
            
            break;
        default:
            if (firstName.length > 0) {
                fullName = firstName;
            }
            if (middleName.length > 0) {
                fullName = fullName + ' ' + middleName;
            }
            if (lastName.length > 0) {
                fullName = fullName + ' ' + lastName;
            }
            
            break;
    }

    return fullName;
}

function FormatPhoneShow(countryCode, phone, isCountryCodeEnabled) {
    var result = '';

    if (phone != null && phone.length > 0) {
        if (isCountryCodeEnabled) {
            result = '(+' + countryCode + ')' + phone;
        }
        else {
            result = phone;
        }        
    }

    return result;
}

function GetValidCssClassName(str) {
    var className = str.trim().replace(/\W/g, '_');
    if (/^\d{1}.*/.test(className)) {
        className = '_' + className;
    }

    return className;
}

//usage:Similar to the string.Format function in C#
String.prototype.format = function () {
    var args = arguments;
    return this.replace(/\{(\d+)\}/g,
        function (m, i) {
            return args[i];
        }
    );
}

// used to create collapsible element
var CollapsibleElement = function (elementID) {
    this.elementID = elementID;
    this.element = $('#' + this.elementID);
    this.isCollapsed = true;
}

CollapsibleElement.prototype.expand = function () {
    if (this.isCollapsed && this.element.hasClass('ACA_Hide')) {
        this.isCollapsed = false;
        this.element.removeClass('ACA_Hide');
    }
}

CollapsibleElement.prototype.collapse = function () {
    if (!this.isCollapsed && !this.element.hasClass('ACA_Hide')) {
        this.isCollapsed = true;
        this.element.addClass('ACA_Hide');
    }
}

CollapsibleElement.prototype.toggle = function () {
    if (this.isCollapsed) {
        this.expand();
    } else {
        this.collapse();
    }
}

// get the current checked values split by 'splitChar' which the checkbox click.
// obj: the checkbox object
// checkedValue: the current row value which the checkbox click
// existValue: the exist values
// splitChar: the split char
function GetCurrentCheckedValues(obj, checkedValue, existValue, splitChar) {
    var result = existValue;

    if ($(obj).attr('checked')) {
        if (result == null || result == '') {
            result = splitChar + checkedValue + splitChar;
        }
        else if (result.indexOf(splitChar + checkedValue + splitChar) == -1) {
            result = result + checkedValue + splitChar;
        }
    }
    else {
        if (result.indexOf(splitChar + checkedValue + splitChar) != -1) {
            result = result.replace(splitChar + checkedValue + splitChar, splitChar);

            if (result == splitChar) {
                result = '';
            }
        }
    }

    return result;
}

function SetNotAskForSPEAR() {
    if (typeof (SetNotAsk) != 'undefined') {
        SetNotAsk(true);
    }
}

function IsTrue(obj) {
    var isTrue = false;

    if (typeof (obj) == "boolean" && obj == true) {
        isTrue = true;
    } else if (typeof (obj) == "string" && obj.toUpperCase() == "TRUE") {
        isTrue = true;
    }

    return isTrue;
}

function RoundDecimal(numValue, decimalLength, isNeedComma) {

    if (numValue == null || numValue.trim() == "") return "";

    numValue = numValue.toString().replace(/\$|\,/g, '');

    if (isNaN(numValue)) numValue = "0";

    // CASE 0: decimal = 10, zero='0'
    // CASE 1: decimal = 100, zero='00'
    // CASE 2: decimal = 1000, zero='000'
    // CASE 3: decimal = 10000, zero='0000'
    // CASE 4: decimal = 100000, zero='00000'
    var decimal = 1;
    var zero = "";
    if (decimalLength > 0) {

        for (var i = 0; i < decimalLength; i++) {
            zero = zero + '0';
        }

        var temp = 'decimal = 1' + zero;
        eval(temp);
    }

    if (numValue < 0) numValue = 0 - numValue;
    numValue = Math.floor(0.50000000001 + (numValue * decimal));
    var cents = numValue % decimal;

    numValue = Math.floor(numValue / decimal).toString();
    if (isNeedComma) {
        for (var i = 0; i < Math.floor((numValue.length - (1 + i)) / 3); i++) {
            numValue = numValue.substring(0, numValue.length - (4 * i + 3)) + ',' + numValue.substring(numValue.length - (4 * i + 3));
        }
    }

    cents = "" + cents;
    if (decimalLength > 0) {
        cents = zero.substr(0, decimalLength - cents.toString().length) + cents;
        numValue = numValue + '.' + cents;
    }

    return numValue;
}
