/// <reference path="../jquery/jquery-1.7.2.min.js" />
/// <reference path="../Resources/en-us/custom.js" />

// For changing between mobile view and full site view on mobile devices. uses cookies- this needs to stay at the top of the document or it does not work- Adriane 09/28/2012
function viewfullsite() {
    var viewfullClass = document.getElementById('view-full').className;
    if (viewfullClass == "mobile_only fullsite") {
        setCookie('ISRESPONSIVE', 'no', 7);
        window.location.reload();
    } else {
        setCookie('ISRESPONSIVE', 'yes', 7);
        window.location.reload();
    }
}

var __sortNumberFunction = function (num1, num2) {
    return num1 - num2;
};
Array.prototype.sortNumber = function () {
    return this.sort(__sortNumberFunction);
}

//jQuery Extend
; (function ($) {
    $.extend($, {
        cookie: function (name, value, options) {
            if (typeof value != 'undefined') { // name and value given, set cookie
                options = options || {};
                if (value === null) {
                    value = '';
                    options.expires = -1;
                }
                var expires = '';
                if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                    var date;
                    if (typeof options.expires == 'number') {
                        date = new Date();
                        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                    } else {
                        date = options.expires;
                    }
                    expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
                }
                var path = options.path ? '; path=' + options.path : '';
                var domain = options.domain ? '; domain=' + options.domain : '';
                var secure = (window.location.protocol == 'https:') ? '; secure' : '';
                document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
            } else { // only name given, get cookie
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        // Does this cookie string begin with the name we want?
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
        },
        unbindShowImageAnchorsClick: function (anchors) {
            anchors = anchors || "a[href!='#'][href]";
            $(anchors).each(function () {
                var href = $(this).attr("href") || "";
                var exts = href.match(/[^'"]*?home\/showimage\s*(\?.*)/gi);
                if (exts) {
                    $(this).unbind();
                }
            });
        },
        /*File Related*/
        getFileExtension: function (fileName) {
            var exts = fileName.match(/\.([^\.]+)$/);
            if (exts) {
                return exts[0].toLowerCase();
            } else {
                return "";
            }
        },
        convertHtmlToText: function (html, maxLength) {
            var htmlRegex = /<[^><]*?>/gi;
            var htmlReplacement = ' ';
            var result = html.replace(htmlRegex, htmlReplacement);
            if (typeof maxLength == "Number" && maxLength > 3 && result.length > maxLength) {
                result = result.substr(0, result.length - 3) + "...";
            }
            return result;
        },
        isFileInputExtensionValid: function (fileSelector, allowedExtensions, allowEmpty) {
            allowEmpty = allowEmpty || false;
            var extensionArray0 = $.trim(allowedExtensions).split(',');
            var extensionArray = [];
            $(extensionArray0).each(function (i, n) {
                extensionArray.push($.trim(n));
            });
            var file = $(fileSelector);
            var fileFullName = file.val();
            if (fileFullName) {
                var fileExtension = $.getFileExtension(fileFullName);
                return $.inStringArray(fileExtension, extensionArray, true) >= 0;
            }
            return allowEmpty;
        },
        isLocalUrl: function (url) {
            return url && !(/^([a-z]+:)?\/\//i).test(url);
        },
        isUrl: function (value) {
            return value && /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(value);
        },
        isIntranetUrl: function (value) {
            return value && /^(((ftp|http|https):\/\/)|(\/)|(..\/))(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/i.test(value);
        },
        isIEBrowser: function (userAgent) {
            userAgent = userAgent || navigator.userAgent;
            return userAgent.indexOf("MSIE ") > -1 || userAgent.indexOf("Trident/") > -1;
        },
        isIE9Browser: function (userAgent) {
            userAgent = userAgent || navigator.userAgent;
            return userAgent.indexOf("MSIE 9") > -1;
        },
        getIEVersion: function () {
            var myNav = navigator.userAgent.toLowerCase();
            return (myNav.indexOf('msie') != -1) ? parseInt(myNav.split('msie')[1]) : -1;
        },
        evalFunc: function (data) {
            return eval("(0," + data + ")");
        },
        refreshTempMessage: function (msg) {
            if ($.fn.tempMessage) {
                $(".vi-temp-message-container").tempMessage({ message: msg });
            }
        },
        isEmpty: function (value, allowBlank) {
            if (typeof value == 'undefined' || value == null) {
                if (!allowBlank) {
                    return typeof value == "string" && $.trim(value) == "";
                } else {
                    return true;
                }
            } else {
                if ($.type(value) == "string" && $.trim(value) == "" && !allowBlank) {
                    return true;
                }
                return false;
            }
        },
        refreshFriendlyUrl: function (key, oldValue, newValue, appDoaminAppVirtualPath, url, enableFriendlyFeature) {
            enableFriendlyFeature = enableFriendlyFeature === "True";
            var adminPath = (appDoaminAppVirtualPath + "/Admin/").toLowerCase();
            if (url == "undefined" || url == null)
                var currentUrl = window.location.toString();
            else
                currentUrl = url;
            var isInAdminMode = (currentUrl.toLowerCase().indexOf(adminPath) >= 0);
            var returnVal = "";
            if (!isInAdminMode && enableFriendlyFeature) {
                var currentFriendlyKeyStr = "/-" + key + "-" + oldValue;
                var friendlyUrlIndex = currentUrl.indexOf(currentFriendlyKeyStr);
                if (friendlyUrlIndex >= 0) {
                    returnVal = currentUrl.substring(0, friendlyUrlIndex) + "/-" + key + "-" + newValue + currentUrl.substring(friendlyUrlIndex + currentFriendlyKeyStr.length);
                } else {
                    returnVal = currentUrl + "/-" + key + "-" + newValue;
                }
                return returnVal;
            }
            else {
                var currentNormalKeyStr = "&" + key + "=" + oldValue;
                var normalUrlIndex = currentUrl.indexOf(currentNormalKeyStr);
                if (normalUrlIndex >= 0) {
                    returnVal = currentUrl.substring(0, normalUrlIndex) + "&" + key + "=" + newValue + currentUrl.substring(normalUrlIndex + currentNormalKeyStr.length);
                } else {
                    returnVal = currentUrl + "&" + key + "=" + newValue;
                }
                return returnVal;
            }
        },
        format: function (str) {
            var s = arguments[0];

            for (var i = 0, l = arguments.length - 1; i < l; i++) {
                var reg = new RegExp('\\{' + i + '(:([^\\}]+))?\\}', 'gm');

                var argument = arguments[i + 1];

                s = s.replace(reg, function () {
                    return argument;
                });
            }
            return s;
        },
        _onloadFuncArray: [],
        prepareTriggerOnloadParams: function (context, triggerSelf) {
            context = context || "";
            if (typeof (triggerSelf) == 'undefined' || triggerSelf == false) {
                context = context + " ";
            }
            return context;
        },
        triggerOnload: function (context, triggerSelf) {
            var that = this;
            $(that._onloadFuncArray).each(function (i, n) {
                if ($.isFunction(n)) {
                    n(context, triggerSelf);
                }

                if ($.type(n) === "string") {
                    try {
                        that.evalFunc(n)();
                    } catch (e) {
                        alert(e.message);
                    }
                }
            });
        },
        pushOnloadFunc: function (onloadFunc, runAtOnce) {
            if ($.inArray(onloadFunc, this._onloadFuncArray) < 0) {
                this._onloadFuncArray.push(onloadFunc);
            }
            if (runAtOnce == true) {
                onloadFunc();
            }
        },
        /*Array related*/
        inStringArray: function (value, array, ignoreCase) {
            var tempValue = value;
            var tempArray = array;
            if (typeof ignoreCase != "undefined" && ignoreCase == true) {
                tempValue = value.toLowerCase();
                tempArray = $.map(array, function (i) { return i.toLowerCase() });
            }
            return $.inArray(tempValue, tempArray);
        },
        decodeHTML: function (html) {
            // copy from telerik
            var a = /&amp;/g, c = /&lt;/g, b = /&gt;/g;
            return ("" + html).replace(b, ">").replace(c, "<").replace(a, "&");
        },
        encodeHTML: function (html) {
            var a = /&/g, c = /</g, b = />/g;
            return ("" + html).replace(a, "&amp;").replace(c, "&lt;").replace(b, "&gt;");
        },
        appendQueryString: function (url, key, value, needEncode) {
            url = url || "";
            needEncode = needEncode || true;
            value = value || "";
            value = needEncode ? encodeURIComponent(value) : value;
            return url + (url.indexOf("?") >= 0 ? "&" : "?") + key + "=" + value;
        },
        calculateTimespan: function (startDate, endDate) {
            var defaultDate = new Date();
            startDate = startDate || defaultDate;
            endDate = endDate || defaultDate;

            var milliseconds = endDate.getTime() - startDate.getTime();
            var days = Math.floor(milliseconds / (24 * 3600 * 1000));
            var leave1 = milliseconds % (24 * 3600 * 1000);
            var hours = Math.floor(leave1 / (3600 * 1000));
            var leave2 = leave1 % (3600 * 1000);
            var minutes = Math.floor(leave2 / (60 * 1000));

            var daysText = days > 0 ? days + " days " : "";
            var hoursText = hours > 0 ? hours + " hours " : "";
            var minutesText = minutes > 0 ? minutes + " mins " : "";

            var allText = daysText + hoursText + minutesText;
            if (allText.length != 0)
                allText = allText.substring(0, allText.length - 1);
            if (allText.length == 0)
                allText = "0 min";
            return allText;
        }
    });

    /* Frontend Check first. */
    /* mainSpan_wrapper & mainSpan_wrapper_home for site template caching issue*/
    if (window.visionOptions) {
        if (window.visionOptions.navigationID > 0) {
            var alertContainer = $(".alert_container");
            if (alertContainer) {
                var showTopTipsCookie = window.visionOptions.showTopTips;
                var containerClass = showTopTipsCookie ? "" : "hideContent";
                var buttonClass = containerClass == "hideContent" ? "show" : "hide";
                if (containerClass == "hideContent") {
                    if (!window.visionOptions.loggedIn && window.visionOptions.emergencyNoticeChanged) {
                        containerClass = "";
                        buttonClass = "hide";
                    }
                }
                alertContainer.find(".important_alert_wrapper").removeClass("hideContent").addClass(containerClass);
                alertContainer.find("#alert_controls").attr("class", buttonClass);
            }
        }
    }
})(jQuery);

function RedirectAfterDropDownListSelectedChanged(obj) {
    var url = $(obj[obj.selectedIndex]).attr("data-url");
    url = $("<div/>").html(url).text();//This means html decode url.
    window.location.href = url;
};

/*********** CheckBoxListManager Start**************/
; (function () {
    function checkBoxListManager(container, options) {
        this._container = container;
        this._options = options;
        this._elementArray = new Array();
        this._indexArray = new Array();
        $(this._container).data("_checkBoxListManager", this);
    };

    checkBoxListManager.prototype = {
        _options: { submitOnlyChecked: true, required: false },
        _container: null,
        _elementArray: new Array(),
        _indexArray: new Array(),
        _toggle: function (checkBox, manager) {
            var checked = $(checkBox).prop("checked");
            $(checkBox).val(checked);
            var parent = $(checkBox).parent("li");
            if (parent != null) {
                if (manager._options.submitOnlyChecked) {
                    var elementIndex = parseInt(parent.find("input.index").val());
                    var index = $.inArray(elementIndex, manager._indexArray);
                    if (!checked) {
                        $(manager._elementArray[index]).remove();
                    }
                    else {
                        parent.append(manager._elementArray[index]);
                    }
                }
                else {
                    // change the check box hidden input's value according to the check box field.
                    $(parent).find("input.to-hidden[type='hidden'][name='" + $(checkBox).attr("name") + "']").val(checked);
                }
            }

            var options = manager._options;

            if (options.required && manager._requiredHidden) {
                if (manager.getSelectedValues().length > 0) {
                    manager._requiredHidden.val(true);
                } else {
                    manager._requiredHidden.val("");
                }
            }
        },
        getSelectedValues: function () {
            var result = [];
            $(this._container).find("input.value[type='hidden']").each(function (i, n) { result.push($(n).val()); });
            return result;
        },
        build: function () {
            var manager = this;

            //prepare
            $(this._container).find("li").each(function (i, n) {
                var element = $(n).find("input.to-hidden[type='hidden']:not(.index)");
                manager._elementArray.push(element);
                var elementIndex = parseInt($(n).find("input.index").val());
                manager._indexArray.push(elementIndex);

                var checkbox = $(n).find("input[type='checkbox']");
                if (manager._options.submitOnlyChecked) {
                    var checked = checkbox.val().toLowerCase() == "true";
                    if (!checked) {
                        element.remove();
                    }
                }
            });

            // check box item change event
            $(this._container).delegate("input[type='checkbox']", "click", function () {
                manager._toggle($(this), manager);
            });

            // check all change event
            $(this._container).next("input.check-all[type='checkbox']").change(function () {
                var thisObj = $(this);
                $(manager._container).find("input[type='checkbox']").each(function (i, n) {
                    if ($(n).prop("disabled") != true) {
                        $(n).prop("checked", thisObj.prop("checked"));
                        manager._toggle($(n), manager);
                    }
                });
            });

            var options = manager._options;
            var container = manager._container;

            if (options.required && $.validator) {
                var requiredHidden = manager._requiredHidden = container.children("input.check_box_list_required");
                var fieldName = container.attr("name");
                var errorMessage = container.attr("data-val-required") || "";
                var checkBoxListRequiredMessage = $.isEmpty(errorMessage) ? $.format(Vision.Resources.UI_Common_CheckBoxList_RequireValidError, fieldName) : errorMessage;

                requiredHidden.rules("add", {
                    checkBoxListRequired: [container],
                    messages: {
                        checkBoxListRequired: checkBoxListRequiredMessage
                    }
                });
            }
        }
    };

    $.extend($.fn, {
        checkBoxList: function (options) {
            options = options || { submitOnlyChecked: true };
            var element = $(this);
            element.each(function () {
                var manager = new checkBoxListManager($(this), options);
                manager.build();
            })
            return element;
        },
        getCheckBoxListManager: function () {
            return $(this).data("_checkBoxListManager");
        },
        moveStyleSheetsToHead: function (options) {
            $(this).find("link").each(function () {
                var linksSelector = null;
                if (options && options.linksSelector)
                    linksSelector = options.linksSelector;
                else
                    linksSelector = "link[href='" + $(this).attr("href") + "']";
                if ($("head").find(linksSelector).length <= 0) {
                    $(this).appendTo('head');
                } else {
                    $(this).remove();
                }
            });
        }
    });
})(jQuery);
/*********** CheckBoxListManager End**************/

/*********** zCheckBoxListManager Start**************/
; (function () {
    function zCheckBoxListManager(container, options) {
        this._container = container;
        this._options = options;
        this._elementArray = new Array();
        this._indexArray = new Array();
        $(this._container).data("_zCheckBoxListManager", this);
    };

    zCheckBoxListManager.prototype = {
        _options: { submitOnlyChecked: true, required: false },
        _container: null,
        _elementArray: new Array(),
        _indexArray: new Array(),
        _toggle: function (checkBox, manager) {
            var checked = $(checkBox).prop("checked");
            $(checkBox).val(checked);
            var parent = $(checkBox).parent("li");
            if (parent != null) {
                if (manager._options.submitOnlyChecked) {
                    var elementIndex = parseInt(parent.find("input.index").val());
                    var index = $.inArray(elementIndex, manager._indexArray);
                    if (!checked) {
                        $(manager._elementArray[index]).remove();
                    }
                    else {
                        parent.append(manager._elementArray[index]);
                    }
                }
                else {
                    // change the check box hidden input's value according to the check box field.
                    $(parent).find("input.to-hidden[type='hidden'][name='" + $(checkBox).attr("name") + "']").val(checked);
                }
            }

            var options = manager._options;

            if (options.required && manager._requiredHidden) {
                if (manager.getSelectedValues().length > 0) {
                    manager._requiredHidden.val(true);
                } else {
                    manager._requiredHidden.val("");
                }
            }
        },
        getSelectedValues: function () {
            var result = [];
            $(this._container).find("input.value[type='hidden']").each(function (i, n) { result.push($(n).val()); });
            return result;
        },
        build: function () {
            var manager = this;

            //prepare
            $(this._container).find("li").each(function (i, n) {
                var element = $(n).find("input.to-hidden[type='hidden']:not(.index)");
                manager._elementArray.push(element);
                var elementIndex = parseInt($(n).find("input.index").val());
                manager._indexArray.push(elementIndex);

                var checkbox = $(n).find("input[type='checkbox']");
                if (manager._options.submitOnlyChecked) {
                    var checked = checkbox.val().toLowerCase() == "true";
                    if (!checked) {
                        element.remove();
                    }
                }
            });

            // check box item change event
            $(this._container).delegate("input[type='checkbox']", "click", function () {
                manager._toggle($(this), manager);
                var checked = $(this).prop("checked");
                if (!checked) {
                    //uncheck select all checkbox
                    var selectedAllCheckBox = $(this).parents('.checkboxlist-container').next("input.check-all");
                    selectedAllCheckBox.removeAttr("checked");
                    $(manager._container).closest("li").find("input.check-all-hidden").val(false);
                }
            });

            // check all change event
            $(this._container).next("input.check-all[type='checkbox']").change(function () {
                var thisObj = $(this);
                $(manager._container).find("input[type='checkbox']").each(function (i, n) {
                    if ($(n).prop("disabled") != true) {
                        $(n).prop("checked", thisObj.prop("checked"));
                        manager._toggle($(n), manager);
                    }
                });
                var checked = thisObj.prop("checked");
                if (checked) {
                    thisObj.val(checked);
                }
                $(manager._container).closest("li").find("input.check-all-hidden").val(checked);
            });

            var options = manager._options;
            var container = manager._container;

            if (options.required && $.validator) {
                var requiredHidden = manager._requiredHidden = container.children("input.check_box_list_required");
                var fieldName = container.attr("name");
                var errorMessage = container.attr("data-val-required") || "";
                var checkBoxListRequiredMessage = $.isEmpty(errorMessage) ? $.format(Vision.Resources.UI_Common_CheckBoxList_RequireValidError, fieldName) : errorMessage;

                requiredHidden.rules("add", {
                    checkBoxListRequired: [container],
                    messages: {
                        checkBoxListRequired: checkBoxListRequiredMessage
                    }
                });
            }
        }
    };

    $.extend($.fn, {
        zCheckBoxList: function (options) {
            options = options || { submitOnlyChecked: true };
            var element = $(this);
            element.each(function () {
                var manager = new zCheckBoxListManager($(this), options);
                manager.build();
            })
            return element;
        },
        getzCheckBoxListManager: function () {
            return $(this).data("_zCheckBoxListManager");
        }
    });
})(jQuery);
/*********** zCheckBoxListManager End**************/


// options:{
// pagerName,totalCount, pageSize,currentPage,pagerContainer, showRecordsHtml
// }
function Pager(options) {
    this.totalCount = options.totalCount;
    this.pageSize = options.pageSize;
    this.pagerName = options.pagerName;
    this.currentPage = options.currentPage;
    this.pagerContainer = options.pagerContainer;
    this.pages = 0;
    this.inited = false;
    Pager.Manager._allPagers.push(this);

    this.showRecords = options.showRecordsHtml;

    this.showPage = function (pageNumber) {
        this.moveToCurrentPage(pageNumber);
        this.showRecords(pageNumber);
        this.showPageNav();
    };
    this.moveToCurrentPage = function (pageNumber) {
        if (!this.inited) {
            alert(Vision.Resources.UI_Common_Paging_NotInitializedError);
            return;
        }

        var oldPageAnchor = $("#" + this.pagerName + 'pg' + this.currentPage).attr("class", "pg-normal");

        this.currentPage = pageNumber;
        $("#" + this.pagerName + 'pg' + this.currentPage).attr("class", "pg-selected");
    };

    this.prev = function () {
        if (this.currentPage > 1)
            this.showPage(this.currentPage - 1);
    };

    this.next = function () {
        if (this.currentPage < this.pages) {
            this.showPage(this.currentPage + 1);
        }
    };

    this.init = function () {
        var records = this.totalCount;
        this.pages = Math.ceil(records / this.pageSize);
        this.inited = true;
        this.showPageNav();
    };

    this.showPageNav = function () {
        if (!this.inited) {
            alert(Vision.Resources.UI_Common_Paging_NotInitializedError);
            return;
        }
        if (this.pages > 0) {
            var element = $(this.pagerContainer);
            var pagerHtml = '<a ' + (this.currentPage > 1 ? 'onclick="Pager.Manager.getPager(\'' + this.pagerName + '\').prev();"' : '') + ' class="' + (this.currentPage > 1 ? 'pg-normal' : "disabled") + ' pg-button">' + Vision.Resources.UI_Common_Paging_PrevButtonText + '</a> | ';
            for (var page = 1; page <= this.pages; page++) {
                var onclick = page == this.currentPage ? "" : "Pager.Manager.getPager(\'" + this.pagerName + "\').showPage(" + page + ");";
                pagerHtml += '<a id="' + this.pagerName + 'pg' + page + '" class="pg-normal" onclick="' + onclick + '">' + page + '</a> | ';
            }
            pagerHtml += '<a ' + (this.currentPage < this.pages ? 'onclick="Pager.Manager.getPager(\'' + this.pagerName + '\').next();"' : '') + ' class="' + (this.currentPage < this.pages ? 'pg-normal' : "disabled") + ' pg-button"> ' + Vision.Resources.UI_Common_Paging_NextButtonText + '</a>';
            element.html(pagerHtml);
            this.moveToCurrentPage(this.currentPage);
        }
    };
};

Pager.Manager = {
    _allPagers: [],
    getPager: function (name) {
        var result = null;
        $(this._allPagers).each(function (i, n) {
            if (n.pagerName == name) {
                result = n;
                return;
            }
        });
        return result;
    }
};

/*  -------------  Page View State  -------------------*/
function visionViewState(options) {
    this._conatiner = $(options.conatiner);
    this._data = $.parseJSON($(options.conatiner).val());
    this.data = function (key, value) {
        if (value == null) {
            return this._data[key];
        }
        else {
            this._data[key] = value;
            $(this._conatiner).val(JSON.stringify(this._data));
        }
    }
};

/* -------------- jquery Drop down --------------- */
; (function ($) {
    var ViDropdown = function (element, options) {
        var defaults = {
            eventName: "click",
            targetEl: null,
            rewriteTarget: false,
            animSpeed: 100,
            minWidth: 250,
            minHeight: 100,
            maxHeight: 200,
            enableInput: true,
            backSpaceClear: true,//only used when enableInput is false.
            //zIndex: 1000,
            relocateEl: "#toppanel",
            dialogClass: ".vi-content",
            init: function (dropdown) { },
            beforeShow: function () { },
            afterShow: function () { },
            //only used when enableInput is false and backSpaceClear is false, but want to clear some other element val.
            clearElement: function (inputEl, keyCode) { }
        };
        var zIndex = $(element).getZIndex() + 1;
        this.setting = $.extend({ zIndex: zIndex }, defaults, options);
        this.vars = {
            openState: false
        };
        this.dropDown = $(element);
        // If exists the same panel among body children, we should remove the old one, append the new one.
        // The scenario will appear in SystemVariableAdd Page, when we switch multiple time between Links and the other field types.
        var existedDropDownPanel = $("body").children(this.setting.targetEl);
        if (existedDropDownPanel.length > 0) {
            if (!this.setting.rewriteTarget) {
                existedDropDownPanel.remove();
            }
        }

        this.dropDownPanel = $(this.setting.targetEl);

        if (this.setting.targetEl == null) {
            alert(Vision.Resources.UI_Common_ViDropdown_PleaseSetTargetEle);
            return;
        }
        this.initialize();
    };

    ViDropdown.prototype = {
        initialize: function () {
            var _this = this,
                vars = _this.vars,
                dropDown = _this.dropDown,
                dropDownPanel = _this.dropDownPanel,
                setting = _this.setting,
                parent = dropDownPanel.parent();

            var dropDownInput = dropDown.is(":text") ? dropDown : dropDown.find(":text");
            dropDownInput.attr('autocomplete', 'off');
            dropDownPanel.addClass("vi-dropdown-panel");

            if (parent.length > 0 && !parent.is("body")) {
                dropDownPanel.appendTo("body");
            }
            dropDownPanel.data("SourceEl", dropDown);

            dropDownPanel.css({
                "position": "absolute",
                "min-width": setting.minWidth,
                "min-height": setting.minHeight,
                "max-height": setting.maxHeight,
                "overflow": "auto",
                "z-index": setting.zIndex
            });

            if (setting.maxWidth) {
                dropDownPanel.css({
                    "max-width": setting.maxWidth,
                });
            }

            _this.bindEvent();

            if (setting.init && $.isFunction(setting.init)) {
                setting.init(this);
            }
        },
        bindEvent: function () {
            var _this = this,
                vars = _this.vars,
                dropDown = _this.dropDown,
                dropDownPanel = _this.dropDownPanel,
                setting = _this.setting,
                parent = dropDownPanel.parent();

            //registe event start
            dropDown.bind(setting.eventName, function () {
                _this._setPosition(dropDown);
                if (vars.openState) {
                    _this.close();
                } else {
                    _this.open();
                }
            });

            var dropDownInput = dropDown.is(":text") ? dropDown : dropDown.find(":text");
            if (!setting.enableInput) {
                dropDownInput.bind("keydown", function (e) {
                    if (setting.backSpaceClear) {
                        if (e.which !== 8) {
                            return false;
                        } else {
                            dropDownInput.val("");
                            setting.clearElement && setting.clearElement.call(_this, dropDownInput, e.which);
                        }
                    } else {
                        return false;
                    }
                });
            }

            $(document).bind("mousedown", $.proxy(function (e) {
                if (dropDownPanel.length == 0 || ($.contains(dropDownPanel[0], e.target) || dropDownPanel[0] == e.target)) {
                    return;
                }
                if (dropDown[0] != e.target && vars.openState) {
                    _this.close();
                }
            }, this));

            var resizeTimer;
            $(window).resize(function () {
                resizeTimer && clearTimeout(resizeTimer);
                resizeTimer = setTimeout(function () {
                    if (vars.openState) {
                        _this._setPosition(dropDown);
                    }
                }, 20);
            });

            var scrollTimer;
            $(window).scroll(function () {
                scrollTimer && clearTimeout(scrollTimer);
                scrollTimer = setTimeout(function () {
                    if (vars.openState) {
                        _this._setPosition(dropDown);
                    }
                }, 20);
            });

            var hasScrollbar = false, scrollElement = [];
            dropDown.parents().each(function (i, n) {
                hasScrollbar |= n.scrollHeight > n.clientHeight && $(n).css("overflow") == "auto";
                scrollElement.push($(n));
                return !hasScrollbar;
            });

            if (scrollElement.length > 0) {
                $.each(scrollElement, function (i, n) {
                    if (!$(n).is(window)) {
                        $(n).scroll(function () {
                            _this.close();
                        });
                    }
                });
            }
            //registe event end
        },
        _setPosition: function (dropDown) {
            var _this = this,
                vars = _this.vars,
                dropDownPanel = _this.dropDownPanel,
                setting = _this.setting,
                offset = dropDown.offset();

            var isFixed = false, fixedTop = null;
            dropDown.parents().each(function () {
                isFixed |= $(this).css('position') == 'fixed';
                if ($(this).css("position") == "fixed") {
                    fixedTop = parseInt($(this).css("top"));
                }
                return !isFixed;
            });

            //check the dropdown if inDialog.
            var inDialog = false,
                topDistance = 0,
                dropDownWidth = dropDown.outerWidth(true),
                dropDownHeight = dropDown.outerHeight(true);

            if (setting.dialogClass) {
                inDialog = dropDown.closest(setting.dialogClass).length > 0;
            }

            if (isFixed) {
                position = "fixed";
                var relocateEl = $(setting.relocateEl);
                //changed the order of this if / else if statement.  If it is "inDialog" it should calculate it that way regardless of if the "relocateEl" is there - Adriane 2012-12-17 - BTNET ID 675
                if (inDialog) {
                    topDistance = dropDownHeight + offset.top - $(document).scrollTop();
                } else if (relocateEl.length > 0) {
                    topDistance = dropDownHeight + fixedTop + (dropDown.offset().top - relocateEl.offset().top);
                }
            } else {
                position = "absolute";
            }

            dropDownPanel.data("SourceEl", dropDown);
            dropDownPanel.css({
                "position": position,
                "left": offset.left,
                "top": isFixed ? topDistance : (offset.top + dropDownHeight),
                "width": dropDownWidth < setting.minWidth ? setting.minWidth : dropDownWidth - 2
            });
        },
        open: function () {
            var _this = this,
                vars = _this.vars,
                dropDownPanel = _this.dropDownPanel,
                setting = _this.setting;

            if (setting.beforeShow && $.isFunction(setting.beforeShow)) {
                setting.beforeShow.call(_this);
            }

            dropDownPanel.slideDown(setting.animSpeed, function () {
                vars.openState = true;
                if (setting.afterShow && $.isFunction(setting.afterShow)) {
                    setting.afterShow.call(_this);
                }
            });
        },
        close: function () {
            var _this = this,
                vars = _this.vars,
                dropDownPanel = _this.dropDownPanel,
                setting = _this.setting;

            dropDownPanel.slideUp(setting.animSpeed, function () {
                vars.openState = false;
            });
        },
        setValue: function (inputVal) {
            var _this = this,
                vars = _this.vars,
                dropDown = _this.dropDown,
                dropDownPanel = _this.dropDownPanel,
                setting = _this.setting;

            var viInput = dropDown.is(":text") ? dropDown : dropDown.find(":text");
            if (viInput.length > 0) {
                viInput.val(inputVal);
            } else {
                dropDown.text(inputVal);
            }
        }
    };

    $.fn.viDropdown = function (options) {
        return this.each(function (key, value) {
            var element = $(this);
            // Return early if this element already has a plugin instance
            if (element.data('viDropdown')) return element.data('viDropdown');
            // Pass options to plugin constructor
            var viDropdown = new ViDropdown(this, options);
            // Store plugin object in this element's data
            element.data('viDropdown', viDropdown);
        });
    };
})(jQuery);

/* ------------ jquery  ViLinkComboBox ---------------------*/
; (function ($, undifined) {
    var ViLinkComboBox = function viLinkComboBox(element, options) {
        var defaults = {
            eventName: "click",
            targetEl: ".vi-animation-container",
            animSpeed: 100,
            minWidth: 120,
            minHeight: 100,
            maxHeight: 300,
            validateIntranetUrl: false,
            //zIndex: 1000,
            init: function (_this) {
                var linkComboBox = _this.dropDown,
                    setting = _this.setting,
                    input = linkComboBox.is(":text") ? linkComboBox : linkComboBox.find(".vi-input"),
                    hidden = input.next(),
                    popuPanel = _this.dropDownPanel;
                var validateIntranetUrl = this.validateIntranetUrl;
                if (setting.enableInput) {
                    $.validator.addMethod(input.attr("id") + "redirectUrl", function (value, element, param) {
                        var result = true;
                        if (input.is(":visible")) {
                            if (value.indexOf("?navid=") > -1 || value == "") {
                                return true;
                            }
                            if (validateIntranetUrl) {
                                if ($.isIntranetUrl(value)) return true;
                            }
                            result = $.isUrl(value);
                            if (!result) {
                                input.addClass("input-validation-error");
                            } else {
                                input.removeClass("input-validation-error");
                            }
                        }
                        return result;
                    }, $.validator.format(Vision.Resources.UI_Common_ViLinkComboBox_URLInValidError));

                    var ruleConfig = {};
                    ruleConfig[input.attr("id") + "redirectUrl"] = true;
                    window.setTimeout(function () {
                        hidden.rules("add", ruleConfig);
                    }, 50);
                    if (input.val() === "") {
                        input.val("http://");
                    }
                }
            }
        };
        var zIndex = $(element).getZIndex() + 1;
        var extendOptions = $.extend({ zIndex: zIndex }, defaults, options);
        this.linkComboBox = $(element);
        this.linkComboBox.viDropdown(extendOptions);
        //inherit from the base class
        $.extend(this, this.linkComboBox.viDropdown(extendOptions).data("viDropdown"));
    };

    $.fn.viLinkComboBox = function (options) {
        return this.each(function (key, value) {
            var element = $(this);
            // Return early if this element already has a plugin instance
            if (element.data('viLinkComboBox')) return element.data('viLinkComboBox');
            // Pass options to plugin constructor

            var viLinkComboBox = new ViLinkComboBox(this, options);
            // Store plugin object in this element's data
            element.data('viLinkComboBox', viLinkComboBox);
        });
    };
})(jQuery);

/* ------------ jquery  ViQuickLink ---------------------*/
; (function ($) {
    var ViQuickLink = function (element, options) {
        var defaults = {
            init: null,
            runTemplates: function (num) { },
            insertRowCall: $.noop,
            removeRowCall: $.noop,
            registeValidate: $.noop
        };

        this.setting = $.extend({}, defaults, options);
        this.quickLink = $(element);

        if (defaults.runTemplates == null || !$.isFunction(defaults.runTemplates)) {
            alert(Vision.Resources.UI_Common_ViQuickLink_RunTemplatesMethodFailedError);
            return;
        }

        this.initialize();
    };

    ViQuickLink.prototype = {
        initialize: function () {
            var _this = this,
                setting = _this.setting,
                quickLink = _this.quickLink;

            $(".addlink", quickLink).live("click", function () {
                var row = $(this).closest("tr");
                _this.addRow(row);
            });
            $(".deletelink", quickLink).live("click", function () {
                var row = $(this).closest("tr");
                _this.removeRow(row);
            });

            _this.registeValidate(quickLink, "add");

            if (setting.init && $.isFunction(setting.init)) {
                setting.init(quickLink);
            }
        },
        addRow: function (row) {
            var _this = this,
                setting = _this.setting,
                quickLink = _this.quickLink,
                editorRowHtml = [],
                tbody = row.parent(),
                num = tbody.find("tr").length;

            editorRowHtml = setting.runTemplates(num);

            if ($.isArray(editorRowHtml)) {
                row.after(editorRowHtml.join(''));
            }
            var removeLinkTemp = "<a href=\"javascript:void(0);\" title=\"" + Vision.Resources.UI_Common_ViQuickLink_DeleteLinkButtonTitle + "\" class=\"deletelink\"></a>";
            if (tbody.find("tr").length == 2) {
                tbody.find("tr:first").find("td:last").html(removeLinkTemp);
            }
            _this.registeValidate(quickLink);

            if (setting.insertRowCall && $.isFunction(setting.insertRowCall)) {
                setting.insertRowCall(row.next());
            }
        },
        removeRow: function (row) {
            var _this = this,
                setting = _this.setting,
                tbody = row.parent();

            _this.registeValidate(row, false);
            row.remove();

            if (tbody.find("tr").length == 1) {
                tbody.find(".deletelink").remove();
            }

            if (setting.removeRowCall && $.isFunction(setting.removeRowCall)) {
                setting.removeRowCall();
            }
        },
        registeValidate: function (row, addRule) {
            var command = addRule == null ? "add" : addRule ? "add" : "remove";
            switch (command) {
                case "add":
                    $(":text", row).each(function () {
                        if ($(this).hasClass("link_name")) {
                            $(this).rules(command, {
                                required: true,
                                messages: {
                                    required: Vision.Resources.UI_Common_ViQuickLink_LinkNameIsRequiredMessage
                                }
                            });
                        }

                        if ($(this).hasClass("link_url")) {
                            $(this).rules(command, {
                                required: true,
                                messages: {
                                    required: Vision.Resources.UI_Common_ViQuickLink_LinkURLIsRequiredMessage
                                }
                            });
                        }
                    });
                    break;
                case "remove":
                    $(".link_name", row).each(function () { $(this).rules(command); });
                    $(".link_url", row).each(function () { $(this).rules(command); });
                    break;
            }
        },
        generateJsonObj: function () {
            var _this = this,
                quickLink = _this.quickLink,
                linkNo = 1,
                linkName = linkUrl = linkTarget = "",
                linkJsonObjArray = [];
            linkJsonArray = ['['];

            $("tbody tr", quickLink).each(function () {
                var row = $(this);
                linkName = row.find(".link_name").val();
                linkUrl = row.find(".link_url").val();
                linkTarget = row.find(".linkTarget").val();

                if ($.trim(linkName) != "" && $.trim(linkUrl) != "") {
                    var json = "{ 'ID':" + linkNo + ", 'Name':'" + linkName + "', 'LinkUrl':'" + linkUrl + "', 'LinkTarget':'" + linkTarget + "', 'Order': " + linkNo + " }";
                    linkJsonObjArray.push(
                    {
                        ID: linkNo,
                        Name: linkName,
                        LinkUrl: linkUrl,
                        LinkTarget: linkTarget,
                        Order: linkNo
                    });
                    if (linkNo > 1) {
                        linkJsonArray.push(",");
                    }
                    linkJsonArray.push(json);
                    linkNo += 1;
                }
            });
            linkJsonArray.push(']');

            if (linkNo == 1) {
                linkJsonArray = [];
            }
            //return linkJsonArray.join('');
            return JSON.stringify(linkJsonObjArray);
        },
        enable: function (enabled) {
            var _this = this,
                quickLink = _this.quickLink;
            if (typeof enabled == 'undefined' || enabled == null) {
                enabled = true;
            }
            _this.registeValidate(quickLink, enabled);
        }
    };

    $.fn.viQuicklink = function (options) {
        return this.each(function (key, value) {
            var element = $(this);
            // Return early if this element already has a plugin instance
            if (element.data('viQuicklink')) return element.data('viQuicklink');
            // Pass options to plugin constructor
            var viQuicklink = new ViQuickLink(this, options);
            // Store plugin object in this element's data
            element.data('viQuicklink', viQuicklink);
        });
    };
})(jQuery);

//jQuery element Extend
; (function ($) {
    $.fn.extend({
        rebindUnobtrusiveValidation: function () {
            if ($(this).is("form")) {
                $(this).removeData("validator")
                       .removeData("unobtrusiveValidation");
                $.validator.unobtrusive.parse($(this));
            }
            return $(this);
        },
        getZIndex: function () {
            var zIndex;
            $(this).parents().andSelf().each(function () {
                zIndex = $(this).css('zIndex');
                if (parseFloat(zIndex)) {
                    zIndex = parseFloat(zIndex) + 1;
                    return false;
                }
            });
            return zIndex == 'auto' ? 1 : zIndex; // 'auto' causes problems if there is Upload behind the dropdown
        },
        xBrowserAddHandler: function (eventName, handlerName) {
            $(this).each(function () {
                var target = this;
                if (target.addEventListener)
                    target.addEventListener(eventName, handlerName, false);
                else if (target.attachEvent)
                    target.attachEvent("on" + eventName, handlerName);
                else
                    target["on" + eventName] = handlerName;
            });
            return $(this);
        },
        iframeLoad: function (callback) {
            return $(this).filter("iframe").xBrowserAddHandler("load", callback);
        },
        tempMessage: function (options) {
            var defaultOptions = { message: "", cssClass: "" };
            var _opt = $.extend(defaultOptions, options);
            var $this = $(this);
            if (!$this.hasClass("vi-temp-message-container")) {
                $this.addClass("vi-temp-message-container");
            }
            var message = _opt.message || $this.html();
            if (message) {
                if (message.charAt(0) === '!') {
                    message = message.slice(1);
                    $this.addClass("vi-temp-message-container-error");
                }
                var fadeInTimeout = setTimeout(function () {
                    $this.html(message);
                    $this.fadeIn(200);
                    var fadeoutTimeout = setTimeout(function () {
                        $this.fadeOut(500, function () {
                            $this.html("");
                        })
                        clearTimeout(fadeoutTimeout);
                    }, 2000);

                    clearTimeout(fadeInTimeout);
                }, 200);
            }
        },
        loading: function (isSucceed, options, clear) {
            var $this = $(this);
            var defaults = {
                text: "",
                description: "",
                className: ""
            };
            options = $.extend({}, defaults, options);
            if (typeof clear != 'undefined' && clear == true) {
                if (options && options.hideCurrent == true) {
                    $this.find("div.loading").remove();
                }
                else {
                    $("div.loading", "body").remove();
                }
            }
            else {
                succeed = typeof (isSucceed) == 'undefined' || isSucceed ? true : false;
                var text = options.text || (isSucceed ? Vision.Resources.UI_Common_Loading_LoadingText : Vision.Resources.UI_Common_Loading_LoadFailedText);
                var cssClass = isSucceed ? "succeed" : "failed";
                if ($this.find("div.loading").length <= 0) {
                    var loadingHtml = "<div class='loading' style='display:none'><span class='" + cssClass + "'>" + text + "<span/></div>";
                    $this.append(loadingHtml);
                    if (options.description) {
                        $this.find("div.loading").append($("<div class='loading-description'></div>").html(options.description));
                    }
                }
                if (options.className) {
                    $this.find("div.loading").addClass(options.className);
                }

                function setPosition($this) {
                    var loadingDiv = $this.find("div.loading"),
                        height = $this.outerHeight(),
                        width = $this.outerWidth();
                    var _options = $.extend({ mask: false, css: "", opacity: 0.8, width: width, height: height }, options);
                    if (typeof (_options.mask) != 'undefined' && _options.mask) {
                        loadingDiv.addClass("mask").removeClass("succeed").removeClass("failed").addClass(cssClass);
                    } else {
                        loadingDiv.removeClass("mask")
                    }
                    if (typeof (_options.css) != 'undefined') {
                        loadingDiv.addClass(_options.css);
                    }
                    var currentOffset = $this.offset();
                    loadingDiv.width(width)
                        .height(height)
                        .css({ display: "block", position: "absolute" })
                        .offset({ top: currentOffset.top, left: currentOffset.left })
                        .css("opacity", _options.opacity)
                        .css("z-index", 99999)
                        .css("overflow", "hidden");
                    if (_options.width != null) {
                        loadingDiv.width(_options.width);
                    }
                    if (_options.height != null) {
                        loadingDiv.height(_options.height);
                    }

                    var loadingDescription = loadingDiv.find("div.loading-description");
                    var span = loadingDiv.find(">span");
                    var containerWidth = containerHeight = 0;

                    if ($this.is("body") || $this.is(document)) {
                        loadingDiv.width($(document).width());
                        loadingDiv.height($(document).height());
                        containerWidth = $(window).width();
                        containerHeight = $(window).height();
                        span.css({
                            position: "fixed"
                        });
                        loadingDescription.css({
                            position: "fixed"
                        });
                    } else {
                        containerWidth = loadingDiv.outerWidth(true);
                        containerHeight = loadingDiv.outerHeight(true);
                        span.css({
                            position: "absolute"
                        });
                        loadingDescription.css({
                            position: "absolute"
                        });
                    }

                    span.css({
                        top: (containerHeight - span.outerHeight()) / 2,
                        left: (containerWidth - span.outerWidth()) / 2
                    });
                    loadingDescription.css({
                        top: (containerHeight + loadingDescription.outerHeight()) / 2,
                        left: (containerWidth - loadingDescription.outerWidth()) / 2
                    });
                }
                setPosition($this);
                $(window).resize(function () {
                    //setPosition($this);
                });
            }
            return $this;
        },
        closestClientDialog: function () {
            var selector = ".v-viClientDialog";
            var dialog = null;
            try {
                dialog = $(this).closest(selector).data("viClientDialog");
                if (!dialog) {
                    //if use iframe
                    var p$ = self.parent.$;
                    var allIframes = p$("iframe");
                    $(allIframes).each(function (i, n) {
                        var frameWindow = n.window || n.contentWindow;
                        if (frameWindow == self) {
                            var currentFrame = n;
                            dialog = p$(currentFrame).closest(selector).data("viClientDialog");
                        }
                    });
                }
            } catch (err) {
                //
            }
            return dialog;
        },
        outerHtml: function () {
            var $this = this;
            return $($('<div></div>').html($this.clone())).html();
        },
        hasXScrollBar: function () {
            var domElement = this.get(0);
            return this.is("body") || this.is(document) || this.is(window) ?
                    (domElement.scrollWidth > domElement.clientWidth) :
                    (domElement.scrollWidth > domElement.clientWidth) && (this.css("overflow") == "auto" || this.css("overflow-x") == "auto");
        },
        hasYScrollBar: function () {
            var domElement = this.get(0);
            return this.is("body") || this.is(document) || this.is(window) ?
                    (domElement.scrollHeight > domElement.clientHeight) :
                    (domElement.scrollHeight > domElement.clientHeight) && (this.css("overflow") == "auto" || this.css("overflow-y") == "auto");
        },
        hasScrollBar: function () {
            var domElement = this.get(0);
            return this.hasXScrollBar() || this.hasYScrollBar();
        },
        isFixed: function () {
            return this.css("position") == "fixed";
        },
        inFixed: function () {
            var isFixed = false;
            $(this).parents().andSelf().each(function () {
                isFixed |= $(this).isFixed();
                return !isFixed;
            });
            return isFixed;
        },
        inScroll: function () {
            var inScroll = false;
            this.parents().andSelf().each(function () {
                inScroll |= $(this).hasScrollBar();
                return !inScroll;
            });

            return Boolean(inScroll);
        }
    });

    if (typeof ($.visionViewState) == 'undefined') {
        $.extend({
            visionViewState: function () {
                return new visionViewState({
                    conatiner: "input[name='_cms_custom_view_input']"
                });
            }
        });
    }

    if (typeof ($.validator) != 'undefined') {
        $.validator.addMethod("cmsFileExtension", function (value, element, params) {
            return $.isFileInputExtensionValid(element, params[0], params[1]);
        }, Vision.Resources.UI_Common_FileExtensionIsNotValid);

        $.validator.addMethod("checkBoxListRequired", function (value, element, params) {
            var result = $.isEmpty(value);
            if (result) {
                params[0].addClass("input-validation-error");
            } else {
                params[0].removeClass("input-validation-error");
            }
            return !result;
        }, Vision.Resources.UI_Common_CheckBoxList_RequireValidError);
    }
})(jQuery);


//Copy To When Change
var initCopyToWhenChange = function () {
    $("input[copyToWhenChanged],textarea[copyToWhenChanged],select[copyToWhenChanged]").change(function () {
        var funcAttr = $(this).attr("copyToFuncWhenChanged");
        var value = null;
        if (funcAttr != null && funcAttr != "") {
            value = $.evalFunc(funcAttr)();
        }
        else {
            if ($(this).is(":checkbox")) {
                value = $(this).prop("checked");
            }
            else {
                value = $(this).val();
            }
        }
        var copyToEle = $($(this).attr("copyToWhenChanged"));
        if (copyToEle.is(":checkbox")) {
            copyToEle.prop("checked", value);
        }
        else {
            if ($(this).is("select")) {
                if ($(this).val() != null && $(this).val() != "") {
                    var text = $("option[value=" + $(this).val() + "]", $(this)).text();
                    setText(copyToEle, text);
                } else {
                    setText(copyToEle, "");
                }
            }
            else {
                setText(copyToEle, value);
            }
        }
    });

    function setText(element, text) {
        if (element.is("input") || element.is("textarea")) {
            element.val(text);
        } else {
            element.text(text);
        }
    }
}

var initializeMask = function (context, triggerSelf) {
    context = $.prepareTriggerOnloadParams(context, triggerSelf);
    //for the input masked.
    if (typeof $.prototype.mask != 'undefined') {
        $(context + "[inputMasked]input").each(function () {
            var element = $(this);

            if (element.attr("maskedPlaceHolder")) {
                element.mask(element.attr("inputMasked"), { placeholder: element.attr("maskedPlaceHolder") });
            } else {
                element.mask(element.attr("inputMasked"));
            }

            if (!element.attr("data-val-required")) {
                element.bind("focusout", function (e) {
                    if ($.isEmpty(element.val())) {
                        element.removeClass("input-validation-error");
                    }
                    return false;
                });
            }
        });
    }
    $(context + "[maskedType]input").each(function () {
        var element = $(this);

        if (element.attr("maskedType").toLowerCase() == "number") {
            var maxLength = 0;
            if (element.attr("maskedMaxLength")) {
                maxLength = parseInt(element.attr("maskedMaxLength"));
            }

            element.keydown(function (event) {
                if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
                  (event.keyCode == 65 && event.ctrlKey === true) ||
                  (event.keyCode >= 35 && event.keyCode <= 39)) {
                    // let it happen, don't do anything 
                    return;
                }
                else {
                    // Ensure that it is a number and stop the keypress 
                    if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                        event.preventDefault();
                    } else {
                        if (element.val().length >= maxLength) {
                            event.preventDefault();
                        }
                    }
                }
            });
        }

        if (element.attr("maskedType").toLowerCase() == "ext") {
            var maxLength = 0;
            if (element.attr("maskedMaxLength")) {
                maxLength = parseInt(element.attr("maskedMaxLength"));
            }

            element.keydown(function (event) {
                if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 ||
                  (event.keyCode == 65 && event.ctrlKey === true) ||
                  (event.keyCode >= 35 && event.keyCode <= 39)) {
                    // let it happen, don't do anything 
                    return;
                }
                else {
                    // Ensure that it is a number and stop the keypress 
                    if (
                        (!(event.ctrlKey === true && event.keyCode == 67) && !(event.ctrlKey === true && event.keyCode == 86))
                        &&
                        ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105))
                        ) {
                        event.preventDefault();
                    } else {
                        if (element.val().length >= maxLength) {
                            event.preventDefault();
                        }
                    }
                }
            });
        }
    });
};

var initializeTempAndTip = function (context, triggerSelf) {
    context = $.prepareTriggerOnloadParams(context, triggerSelf);
    // initialize poshytip
    if ($.fn.poshytip) {
        $(context + ".vi-poshytip[title]").poshytip();
        $(context + ".vi-poshytip[title].click-show").bind("click", function () {
            var item = $(this),
                poshytip = item.data("poshytip");

            if (poshytip && poshytip.$tip.data("active")) {
                item.poshytip("hide");
            } else {
                item.poshytip("show");
            }
        });
    }
    // initialize temp message
    if ($.fn.tempMessage) {
        $(context + ".vi-temp-message-container").tempMessage();
    }
};

var initializeFieldToolTip = function (context, triggerSelf) {
    context = $.prepareTriggerOnloadParams(context, triggerSelf);
    if ($.fn.poshytip) {

        /* Tooltip appears on the right side of the element */
        $(context + ".vi-fieldtooltip[title]").each(function (i, n) {
            var tipItem = $(n);

            tipItem.poshytip({
                className: 'tip-yellowsimple',
                alignTo: 'target',
                showOn: 'focus',
                alignX: 'right',
                alignY: 'center',
                offsetX: 5
            });

            if (tipItem.hasClass("click-show")) {
                tipItem.bind("click", function () {
                    var item = $(this),
                        poshytip = item.data("poshytip");

                    if (poshytip && poshytip.$tip.data("active")) {
                        item.poshytip("hide");
                    } else {
                        item.poshytip("show");
                    }
                });
            }

            // Only need reset z-index in dialog
            if (tipItem.closest(".vi-content").length > 0) {
                tipItem.data("poshytip").$tip.css("z-index", tipItem.getZIndex() + 1);
            }
        });

        /* Tooltip appears on top of the element */
        $(context + ".vi-fieldtooltip-top[title]").each(function (i, n) {
            var tipItem = $(n);

            tipItem.poshytip({
                className: 'tip-yellowsimple',
                alignTo: 'target',
                showOn: 'focus',
                alignX: 'center',
                alignY: 'top',
                offsetX: 5
            });

            tipItem.bind("click", function () {
                var item = $(this),
                    poshytip = item.data("poshytip");

                if (poshytip && poshytip.$tip.data("active")) {
                    item.poshytip("hide");
                } else {
                    item.poshytip("show");
                }
            });

            // Only need reset z-index in dialog
            if (tipItem.closest(".vi-content").length > 0) {
                tipItem.data("poshytip").$tip.css("z-index", tipItem.getZIndex() + 1);
            }
        });
    }
};

var __initializeNeedEnableForm = function (context, triggerSelf) {
    $("form.front_end_form[need-ajax-submit='true'][need-enable-form-after-ready='true']").each(function () {
        var $this = $(this);
        var needEnableSubmitButtonsClassAttr = $this.attr("need-enable-submit-buttons-class");
        if (typeof (needEnableSubmitButtonsClassAttr != "undefined")) {
            $this.find(needEnableSubmitButtonsClassAttr).prop("disabled", false);
        }
        else {
            $this.find("input[type='submit']").prop("disabled", false);
        }
    });
}

var initKendoMobileSwitch = function (context) {
    context = context || document;

    if ($.fn.kendoMobileSwitch) {
        $(context).find(".onoffswitch-checkbox").each(function (i, n) {
            var item = $(n);
            item.kendoMobileSwitch();
        });;
    }
};


$(function () {
    $.ajaxSettings.cache = false;

    // Copy From When Submit
    $(document).delegate("form", "submit", function () {
        $(this).find("input[copyFromFuncWhenSubmit],textarea[copyFromFuncWhenSubmit]").each(function (i, n) {
            var func = $.evalFunc($(n).attr("copyFromFuncWhenSubmit"));
            $(n).val(func());
        });
        $(this).find("input[copyFromWhenSubmit],textarea[copyFromWhenSubmit]").each(function (i, n) {
            var copyfrom = $(n).attr("copyFromWhenSubmit");
            $(n).val($(copyfrom).val());
        });

        // disable RadEditor TextArea
        if ($(this).attr("data-has-editor") == "true") {
            $(this).find("textarea.radeditor-textarea").attr("disabled", "disabled");
        }

        // ToDo check Javascript Validation
        $(this).find("input.phone,input.fax").each(function () {
            var val = $(this).val();
            var finalVal = val.replace(/[^\d]/ig, '');
            $(this).val(finalVal);
        });
    });
    //Copy to When Changed End
    $(document).delegate("input.self-action[type='submit'],.self-action", "click", function (e) {
        if (!e.isDefaultPrevented()) {
            var selfAction = $(this).attr("action");
            if (selfAction) {
                $(this).closest("form").attr("action", selfAction);
                if (!($(this).attr("type") == "submit" && this.tagName == "input")) {
                    $(this).closest("form").submit();
                }
            }
        } else {
            e.stopPropagation();
        }
    });

    $.unbindShowImageAnchorsClick();
    // Show Image Links
    $("body").delegate("a[href!='#'][href]", "click", function () {
        var href = $(this).attr("href") || "";
        var title = $(this).attr("title") || $(this).text();
        var exts = href.match(/[^'"]*?home\/showimage\s*(\?.*)/gi);
        if (exts) {
            var img = $("<img/>");
            img.attr("src", $(this).attr("href"));
            $("body").loading(true, { mask: true });
            img.error(function () {
                var errorMessageDiv = $("<div/>");
                errorMessageDiv.addClass("show_image_error_message");
                errorMessageDiv.html(Vision.Resources.FrontEnd_ShowImage_ErrorMessage);
                $.viClientDialog(
                 {
                     title: title,
                     html: errorMessageDiv,
                     useFrame: false,
                     width: 200,
                     height: 100
                 }).open();
                $("body").loading(null, null, true);
            });
            img.load(function () {
                var width = Math.min($(this).width(), $(window).width() - 30);
                var height = Math.min($(this).height(), $(window).height() - 60);
                $(img).css({ maxWidth: width, maxHeight: height });
                $.viClientDialog(
                 {
                     title: title,
                     html: $("<div/>").append(img),
                     useFrame: false,
                     padding: '0px 1px 0px 0px'
                 }).open();
                $("body").loading(null, null, true);
            });
            $("body").append(img);
            return false;
        }
    });

    //Copy to When Changed Start
    initCopyToWhenChange();

    // for Content Group
    $(".content-group-container select").change(function () {
        var copyToDest = $("input.copy-dest.cg-contentgroup");
        if ($(this).val() == "") {
            copyToDest.val("");
        }
        else {
            copyToDest.val($($(this).find("option")[this.selectedIndex]).text());
        }
    });
    if ($(".content-group-container").find("input[type='hidden']").length > 0) {
        $("input.copy-dest.cg-contentgroup").val($(".content-group-container").find("select").text());
    }

    $(".copy-placeholder-to-text[type='text']").focus(function () {
        var placeHolder = $(this).attr("placeholder");
        if ($(this).val() == "") {
            $(this).val(placeHolder);
            if (!$.support.placeholder) {
                //locate the cursor when broser is IE.
                var esrc = this;
                if (esrc == null) {
                    esrc = event.srcElement;
                }
                var rtextRange = esrc.createTextRange();
                rtextRange.moveStart('character', esrc.value.length);
                rtextRange.collapse(true);
                rtextRange.select();
            }
        }
    });
    $(".copy-placeholder-to-text[type='text']").blur(function () {
        var placeHolder = $(this).attr("placeholder");
        if ($(this).val() == placeHolder) {
            if (!$.support.placeholder) {
                var placeholderAttr = $(this).attr('placeholder');
                if (typeof placeholderAttr != 'undefined' && placeholderAttr != '' && ($(this).val() == '' || $(this).val() == placeholderAttr)) {
                    $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
                }
            }
            else {
                $(this).val("");
            }
        }
    });

    $(document).delegate("input[type='password'].notallowpaste", "keydown", function (e) {
        if (e.ctrlKey && e.keyCode == 86) {//Ctrl + V
            return false;
        }
    });
    $(document).delegate("input[type='password']", "contextmenu", function (e) {
        return false;
    });

    //var initializeFlexSlider = function (context, triggerSelf) {
    //    context = $.prepareTriggerOnloadParams(context, triggerSelf);
    //    if ($.fn.flexslider) {
    //        $(context + ".flexslider").flexslider();
    //    }
    //};

    $.pushOnloadFunc(initializeTempAndTip, true);
    $.pushOnloadFunc(initializeMask, true);
    $.pushOnloadFunc(initializeFieldToolTip, true);
    $.pushOnloadFunc(__initializeNeedEnableForm, true);
    //$.pushOnloadFunc(initKendoMobileSwitch, true);
    //$.pushOnloadFunc(initializeFlexSlider, true);

    // for component category name field validation  --- Start
    var changeFieldNameWhenValidation = function () {
        var $needUpdateField = $("input.need_update_field_name");
        if ($needUpdateField.length > 0) {
            $needUpdateField.each(function (i, n) {
                var $this = $(n);
                var requiredMessage = $this.attr("data-val-required");
                var lenthLimitMessage = $this.attr("data-val-length");
                var fieldValidationName = $this.attr("fieldValidationName");
                var originalFieldName = $this.attr("originalFieldName");

                var changedRequiredMessage = requiredMessage.replace(originalFieldName, fieldValidationName);
                var changedLenthLimitMessage = lenthLimitMessage.replace(originalFieldName, fieldValidationName);

                $this.attr("data-val-required", changedRequiredMessage);
                $this.attr("data-val-length", changedLenthLimitMessage);
            });
            var $form = $needUpdateField.closest("form");
            $form.rebindUnobtrusiveValidation();
        }
    };
    changeFieldNameWhenValidation();
    // for component category name field validation  --- End
});

/* TabStrip Lazy load Start ***************************************/
$(function () {
    var link = $("ul.t-tabstrip-items li.t-item.vi-tab-lazy-load a.t-link");
    link.live("click", function () {
        var tabItem = $(this);
        if (tabItem.prop("actived") != true) {
            var actionUrl = tabItem.attr("actionurl");
            var divUrl = tabItem.attr("href").split("#")[1];
            var tabContent = tabItem.closest("div.t-tabstrip").find("#" + divUrl.toString())
            tabContent.loading(true, { mask: true });

            var contentGroupID = $("#ContentGroup_ID").length > 0 && $("#ContentGroup_ID").is("select") ? $("#ContentGroup_ID").val() : 0;
            $.vision().get(actionUrl, { ContentGroupID: contentGroupID },
                function (data) {
                    tabItem.prop("actived", true);
                    setTimeout(function () {
                        tabContent.html(data);
                        initializeMask("body");
                        tabContent.loading(null, null, true);
                    }, 300);
                }
            );
        }
    });
});
/* TabStrip lazy load End ***************************************/

/****************** Tab Strip Start ***************/
$(function () {
    $("body").delegate(".vi-tabstrip-items .vi-item:not(.vi-state-active)", "click", function () {
        $(".vi-tabstrip-items .vi-state-active").each(function (i, n) {
            $(n).removeClass("vi-state-active");
            $($(n).attr("targetPanel")).hide();
        });
        $(this).addClass("vi-state-active");
        $($(this).attr("targetPanel")).show();
    });
});
/****************** Tab Strip End ***************/

/******************** Scroll Start ********************/
$(function () {
    $("body").delegate(".scroll_container .scroll_commands .scroll_command", "click", function () {
        var $this = $(this);
        var $container = $(".scroll_container .scroll_list")
        var allScrollEles = $container.find(".scroll_item");
        var totalCount = allScrollEles.length;
        var moveLeft = $this.is(".pre");
        var width = allScrollEles.width();
        var left = moveLeft ? ("-=" + width) : ("+=" + width);
        $(".scroll_container .scroll_list div.scroll_item").animate(
                { left: left },
                {
                    duration: 500,
                    easing: "linear",
                    complete: function () {
                        var position = $(this).position();
                        if (moveLeft) {
                            if (position.left == (1 - totalCount) * width) {
                                $(this).css("left", width).removeClass("current");
                            }
                            if (position.left == -width) {
                                $(this).addClass("current");
                            }
                        }
                        else {
                            if (position.left == (totalCount - 1) * width) {
                                $(this).css("left", -width).removeClass("current");
                            }
                            if (position.left == 0) {
                                $(this).addClass("current");
                            }
                        }
                    }
                });
    });
});
/******************** Scroll End **********************/

/* jQuery Query String */
; (function ($) {
    var QueryString = function (options) {
        this.urlParams = {};
        this.load();
    };
    QueryString.prototype = {
        load: function (param) {
            this.urlParams = {}
            var e, k, v,
                a = /\+/g,  // Regex for replacing addition symbol with a space
                r = /([^&=]+)=?([^&]*)/g,
                d = function (s) { return decodeURIComponent(s.replace(a, " ")); }
            if (!param) {
                param = window.location.search;
            }
            if (param.charAt(0) == '?') {
                param = param.substring(1);
            }
            while (e = r.exec(param)) {
                k = d(e[1]);
                v = d(e[2]);
                this.set(k, v);
            }
            return this;
        },
        toString: function (options) {
            var settings = {
                'hash': false,
                'traditional': true
            };
            if (options) {
                $.extend(settings, options);
            }
            var old = jQuery.ajaxSettings.traditional;
            jQuery.ajaxSettings.traditional = settings.traditional;
            var result = '?' + $.param(this.urlParams);
            jQuery.ajaxSettings.traditional = old;
            if (settings.hash)
                result = result + window.location.hash;
            return result;
        },
        set: function (k, v, replace) {
            replace = replace || false;
            if (replace)
                this.urlParams[k] = v;
            else {
                if (k in this.urlParams) {
                    if ($.type(this.urlParams[k]) === 'array') {
                        this.urlParams[k].push(v);
                    }
                    else {
                        if (this.urlParams[k] == '')
                            this.urlParams[k] = v;
                        else
                            this.urlParams[k] = [this.urlParams[k], v];
                    }
                }
                else
                    this.urlParams[k] = v;
            }
            return this;
        },
        get: function (k) {
            return this.urlParams[k];
        },
        remove: function (k) {
            if (k in this.urlParams) {
                delete this.urlParams[k];
            }
            return this;
        }
    };
    $.query_string = new QueryString();
})(jQuery);
/* jQuery Query String */

/* Calendar */
; (function ($) {
    var viCalendar = function (target, options) {
        this._init(target, options);
    };
    viCalendar.prototype = {
        _target: null,
        _options:
        {
            currentDate: new Date(),
            useDefaultNext: true,
            useDefaultPrev: true
        },
        _init: function (target, options) {
            options = options || {};
            var $this = this;
            $this._target = $(target);
            $this._options = $.extend($this._options, options);

            if ($this._options.useDefaultNext) {
                $(target).find(".calendar_title .calendar_nextprev a.next").click(function () {
                    $this._redirectToMonth($this._options.currentDate, 1);
                });
            }
            if ($this._options.useDefaultPrev) {
                $(target).find(".calendar_title .calendar_nextprev a.prev").click(function () {
                    $this._redirectToMonth($this._options.currentDate, -1);
                });
            }
        },
        _redirectToMonth: function (currentDate, monthDiff) {
            var currentYear = currentDate.getFullYear();
            var currentMonth = currentDate.getMonth() + 1;
            var nextMonth = currentMonth;
            var nextYear = currentYear;

            var compareNextMonth = currentMonth + monthDiff;
            if (monthDiff > 0) {
                nextMonth = compareNextMonth <= 12 ? compareNextMonth : 1;
                nextYear = compareNextMonth <= 12 ? currentYear : currentYear + 1;
            } else {
                nextMonth = compareNextMonth >= 1 ? compareNextMonth : 12;
                nextYear = compareNextMonth >= 1 ? currentYear : currentYear - 1;
            }
            $.query_string.set("curm", nextMonth, true);
            $.query_string.set("cury", nextYear, true);
            window.location = $.query_string.toString();
        }
    };

    $.prototype.extend({
        viCalendar: function (options) {
            $(this).data("data-viCalendar", new viCalendar($(this), options));
        }
    });
})(jQuery);
/* Calendar */

/********************* Added  by Jung Start *****************/
/*tabs*/
$(function () {
    if (typeof $.prototype.tabs != 'undefined' && $.isFunction($.prototype.tabs)) {
        //        $("#WidgetTabControl").tabs();
        //        $("#SecurityRoleTabControl").tabs();
        //        $("#PageEditTabControl").tabs();
    }
});

// date time picker
var bindDateTimePicker = function (pickerEles, pickerFunc, _tpCallBack) {
    if (typeof $.prototype[pickerFunc] != 'undefined') {
        var tpCallBack = _tpCallBack;
        $(pickerEles).each(function (i, n) {
            var element = $(n);
            var nextSlibing = element.next();
            if (!(nextSlibing.is("a") && nextSlibing.hasClass("calendar_icon"))) {
                var calendarIcon = $('<a class="calendar_icon"><span class="icon_button">Pick date from calendar</span></a>');
                element.after(calendarIcon);

                if (!element.prop("disabled")) {
                    $(calendarIcon).click(function () {
                        element.focus();
                    });
                }
            }
            var option = {
                hourGrid: 3,
                minuteGrid: 15,
                enableInput: true,
                filterTime: null,
                updateDateTimeCallback: function (datePicker, dp_inst, formattedDateTime) {
                    var _defaults = datePicker._defaults;
                    if (_defaults.filterTime) {
                        var filterTimeOption = $.parseJSON(_defaults.filterTime);
                        var filterTime = { hour: filterTimeOption.Hour, minute: filterTimeOption.Minute };
                        var filterTimeStr = $.datepicker.formatTime(_defaults['timeFormat'], filterTime, _defaults);

                        if (filterTimeStr.toLowerCase() == datePicker.formattedTime.toLowerCase()) {
                            return formattedDateTime;
                        } else {
                            formattedDateTime += _defaults.separator + datePicker.formattedTime + _defaults.timeSuffix;
                            return formattedDateTime;
                        }
                    } else {
                        return formattedDateTime += _defaults.separator + datePicker.formattedTime + _defaults.timeSuffix;
                    }
                },
                separator: ' ', //fix the bug for don't know the dateTime type,
                yearRange: 'c-50:c+20'
            };

            var optionAttr = element.attr("date_time_picker_option");
            if (typeof optionAttr != 'undefined') {
                option = $.extend(option, $.parseJSON(optionAttr));
                if (option.onClose && typeof option.onClose == 'string') {
                    //We should use the $.evalFunc, because the eval has a bug in IE8.
                    option.onClose = $.evalFunc(option.onClose);
                }
                if (option.onSelect && typeof option.onSelect == 'string') {
                    option.onSelect = $.evalFunc(option.onSelect);
                }
                if (option.beforeShowDay && typeof option.beforeShowDay == 'string') {
                    option.beforeShowDay = $.evalFunc(option.beforeShowDay);
                }
                if (option.minDate && typeof option.minDate == 'string') {
                    option.minDate = new Date(option.minDate);
                }
                if (option.maxDate && typeof option.maxDate == 'string') {
                    option.maxDate = new Date(option.maxDate);
                }

                if (option.showNowButton && typeof option.showNowButton == 'boolean') {
                    option.showNowButton = option.showNowButton;
                }

                if (option.renderDate && typeof option.renderDate == 'string') {
                    option.renderDate = $.evalFunc(option.renderDate);
                }
            }

            element[pickerFunc](option);

            var parentForm = element.closest("form");
            parentForm.bind("submit", function () {
                var formValidator = parentForm.data("validator");
                console.log(formValidator);
                if (formValidator && formValidator.valid()) {
                    console.log(formValidator.valid());
                    element.val($.datepicker.replaceDotInTime(element.val()));
                }
            });

            if (!option.enableInput) {
                element.keydown(function (e) {
                    var k = e.which;
                    //keep the BackSpace enable.
                    if (k != 8) {
                        return false;
                    }
                });
            }

            if (typeof tpCallBack != "undefined" && $.isFunction(tpCallBack)) {
                tpCallBack(n, option);
            }
        });
    }
};

var bindAllDateTimePicker = function (context) {
    if (typeof context == "object") {
        bindDateTimePicker($(context).find(".ui_need_date_time_picker"), "datetimepicker", function (n, option) {
            var date = null;
            if ($(n).val()) {
                $(n).datetimepicker('setDate', new Date($(n).val()));
            }
        });
        bindDateTimePicker($(context).find(".ui_need_date_picker"), "datepicker", function (n, option) {
            if ($(n).val()) {
                var date = new Date($(n).datepicker("getDate"));
                $(n).datepicker("setDate", date);
            }
        });
        bindDateTimePicker($(context).find(".ui_need_time_picker"), "timepicker");
    }
    else {
        context = context || "";
        bindDateTimePicker(context + ".ui_need_date_time_picker", "datetimepicker", function (n, option) {
            var date = null;
            if ($(n).val()) {
                $(n).datetimepicker('setDate', new Date($(n).val()));
            }
        });
        bindDateTimePicker(context + ".ui_need_date_picker", "datepicker", function (n, option) {
            if ($(n).val()) {
                var date = new Date($(n).datepicker("getDate"));
                $(n).datepicker("setDate", date);
            }
        });
        bindDateTimePicker(context + ".ui_need_time_picker", "timepicker");
    }
};

$(function () {
    /******toolbar open and close********************/
    /******toppanel code added so that the toppanel adjusts its position correctly if the toolbar is closed - Adriane 06-13-2012**********/
    $('#toolbar .toggle').click(function () {
        if ($("#toolbar ul").is(":hidden")) {
            $("#toolbar ul").slideDown('400');
            $('#toolbar').toggleClass('closed');
            $.cookie('data-my-task', 'visible');
            if ($("#toppanel")) { $("#toppanel").css('margin-top', '0'); }
        } else {
            var offsetHeight = document.getElementById("toolbar").clientHeight;
            var marginTop = parseInt(offsetHeight) - 10;
            var negMarginTop = '-' + marginTop + 'px';
            $("#toolbar ul").slideUp('400', function () { $('#toolbar').toggleClass('closed'); });
            if ($("#toppanel")) { $("#toppanel").css('margin-top', negMarginTop); }
            $.cookie('data-my-task', 'hidden');
        }
    });
    if ($.cookie('data-my-task') == 'hidden') {
        //changed to try to eliminate sliding motion on page load if user has toolbar hidden - Adriane 2012/05/24
        //$("#toolbar ul").slideUp('400', function () { $('#toolbar').toggleClass('closed'); });
        var offsetHeight = document.getElementById("toolbar").clientHeight;
        var marginTop = parseInt(offsetHeight) - 10;
        var negMarginTop = '-' + marginTop + 'px';
        $("#toolbar ul").css('display', 'none');
        $('#toolbar').toggleClass('closed');
        if ($("#toppanel")) { $("#toppanel").css('margin-top', negMarginTop); }
    } else {
        $("#toolbar ul").css('display', 'block');
        if ($("#toppanel")) { $("#toppanel").css('margin-top', '0'); }
    }

    /****added so that the toppanel will stay at the top of the screen once the user has scrolled past it.- Adriane 06-13-2012****/
    function toppanel_relocate() {
        var window_top = $(window).scrollTop();
        /***the page_title may be not exist, so should check it. Such as: LogOn - Jianzhuang Gao 06-14-2012**/
        var pageTitle = $('.page_title');
        if (pageTitle.length > 0) {
            var div_top = pageTitle.offset().top;
            /**edit by: jianzhuang gao. If the height of the toppanel is more than the height of the window, it should remove the "sticky" class, 
            else will make the browser screen unexpected shake in 1024*768 screen mode.**/
            var winHeight = $(window).height();
            var headerNavHeight = $("#header_nav").outerHeight(true);
            var topPanelHeight = $('#toppanel').outerHeight(true);
            if (window_top > div_top && topPanelHeight < (winHeight - headerNavHeight))
                $('#toppanel').addClass('sticky')
            else
                $('#toppanel').removeClass('sticky');

            //For Bug: 16401: RadEditor Toggle Full Screen acts up in toppanel.
            if($("#toppanel").data("isRadEditorFullScreen"))
                $('#toppanel').removeClass('sticky');
        }
    };
    $(function () {
        /**should not go to position fixed on small screens*/
        if ((document.getElementById('toppanel')) && ($(window).width() > 480)) {
            $(window).scroll(function () {
                toppanel_relocate();
                return false;
            });
            toppanel_relocate();
        }
    });

    /****added so that the widgets will stay at the top of the screen once the user has scrolled past it.- Adriane 07-11-2012****/
    function widgets_relocate() {
        var window_top = $(window).scrollTop();

        if ($('.page_title').length > 0) {
            var div_top = $('.page_title').offset().top;
            if (window_top > div_top)
                $('#WidgetTabControl').addClass('sticky')
            else
                $('#WidgetTabControl').removeClass('sticky');
        }
    };
    $(function () {
        /**should not go to position fixed on small screens*/
        if ((document.getElementById('WidgetTabControl')) && ($(window).width() > 480)) {
            $(window).scroll(widgets_relocate);
            widgets_relocate();
        }
    });

    $(function () {
        /****added so that the top bar will stay at the top of the screen once the user has scrolled past it.- Adriane 09-04-2012****/
        function topbar_relocate() {
            var window_top = $(window).scrollTop();

            if ($('.front_end_body').length > 0) {
                var div_top = $('.front_end_body').offset().top;
                if (window_top > div_top)
                    $('#top_bar').addClass('sticky')
                else
                    $('#top_bar').removeClass('sticky');
            }
        };

        /****added so that the toppanel will adjust position when the window has been resized and the header has gotten taller..- Adriane 06-21-2012****/
        function toppanelOffset() {
            var bodyPlaceHolderOffset = $("#body_place_holder").offset();
            $("div#toppanel").css({
                top: bodyPlaceHolderOffset && bodyPlaceHolderOffset.top > 0 ? bodyPlaceHolderOffset.top : 221,
                display: "block"
            });
        };

        /**should not go to position fixed on small screens*/
        if ((document.getElementById('top_bar')) && ($(window).width() > 480)) {
            $(window).scroll(topbar_relocate);
            topbar_relocate();
        }

        if (document.getElementById('toppanel')) {
            var resizeTimer;
            $(window).bind("resize", function () {
                resizeTimer && clearTimeout(resizeTimer);
                resizeTimer = setTimeout(toppanelOffset, 100);
            });
        }

        /******Icon legend open and close - added by Adriane********************/
        $('#icon_legend .toggle').click(function () {
            if ($("#icon_legend .legend_list").is(":hidden")) {
                $("#icon_legend .legend_list").slideDown('400');
                $('#icon_legend').toggleClass('closed');
                $.cookie('data-legend', 'visible');
            } else {
                $("#icon_legend .legend_list").slideUp('400', function () { $('#icon_legend').toggleClass('closed'); });
                $.cookie('data-legend', 'hidden');
            }
        });

        if ($.cookie('data-legend') == 'hidden') {
            $("#icon_legend .legend_list").slideUp('400', function () { $('#icon_legend').toggleClass('closed'); });
        }

        /******release notes open and close - added by Adriane********************/
        $('tr').not(":first-child").find('.release_notes_version').click(function () {

            var clickedNotes = $(this).parent().find('.release_notes_note');
            clickedNotes.toggle();
            $(this).toggleClass('notesShown');
        });

        /******sidenav open and close for mobile - added by Adriane 9/20/2012********************/
        $('.sidenav .mobile_header').click(function () {
            $(this).parent().toggleClass('open');
        });
        /**mobile sidenav hide siblings of current expanded page and hide sidenav entirely if empty**/
        if (($('.sidenav').length > 0) && ($(window).width() < 648)) {
            $('.sidenav .sidenav_expanded').siblings().css('display', 'none');
            if (($('.sidenav .sidenav_current').length > 0) && ($('.sidenav .sidenav_current.sidenav_expanded').length == 0)) {
                $('.sidenav h2').css('display', 'none');
            }
        }

        /**search options open and close************/
        $('.settingicon').click(function (e) {
            $('.search_settings_pane').slideToggle('400');
            var frontend_id = $(e.target).closest('.content-filter-widget').attr('id');
            $('div#' + frontend_id + ' .frontend-search-settings-pane').slideToggle('400');
        });

        $(document).click(function (e) {
            if (!$(e.target).closest(".search_area").length > 0) {
                $(".search_settings_pane").slideUp('400');
            }
            if (!$(e.target).closest(".content-filter-widget").length > 0) {
                $(".frontend-search-settings-pane").slideUp('400');
            }
        });

        $('.edit_dashboard').click(function () {
            $(this).toggleClass('active');
            $('.dashboard_settings_pane').slideToggle('400');
        });
        $(document).click(function (e) {
            // Changed by Ding Yuliang;
            // we should check the .edit_dashboard is or not active.
            if (!$(e.target).closest(".dashboard_controls").length > 0 && $(".dashboard_controls .edit_dashboard").is(".active")) {
                $(".edit_dashboard").toggleClass('active');
                $(".dashboard_settings_pane").slideUp('400');
            }
        });

        // added by Ding Yuliang.
        // add js for My Task
        $('#toolbar .tools_show_list').click(function () {
            $(this).toggleClass('active');
            $('#toolbar').toggleClass('show_task_items');
            $('.task_settings_pane').slideToggle('400');
        });
        $(document).click(function (e) {
            // Changed by Ding Yuliang;
            // we should check the .edit_dashboard is or not active.
            if (!$(e.target).closest(".task_settings_pane").length > 0 && $(e.target).is(":not(.tools_show_list)") && $("#toolbar .tools_show_list").is(".active")) {
                $('#toolbar').toggleClass('show_task_items');
                $("#toolbar .tools_show_list").toggleClass('active');
                $(".task_settings_pane").slideUp('400');
            }
        });

        bindAllDateTimePicker();
        // this is only for social media (twitter). use different class
        $(".character-count-input").characterCounter({ maxLength: 140, ignoreCustomMsg: true, container: function (item) { return $(item).parent().parent(); } });

        $(window).scroll(function () {
            if ($(this).scrollTop() > 100) {
                $('.backToTop').fadeIn();
            } else {
                $('.backToTop').fadeOut();
            }
        });

        // scroll body to 0px on click
        $('.backToTop').click(function () {
            $('body,html').animate({
                scrollTop: 0
            }, 200);
            return false;
        });
    });

    // Added By Ding Yuliang 20120630
    // Tab in TextArea
    var tabHotKeyElementPress = function (e) {
        var tab = "\t";
        var target = e.target;
        var selectionStart = target.selectionStart;
        var selectionEnd = target.selectionEnd;

        if (e.keyCode == 9) {
            e.preventDefault();

            // Multiline selection
            if (selectionStart != selectionEnd && target.value.slice(selectionStart, selectionEnd).indexOf("\n") != -1) {
                var pre = target.value.slice(0, selectionStart);
                var sel = target.value.slice(selectionStart, selectionEnd);
                var post = target.value.slice(selectionEnd, target.value.length);
                if (sel.match(/\n(\t){1}/g))
                    var lines = sel.match(/\n(\t){1}/g).length + 1;
                else
                    var lines = sel.split(/\n/).length;

                if (!e.shiftKey) {
                    sel = sel.replace(/\n/g, "\n" + tab);
                    target.value = pre.concat(tab).concat(sel).concat(post);
                    target.selectionStart = selectionStart;
                    target.selectionEnd = selectionEnd + lines * tab.length;
                } else {
                    if (sel.match(/^(\t){1}/m) || sel.match(/\n(\t){1}/g)) {
                        sel = sel.replace(/^(\t){1}/m, "");
                        sel = sel.replace(/\n(\t){1}/g, "\n");

                        target.value = pre.concat(sel).concat(post);
                        target.selectionStart = selectionStart;
                        target.selectionEnd = selectionEnd - lines * tab.length;
                    }
                }
            }
                // No selection or sigle line selection
            else {
                if (!e.shiftKey) {
                    target.value = target.value.slice(0, selectionStart).concat(tab).concat(target.value.slice(selectionStart, target.value.length));
                    if (selectionStart == selectionEnd) {
                        target.selectionStart = target.selectionEnd = selectionStart + tab.length;
                    }
                    else {
                        target.selectionStart = selectionStart;
                        target.selectionEnd = selectionEnd + tab.length;
                    }
                } else {
                    if (selectionStart != selectionEnd) {
                        var pre = target.value.slice(0, selectionStart);
                        var post = target.value.slice(selectionEnd, target.value.length);
                        var sel = target.value.slice(selectionStart, selectionEnd);

                        if (sel.match(/^(\t){1}/)) {
                            sel = sel.replace(/^(\t){1}/, "");
                            target.value = pre.concat(sel).concat(post);
                            target.selectionStart = selectionStart;
                            target.selectionEnd = selectionEnd - tab.length;
                        }
                    }
                }
            }
        }
    };
    var enableTabHotKey = function (selector) {
        $(selector).keypress(function (e) { tabHotKeyElementPress(e); });
    };
    $(document).delegate(".need_tab_hotkey", "keydown", function (e) {
        tabHotKeyElementPress(e);
    });
    $(document).delegate("input.button_invoker[data-invoke-target]", "keydown", function (e) {
        if (e.keyCode == 13) { //enter
            $($(this).attr("data-invoke-target")).click();
        }
    });
});
/********************* Added  by Jung End *****************/

/* Editor Event Handlers Start ***************************************/
function onEditorClientPasteHtml(sender, args) {
    var commandName = args.get_commandName();

    // Nero - 2/15/2011 - bug 7355 - Hyperlink manager email links add ApplyClass to A tag
    if (commandName == "LinkManager") {
        var value = args.get_value();
        value = value.replace("class=ApplyClass", "");
        value = value.replace("class=\"ApplyClass\"", "");
        args.set_value(value);
    }
};
function onEditorClientCommandExecuting(editor, args) {
    var commandName = args.get_name();
    if (commandName == "InsertCustomLink") {
        if (editor.get_html() == "<P>&nbsp;</P>") {
            editor.set_html("");
        }
    }
    else if (commandName == "Help") {
        var url = $.vision().buildPath("Admin/Shared/ShowOnlineReference?appRelativeUrl=~%2FEditorTool");
        var opts = {
            title: "",
            url: url,
            //width: 750,
            //height: 600,
            useFrame: false,
            onClosed: function (data) {
                return;
            }
        };
        $.viClientDialog(opts).open();
        args.set_cancel(true);
    }
    else if (commandName == "WCAG") {
        var url = $.vision().buildPath("Admin/Shared/ShowOnlineReference?appRelativeUrl=~%2FWCAG");
        var opts = {
            title: "",
            url: url,
            //width: 650,
            //height: 750,
            useFrame: false,
            onClosed: function (data) {
                return;
            }
        };
        $.viClientDialog(opts).open();
        args.set_cancel(true);

    }
    else if (commandName.indexOf("CustomizedHTMLCommand_") >= 0) {
        editor.setFocus();
        var val = args.get_value();
        editor.pasteHtml(val);
        args.set_cancel(true);
    }
    else {
        if (commandName == "ImageManager" || commandName == "DocumentManager" || commandName == "LinkManager") {
            editor.setFocus();
        }
    }
};
function onEditorClientCommandExecuted(editor, args) {
    var commandName = args.get_commandName();
    //if (commandName == "PastePlainText") {
    //// When the editor is in light-box, we need set the Paste Dialog z-index according to the editor.
    //    var pastePlainTextWindow = $("#RadWindowWrapper_" + editor._element.id + "_dialogOpenerCleanPasteTextContent");
    //    pastePlainTextWindow.css("z-index", $("#"+editor._element.id).getZIndex() + 1);
    //}
};

// We will intercept the Telerik Editor ShowDialog method.
function onEditorShowDialog(dialogName, args) {
    /*2014-04-11, by panhaikuo
      Remove the width/#wrapper/bodyWidth/margin-left/margin-top logic. 
      Because the dialog cannot closed in IE9/IE10 after upgrade to Q1_2014 version.
      And the overlay issue has fixed in Telerik.Web.UI.Window.RadWindowScripts.js. We move its default parant under the body node.
    */

    var editor = this;
    var zIndex = $("#" + editor._element.id).getZIndex();

    var allRadWindows = $(".RadWindow.RadWindow_Default.rwNormalWindow.rwTransparentWindow");
    var currentDialogFullID = "RadWindowWrapper_" + editor._element.id + "_dialogOpener" + dialogName;// commandName        
    var currentRadWindow = $(".RadWindow.RadWindow_Default.rwNormalWindow.rwTransparentWindow#" + currentDialogFullID);
    //if (dialogName == "ImageManager" || dialogName == "DocumentManager") {
    //    currentRadWindow.width(750);
    //}
    $(allRadWindows).each(function (i, n) {
        var nZIndex = $(n).getZIndex();
        if ($(n).attr("id") != currentDialogFullID && nZIndex > zIndex) {
            zIndex = nZIndex;
        }
    });

    var overlay = $("div.TelerikModalOverlay");
    if (overlay.is(":visible")) {
        //var bodyWidth = $("#wrapper").outerWidth();
        overlay.css("z-index", zIndex + 1);//.width(bodyWidth)
        //.appendTo("#wrapper");
        // sometimes, we need render the RADEditor in non-content-add/edit page, which the main section's width is not 100%,
        // the RADEditor's overlay won't mask the whole page, so we would better move it under the body node.
        // e.g. Meetings Manager/Default Setting/Cover Page

    }

    if (currentRadWindow.length > 0) {
        //currentRadWindow.appendTo("#wrapper");
        // By default, the RAD Window will append to Form element, but sometimes, if the form is under the overlay, 
        // the Window will be covered. So, we always append the window to the Wrapper as the overlay.
        // offset the window to the left half of the width, to center it. Added by Adriane
        //var radWindowOffset = "-" + currentRadWindow.outerWidth() / 2 + "px";
        //var radWindowOffsetTop = "-" + currentRadWindow.outerHeight() / 2 + "px";
        currentRadWindow.css({
            "z-index": zIndex + 2
            //"margin-left": radWindowOffset,
            //"margin-top": radWindowOffsetTop

        });
    }
}

function onEditorClientLoad(editor, args) {
    var closestForm = $(editor.get_element()).closest("form");
    closestForm.attr("data-has-editor", "true");

    /*[20160114] Commented out the following code because of bug not present.
    ***
    //[20140411]Changed by Ding Yuliang (BTNET 1549)
    //Issue, can't type when open Content Area Widget setting in Edit Page at the second time, only in IE.
    // We shall add the related class to the Ajax form with RadEditor.
    if ($telerik.isIE && (closestForm.hasClass("radeditor_auto_focus") || closestForm.closest("div.vi-content").length > 0)
    && editor.get_contentAreaMode() == Telerik.Web.UI.EditorContentAreaMode.Iframe) {
        if (editor.get_mode() == Telerik.Web.UI.EditModes.Design) {
            // editor.set_mode(Telerik.Web.UI.EditModes.Design); 
            setTimeout(function () {
                editor.setFocus();
                if (!$telerik.isIE) {
                    $(editor.get_document().body).blur();
                }
                //$(editor.get_contentWindow()).blur();
            }, 80);
        }
    }
    ***
    */

    if (editor._contentHiddenTextarea)
        $(editor._contentHiddenTextarea).addClass("radeditor-textarea");

    var element = editor.get_contentArea();
    // Changed By Ding Yuliang. I'm not sure we need add this class to the body of the RAD Editor.
    // But if we add the class, it will affect the "Apply CSS Class" dropdown toolbar when focus on the RAD Editor.
    $(element).attr("radeditorbody", "");
    if ($telerik.isChrome || $telerik.isSafari) {
        $telerik.addExternalHandler(element, "click", function (e) {
            if (e.srcElement.tagName == "IMG") {
                editor.selectElement(e.srcElement);
            }
        });
    }
    // Changed by Ding Yuliang. 2012/06/22
    // The RadEditor in Dialog is too small, but the version before 2012/06/17 was OK, 
    // I don't know the detail reason of the bug, (SHOULD be changesets during 2012/06/18-2012/06/21 caused this bug)
    // So, I hard code the width and height.

    //Changed by Adriane 2012/08/21
    //the hard coded height was causing the height to be too tall and overlap items below it in IE9 (Bug ID:  330), 
    //so I removed the height. Instead, a min-height was set in admin.css to prevent it from being too short.
    //editor.setSize("720", "");

    //fix the bug: first time open paste text dialog, browser will jump UP to the top of the page
    //Restored by Ding Yuliang, 20121204, According to BTNET 593, Jason's comments.
    //if (!$telerik.isIE) {
    //    editor.fire("PastePlainText");
    //    editor.get_dialogOpener()._dialogContainers.CleanPasteTextContent.close();
    //}

    // Changed by Gao Jianzhuang. 2013/06/21 start
    // Fix the bug 7545 [BTNET 1091]Forms & surveys Insert Question - table properties view has CSS class dropdown with wrong styles
    var simpleEditor = $(editor._element).closest("div.simple_editor");
    if (simpleEditor.length > 0 && !simpleEditor.hasClass("allow_applay_class")) {
        var applyClass = simpleEditor.find("ul.reToolbar").find("span.ApplyClass");
        var applyClassParent = applyClass.closest("li");
        applyClass && applyClassParent && applyClassParent.hide();
    }
    // Changed by Gao Jianzhuang. 2013/06/21 end

    if (editor.showDialog) {
        var originShowDialog = editor.showDialog;
        editor.showDialog = function (commandName, args, callback) {
            originShowDialog.call(editor, commandName, args, callback);
            onEditorShowDialog.call(editor, commandName, args);
        }
    }

    
    editor.add_toggleScreenMode(function () {
        var toppanel = $("#toppanel");
        var H = editor.get_element();
        if (editor._isFullScreen) {
            $(".vi-mask").hide();
            $("nav#header_nav").hide();
            //For Bug: 16401: RadEditor Toggle Full Screen acts up in toppanel.
            if (toppanel.length != 0) {
                toppanel.data("isRadEditorFullScreen", true);
                toppanel.removeClass("sticky");
            }
        }
        else {
            $(".vi-mask").show();
            $("nav#header_nav").show();
            //For Bug: 16401: RadEditor Toggle Full Screen acts up in toppanel.
            if (toppanel.length != 0) {
                toppanel.data("isRadEditorFullScreen", false);
            }
        }

        //bug13268:RAD editor window size changed after enable/disable Toggle Full Screen 
        //bug14662:RadEditor: Full screen mode blank in editor
        $(H).find("iframe").height("100%");
    });

    //setTimeout(function () {
    //    var toolWCAG = editor.getToolByName("WCAG");
    //    if (toolWCAG) {
    //        toolWCAG.addCssClass("a-wcag");
    //    }
    //}, 200);

    //Telerik.Web.UI.Editor.CommandList["WCAG"] = function (commandName, editor, args) {
    //    var editorElement = editor.get_element();
    //    //set the height size of the editor to decrease with 30px        
    //    editor.setSize(editorElement.clientWidth + 20, editorElement.clientHeight );
    //};


};
function resizeTelerik(container) {
    container = container || "body";
    var radeditor = $find($("div.RadEditor", container).attr("id") || "");
    if (radeditor)
        radeditor._sizer.setContentElementHeight();
}
function maskTextToStore(html) {
    var result = html;//$.decodeHTML(html);
    if (result == "<br />" || result == "<br/>") {
        result = "";
    }

    //image
    var imgRegex = /(src\s*=\s*["'])(?!(http[s]?:))[^'"]*?home\/showimage\s*(\?.*?["'])/gi;
    var imgReplacement = '$1home/showimage$3';
    result = result.replace(imgRegex, imgReplacement);

    //document
    var docRegex = /(href\s*=\s*["'])(?!(http[s]?:))[^'"]*?home\/showdocument\s*(\?.*?["'])/gi;
    var docReplacement = '$1home/showdocument$3';
    result = result.replace(docRegex, docReplacement);

    return result;
};

$(function () {
    if ($("div.RadEditor:not(:visible)").length > 0) {
        $("body").delegate(".t-item a.t-link", "click", function () {
            resizeTelerik($(this).attr("href"));
        });
        $("body .radeditor-visible-trigger").each(function () {
            if ($(this).is("input,select")) {
                $("body").delegate(this, "change", function () {
                    var container = $(this).attr("data-radeditor-trigger-container") || "body";
                    resizeTelerik(container);
                });
            }
        });
    }
})
/* Editor Event Handlers End ***************************************/

/* Place Holder for Cross Browsers Start */
$(function () {
    jQuery.support.placeholder = false;
    test = document.createElement('input');
    if ('placeholder' in test) jQuery.support.placeholder = true;

    if (!$.support.placeholder) {
        var active = null;
        if (window.top != window) {
            window.focus();
        }
        try {
            active = document.activeElement;
        } catch (error) { }
        $(':text,textarea').focus(function () {
            var placeholderAttr = $(this).attr('placeholder');
            if (typeof placeholderAttr != 'undefined' && placeholderAttr != '' && $(this).val() == placeholderAttr) {
                $(this).val('').removeClass('hasPlaceholder');
            }
        }).blur(function () {
            var placeholderAttr = $(this).attr('placeholder');
            if (typeof placeholderAttr != 'undefined' && placeholderAttr != '' && ($(this).val() == '' || $(this).val() == placeholderAttr)) {
                $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
            }
        });
        $(':text,textarea').each(function (i, n) {
            var placeholderAttr = $(this).attr('placeholder');
            if (typeof placeholderAttr != 'undefined' && placeholderAttr != '' && ($(this).val() == '' || $(this).val() == placeholderAttr)) {
                $(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
            }
        });
        if (active != null) {
            $(active).focus();
        }
        $('form').submit(function () {
            $(this).find('.hasPlaceholder').each(function () { $(this).val(''); });
        });
    }
});
/* Place Holder for Cross Browsers End */

/* Front End Form Submit in Widgets Start */
$(function () {
    $(document).delegate("form.front_end_form[need-ajax-submit='true']", "submit", function (event) {
        try {
            if (typeof $(this).validate == 'undefined' || $(this).valid()) {
                // when there is an Array, it won't post successfully because of the index.
                //            var formData = [];
                //            var postEles = $(this).attr("postEles") || "input[type='text'],input[type='hidden'],input[type='password'],input[type='checkbox'],textarea";
                //            $(this).find(postEles).each(function (i, n) {
                //                var obj = {};
                //                obj[$(n).attr("name")] = $(n).val();
                //                formData.push(obj);
                //            });

                var $this = $(this);
                var formData = $this.serializeArray();

                // merge JSON fields
                $this.find(".post-json-info[data-post-target]").each(function (i, n) {
                    var prefix = $(this).attr("data-post-target");
                    var jsonValue = $.parseJSON($(this).val());
                    for (var key in jsonValue) {
                        if (jsonValue[key] != null) {
                            formData.push({ name: prefix + "." + key, value: jsonValue[key] });
                        }
                    }
                });

                var containerSelector = $this.attr("formContainer") || ".front_end_form_container";
                var container = $this.closest(containerSelector);

                var needLoading = $this.attr("needLoading") || false;
                var notClearLoadingWhenSuccess = $this.attr("data-doNotClearLoading") || false;
                var loadingContainerAttr = $this.attr("loadingContainer") || "";
                var loadingContainer = container;
                if (loadingContainerAttr != "") {
                    if (loadingContainerAttr == "parent") {
                        loadingContainer = $this.parent();
                    }
                    else if (loadingContainerAttr == "self") {
                        loadingContainer = $this;
                    }
                    else {
                        loadingContainer = $this.closest(loadingContainerAttr);
                    }
                }
                if (needLoading) {
                    loadingContainer.loading(true, { mask: true, opacity: 0.8 });
                }
                $.frontendAjax(
                        {
                            url: $this.attr("action"),
                            type: $this.attr("method") || 'POST',
                            dataType: 'html',
                            //processData: false,
                            data: formData,
                            success: function (data, textStatus, jqXHR) {
                                if (data && $("<div>" + data + "</div>").find(".error_page.page_title").length > 0) {
                                    alert(Vision.Resources.UI_Common_FrontendFormPostFailed);
                                    if (needLoading) {
                                        loadingContainer.loading(null, null, true);
                                    }
                                    return;
                                }
                                var needWriteProxy = $this.attr("need-write-proxy") || false;
                                var htmlProxy = '';
                                if (needWriteProxy) {
                                    document.write = document.writeln = function (s) {
                                        htmlProxy += s;
                                    };
                                }

                                var dataReplaceSelf = $this.attr("data-replace-self") || "false";
                                if (dataReplaceSelf.toLowerCase() == "true") {
                                    container.replaceWith(data);
                                } else {
                                    container.html(data);
                                }

                                var writeProxy = $this.attr("write-proxy") || "";
                                if (writeProxy == "") {
                                    container.append(htmlProxy);
                                }
                                else {
                                    container.find(writeProxy).append(htmlProxy);
                                }

                                if (needLoading && !notClearLoadingWhenSuccess) {
                                    loadingContainer.loading(null, null, true);
                                }
                            },
                            error: function (data, textStatus, jqXHR) {
                                alert(Vision.Resources.UI_Common_FrontendFormPostFailed);
                                if (needLoading) {
                                    loadingContainer.loading(null, null, true);
                                }
                            }
                        });
            }
        } catch (err) {
            event.preventDefault();
            event.stopPropagation();
            alert("JS Error Occurred:" + err.message);
            window.location.href = window.location.href;
        }
        event.preventDefault();
        event.stopPropagation();
    });
});
/* Front End Form Submit in Widgets End */

/* Front End Widget Ajax Refresh Start */
$(function () {
    $(document).delegate("[widgetAjaxUrl][widgetAjaxTarget]", "click", function () {
        var $this = $(this);
        var ajaxUrl = $this.attr("widgetAjaxUrl");
        var ajaxTarget = $this.attr("widgetAjaxTarget");
        var ajaxDataStr = $this.attr("widgetAjaxData");
        var ajaxData = {};
        if (typeof ajaxDataStr != 'undefined') {
            ajaxData = $.parseJSON(ajaxDataStr);
        }
        var replaceAttr = $this.attr("widgetAjaxReplace");
        var isReplace = typeof replaceAttr != 'undefined' && parseInt(replaceAttr) == 1;

        var container = $this.closest(ajaxTarget);
        if ($.vision) {
            $.vision().ajax({
                url: ajaxUrl,
                dataType: "html",
                data: ajaxData,
                success: function (data) {
                    if (isReplace) {
                        container.replaceWith(data);
                    } else {
                        container.html(data);
                    }
                }
            });
        }
        else {
            $.frontendAjax({
                url: ajaxUrl,
                dataType: "html",
                data: ajaxData,
                success: function (data) {
                    if (isReplace) {
                        container.replaceWith(data);
                    } else {
                        container.html(data);
                    }
                }
            });
        }
        return false;
    });
});
/* Front End Widget Ajax Refresh End */

/* Front End Important Alert Start*/
$(function () {
    $('#alert_controls').click(function () {
        var alertClass = $(this).attr("class");
        var actionUrl = $(this).attr("data-action");
        if (alertClass == "hide") {
            $(document).find(".important_alert_wrapper").slideUp("150");
            $(this).attr("class", "show");
            //$.cookie('IMPTNOTICE', "HIDE", { expires: 1 });
            showTopTips(false, actionUrl);
        }
        else {
            $(document).find(".important_alert_wrapper").slideDown("150");
            $(this).attr("class", "hide");
            //$.cookie('IMPTNOTICE', "SHOW", { expires: 1 });
            showTopTips(true, actionUrl);
        }
    });

    function showTopTips(para, url) {
        $.frontendAjax(
          {
              url: url,
              type: 'POST',
              dataType: 'json',
              data: { 'showTopTips': para },
              success: function (data, textStatus, jqXHR) {
              }
          });
    }

    //var imptNotice = $.cookie('IMPTNOTICE');

    //if (!imptNotice) {
    //    $(".important_alert_wrapper").slideDown("150");
    //    $("#alert_controls").attr("class", "hide");

    //    $.cookie('IMPTNOTICE', "SHOW", { expires: 1 });
    //}
    //else {
    //    // check whether important notice was shown or hidden before
    //    if (imptNotice == "HIDE") {
    //        $(".important_alert_wrapper").css("display", "none");
    //        $("#alert_controls").attr("class", "show");
    //    }
    //    else {
    //        setTimeout(function () {
    //            $(".important_alert_wrapper").css("display", "block");
    //            $("#alert_controls").attr("class", "hide");
    //        }, 500);
    //    }
    //}
});
/* Front End Important Alert End*/

/*collapse fieldset*/
$(function () {
    $("body").delegate("fieldset.collapse > legend.collapse_handle, fieldset.collapse > legend a.collapse_handle", "click", function () {
        var legend = $(this).is("legend") ? $(this) : $(this).closest("legend");
        var content = legend.siblings();;
        if (content.is(":visible")) {
            content.hide();
            $(this).removeClass("expanded");
        } else {
            content.show();
            $(this).addClass("expanded");
        }
    });
});

/******************************Check Password Strength Start***********************************************/
//-----------------
// Description: Check the Password Strength
//-----------------
; (function ($) {
    var PasswordStrength = function () {
        //matching expressions
        var DIGIT_SYMBOLS_REG = /[0-9]/;
        var LOWERCASE_SYMBOLS_REG = /[a-z]/;
        var UPPERCASE_SYMBOLS_REG = /[A-Z]/;
        var SPECIAL_CHAR_SYMBOLS_REG = /[^0-9a-zA-Z]/;
        var MIN_LENGTH = 8;
        //scores
        var SCORE_BLANK = 0;
        var SCORE_VERY_WEAK = 1;
        var SCORE_WEAK = 2;
        var SCORE_MEDIUM = 3;
        var SCORE_STRONG = 4;
        var SCORE_VERY_STRONG = 5;

        this.username = null;
        this.password = null;
        this.score = 0;
        this.status = null;

        this.containInvalidMatches = function () {
            if (!this.exclude) {
                return false;
            }

            if (!this.exclude.test) {
                return false;
            }

            return this.exclude.test(this.password.toString());
        };

        this.test = function () {
            this.score = 0;
            if (this.containInvalidMatches()) {
                this.status = "invalid";
            } else {
                if (this.password.length >= MIN_LENGTH) {
                    this.score += this.scoreFor("numbers");
                    this.score += this.scoreFor("lowercase");
                    this.score += this.scoreFor("uppercase");
                    this.score += this.scoreFor("special");
                }

                if (this.score < SCORE_BLANK) {
                    this.score = SCORE_BLANK;
                }

                if (this.score > SCORE_VERY_STRONG) {
                    this.score = SCORE_VERY_STRONG;
                }

                if (this.score < SCORE_MEDIUM) {
                    this.status = "weak";
                }

                if (this.score >= SCORE_MEDIUM && this.score < SCORE_STRONG) {
                    this.status = "good";
                }

                if (this.score >= SCORE_STRONG) {
                    this.status = "strong";
                }
            }
            return this.score;
        };
        this.scoreFor = function (name) {
            score = 0;
            switch (name) {
                case "numbers":
                    if (this.password.match(DIGIT_SYMBOLS_REG)) {
                        score++;
                    }
                    break;
                case "lowercase":
                    if (this.password.match(LOWERCASE_SYMBOLS_REG)) {
                        score++;
                    }
                    break;
                case "uppercase":
                    if (this.password.match(UPPERCASE_SYMBOLS_REG)) {
                        score++;
                    }
                    break;
                case "special":
                    if (this.password.match(SPECIAL_CHAR_SYMBOLS_REG)) {
                        score++;
                    }
                    break;
                case "username":
                    if (this.password == this.username) {
                        score = 0;
                    } else if (this.password.indexOf(this.username) != -1) {
                        score = -1;
                    }
                    break;
            };
            return score;
        };
        this.isGood = function () {
            return this.status == "good";
        };
        this.isWeak = function () {
            return this.status == "weak";
        };
        this.isStrong = function () {
            return this.status == "strong";
        };
        this.isInvalid = function () {
            return this.status == "invalid";
        };
        this.isValid = function (level) {
            if (level == "strong") {
                return this.isStrong();
            } else if (level == "good") {
                return this.isStrong() || this.isGood();
            } else {
                return !this.containInvalidMatches();
            }
        };
        this.sequences = function (text) {
            var matches = 0;
            var sequenceSize = 0;
            var codes = [];
            var len = text.length;
            var previousCode, currentCode;

            for (var i = 0; i < len; i++) {
                currentCode = text.charCodeAt(i);
                previousCode = codes[codes.length - 1];
                codes.push(currentCode);

                if (previousCode) {
                    if (currentCode == previousCode + 1 || previousCode == currentCode) {
                        sequenceSize += 1;
                    } else {
                        sequenceSize = 0;
                    }
                }

                if (sequenceSize == 2) {
                    matches += 1;
                }
            }
            return matches;
        };

        this.repetitions = function (text, size) {
            var count = 0;
            var matches = {};
            var len = text.length;
            var substring;
            var occurrences;
            var tmpText;

            for (var i = 0; i < len; i++) {
                substring = text.substr(i, size);
                occurrences = 0;
                tmpText = text;

                if (matches[substring] || substring.length < size) {
                    continue;
                }

                matches[substring] = true;
                while ((i = tmpText.indexOf(substring)) != -1) {
                    occurrences += 1;
                    tmpText = tmpText.substr(i + 1);
                };

                if (occurrences > 1) {
                    count += 1;
                }
            }
            return count;
        };

        this.reversed = function (text) {
            var newText = "";
            var len = text.length;

            for (var i = len - 1; i >= 0; i--) {
                newText += text.charAt(i);
            }

            return newText;
        };
    }

    //-----------------
    // Description: Check the Passowrd static function
    //-----------------
    PasswordStrength.test = function (username, password) {
        strength = new PasswordStrength();
        strength.username = username;
        strength.password = password;
        strength.test();
        return strength;
    };

    //-----------------
    // Description: Check the Password Strength Function
    //-----------------
    function checkPasswordStrength(el, userName) {
        var u_name = userName.val();
        var p_word = $(el).val();

        var p_strength = PasswordStrength.test(u_name, p_word);
        var status = p_strength.status;
        var color;
        var width;
        var radius;
        status == "weak" ? color = "#D21C2B" : status == "good" ? color = "#2281CF" : color = "#6ec02a";
        status == "weak" ? width = "25px" : status == "good" ? width = "45px" : width = "70px";
        status == "weak" ? radius = "3px 0px 0px 3px" : status == "good" ? radius = "3px 0px 0px 3px" : radius = "3px 3px 3px 3px";

        var cause;
        if (status == 'weak') {
            cause = $.fn.PasswordStrength.defaults.WeakText;
        } else if (status == 'good') {
            cause = $.fn.PasswordStrength.defaults.GoodText;
        } else if (status == 'strong') {
            cause = $.fn.PasswordStrength.defaults.StrongText;
        }

        if (p_word.length >= 1) {
            $("#pstrength_text_parent").html("<span class='pstrength_text'>" + cause + "</span>");
            $(".pstrength_childbar").animate({ width: width }, "fast");
            $(".pstrength_childbar").css({ 'background-color': color, 'border-radius': radius });
            $(".pstrength_text").css("color", color);
            $(".pstrength_content").show();
        } else if (p_word.length == 0) {
            $(".pstrength_content").hide();
        } else {
            $("#pstrength_text_parent").html("<span class='pstrength_text'>" + cause + "</span>");
            $(".pstrength_childbar").animate({ width: width }, "fast");
            $(".pstrength_childbar").css({ 'background-color': color, 'border-radius': radius });
            $(".pstrength_text").css("color", color);
        }
    };

    $.fn.PasswordStrength = function (option) {
        var options = $.extend({}, $.fn.PasswordStrength.defaults, option);

        return this.each(function (i, n) {
            var element = $(n);

            var parentEl = element.parent();
            if (parentEl.find("#pwdstr").length == 0) {
                parentEl.append('<div id="pwdstr" class="pstrength_content">'
                        + '<span class="pwdbar"><span class="pstrength_childbar"></span></span>'
                        + '<span id="pstrength_text_parent" class="pwdbarspan"></span>'
                        + '</div>');
            }
            element.bind("keyup", function () {
                var userNameEl = $(options.UserName);
                checkPasswordStrength(this, userNameEl);
            });
        });
    };

    $.fn.PasswordStrength.defaults = {
        UserName: "UserName",
        WeakText: Vision.Resources.UI_Common_PasswordStrength_WeakText,
        GoodText: Vision.Resources.UI_Common_PasswordStrength_GoodText,
        StrongText: Vision.Resources.UI_Common_PasswordStrength_StrongText
    };
})(jQuery);
/******************************Check Password Strength End***********************************************/

/***************Session Timeout at Front End - Start***********************/
; (function ($) {
    function FrontEndSessionManager(options) {
        this.opts = $.extend({}, FrontEndSessionManager.defaults, options);
        this._window = window.top;
        this._window._timeoutIDForSessionExpirationAtFrontEnd = null;
        this.sessionExtendPath = this.opts.virtualApplicationPath + this.opts.extendSessionTimeoutPath;
    }
    FrontEndSessionManager.defaults = {
        virtualApplicationPath: "/",
        enableSessionTimeout: false,//Set true when member or website user log in.
        useSessionTimeout: true,
        sessionTimeoutInMinutes: 20,
        timeToAlertBeforeSessionTimeoutInMinutes: 5,
        extendSessionTimeoutPath: "Home/FrontEndExtendSessionTimeout",
        sessionExtensionMode: "server" //client, server.
    };
    FrontEndSessionManager.prototype = {
        ajax: function (url, options) {
            if (this.opts.enableSessionTimeout === true) {
                //useSessionTimeout
                var useTimeout = this.opts.useSessionTimeout;
                if (typeof url === "object" && url.useSessionTimeout) {
                    useTimeout = url.useSessionTimeout;
                } else if (options && options.useSessionTimeout) {
                    useTimeout = options.useSessionTimeout;
                }

                if (useTimeout === true) {
                    //mode
                    var mode = this.opts.sessionExtensionMode;
                    if (typeof url === "object" && url.sessionExtensionMode) {
                        mode = url.sessionExtensionMode;
                    } else if (options && options.sessionExtensionMode) {
                        mode = options.sessionExtensionMode;
                    }

                    //Ajax
                    if (mode === "client") {
                        this.extendSessionTimeout(function () {
                            $.ajax(url, options);
                        });
                    } else {
                        if (typeof url === "object") {
                            url.success = this._wrapSessionExtensionSuccess(url.success);
                            url.headers = { ExtendSession: true };
                        } else {
                            options = options || {};
                            options.success = this._wrapSessionExtensionSuccess(options.success);
                            options.headers = { ExtendSession: true };
                        }
                        $.ajax(url, options);
                    }
                } else {
                    $.ajax(url, options);
                }
            } else {
                $.ajax(url, options);
            }
        },
        _wrapSessionExtensionSuccess: function (originalSuccess) {
            if (this.opts.enableSessionTimeout === true) {
                var manager = this;
                return function (data, textStatus, jqXHR) {
                    var sessionInfo = $.parseJSON(jqXHR.getResponseHeader("SessionInfo") || "");
                    if (sessionInfo && sessionInfo.IsAuth) {
                        manager.setTimerForSessionExpiration(sessionInfo.Timeout, sessionInfo.TimeToAlert);
                        if ($.isFunction(originalSuccess)) {
                            originalSuccess(data, textStatus, jqXHR);
                        }
                    } else {
                        manager._window.alert(Vision.Resources.FrontEndSessionTimeout_SessionExpired);
                        manager._window.location.href = manager._window.location.href;
                    }
                };
            } else {
                return originalSuccess;
            }
        },
        extendSessionTimeout: function (callBackOnSuccess) {
            if (this.opts.enableSessionTimeout === true) {
                var manager = this;
                $.ajax({
                    type: 'POST',
                    async: true,
                    url: manager.sessionExtendPath,
                    success: function (data, textStatus, jqXHR) {
                        try {
                            //if user is offline, returned data will be logon view.
                            if (typeof (data.SessionTimeoutInMinutes) == "undefined" && typeof (data.TimeToAlertBeforeSessionTimeoutInMinutes) == "undefined") {
                                manager._window.alert(Vision.Resources.FrontEndSessionTimeout_SessionExpired);
                                manager._window.location.href = manager._window.location.href;
                            } else {
                                manager.setTimerForSessionExpiration(data.SessionTimeoutInMinutes, data.TimeToAlertBeforeSessionTimeoutInMinutes);
                                if ($.isFunction(callBackOnSuccess)) {
                                    callBackOnSuccess();
                                }
                            }
                        } catch (err) {
                            //alert('error message: ' + err.Message);
                        }
                    }
                });
            } else {
                if ($.isFunction(callBackOnSuccess)) {
                    callBackOnSuccess();
                }
            }
        },
        //this method will cause blockUI
        extendSessionTimeoutSync: function () {
            if (this.opts.enableSessionTimeout !== true) {
                return;
            }
            var manager = this;
            $.ajax({
                type: 'POST',
                async: false,
                url: manager.sessionExtendPath,
                success: function (data, textStatus, jqXHR) {
                    try {
                        //if user is offline, returned data will be logon view.
                        if (typeof (data.SessionTimeoutInMinutes) == "undefined" && typeof (data.TimeToAlertBeforeSessionTimeoutInMinutes) == "undefined") {
                            manager._window.alert(Vision.Resources.FrontEndSessionTimeout_SessionExpired);
                            manager._window.location.href = manager._window.location.href;
                        } else {
                            manager.setTimerForSessionExpiration(data.SessionTimeoutInMinutes, data.TimeToAlertBeforeSessionTimeoutInMinutes);
                        }
                    } catch (err) {
                        //alert('error message: ' + err.Message);
                    }
                }
            });
        },
        setTimerForSessionExpiration: function (sessionTimeoutInMinutes, timeToAlertBeforeSessionTimeoutInMinutes) {
            if (this.opts.enableSessionTimeout !== true) {
                return;
            }
            sessionTimeoutInMinutes = sessionTimeoutInMinutes || this.opts.sessionTimeoutInMinutes;
            timeToAlertBeforeSessionTimeoutInMinutes = timeToAlertBeforeSessionTimeoutInMinutes || this.opts.timeToAlertBeforeSessionTimeoutInMinutes;
            var timeSpan = window.parseInt(sessionTimeoutInMinutes) * 60 * 1000 - window.parseInt(timeToAlertBeforeSessionTimeoutInMinutes) * 60 * 1000;
            if (this._window._timeoutIDForSessionExpirationAtFrontEnd != null) {
                //to be sure only one timer in page
                this._window.clearTimeout(this._window._timeoutIDForSessionExpirationAtFrontEnd);
                this._window._timeoutIDForSessionExpirationAtFrontEnd = null;
            }
            var manager = this;
            this._window._timeoutIDForSessionExpirationAtFrontEnd = this._window.setTimeout(function () { manager.promptSessionTimeout(sessionTimeoutInMinutes, timeToAlertBeforeSessionTimeoutInMinutes); }, timeSpan);
        },
        promptSessionTimeout: function (sessionTimeoutInMinutes, timeToAlertBeforeSessionTimeoutInMinutes) {
            if (this.opts.enableSessionTimeout !== true) {
                return;
            }
            this._window.focus();
            var confirmMessage = $.format(Vision.Resources.FrontEndSessionTimeout_SessionTip, timeToAlertBeforeSessionTimeoutInMinutes, sessionTimeoutInMinutes);
            var result = this._window.confirm(confirmMessage);
            if (result) {
                this.extendSessionTimeout(function () { });
            }
        }
    };
    $.extend($, {
        frontendSessionManager: function (options) {
            var manager = $("body").data("FrontEndSessionManager");
            if (manager) {
                manager.opts = $.extend(manager.opts, options);
                $("body").data("FrontEndSessionManager", manager);
                return manager;
            } else {
                manager = new FrontEndSessionManager(options);
                $("body").data("FrontEndSessionManager", manager);
                return manager;
            }
        }
    });
})(jQuery);
/***************Session Timeout at Front End - End***********************/

; (function ($) {
    /***************Front End Ajax - Start***************/
    $.extend($, {
        frontendAjax: function (url, options) {
            $.frontendSessionManager().ajax(url, options);
        }
    });
    /***************Front End Ajax - End***************/
    $.prototype.extend($.prototype, {
        loadAsyncContainer: function (options) {
            $(this).each(function (i, n) {
                var widget_container = $(n);
                var height = widget_container.height();
                var needLoading = false;// height > 0;
                var url = widget_container.attr("data-async-url");
                if (url) {
                    if (needLoading) {
                        $(widget_container).loading(true, null);
                    }
                    $.frontendAjax(url, {
                        success: function (html) {
                            widget_container.replaceWith(html);
                            if (needLoading) {
                                $(widget_container).loading(null, { hideCurrent: true }, true);
                            }
                        },
                        error: function () {
                            if (needLoading) {
                                $(widget_container).loading(null, { hideCurrent: true }, true);
                            }
                        }
                    });
                }
            });
        }
    });

    $.scriptsStack.add(function () {
        /***************Front End Async Widget Refresh - Start***************/
        // For Global async load widget
        $(".async_widget_container:not(.custominvoke)").loadAsyncContainer();
        /***************Front End Async Widget Refresh - End***************/
    });
})(jQuery);


$(function () {

    /***************Front End Hide Text Area Widget in Detail View - Start***************/
    if ($(".page.edit").length <= 0) {
        $(".column").each(function () {
            if ($(this).find(".need_hide_detail_widget").length > 0) {
                $(this).find(".normal_content_area").each(function (index, item) {
                    /* Do not hide content area in main nav */
                    if ($(item).parents(".mainnav").length == 0) {
                        $(item).hide(); // For Section 508
                        $(item).remove(); // For Normal UI
                    }
                });
            }
        });
    }
    /***************Front End Hide Text Area Widget in Detail View - End***************/

    /* Widget Setting, Hide/Show 'HideContentAreaWidgetInDetailView' setting */
    $("body").delegate(".ele_load_detailview_incurrentpage input:radio", "click", function (e) {
        var radioValue = $(this).val().toLowerCase();
        if (radioValue == "true") {
            // attr 'data-info' only exist in widgets that have List/Detail view setting
            if (typeof ($(".ele_hide_contentareawidget_indetailview").attr("data-info")) == "undefined"
                || $(".ele_hide_contentareawidget_indetailview").attr("data-info") == "is_list_view")
                $(".ele_hide_contentareawidget_indetailview").show();
        }
        else {
            $(".ele_hide_contentareawidget_indetailview").hide();
            $("input[name='Setting.HideContentAreaWidgetInDetailView'][value='False']").prop("checked", true);
            $(".ele_hide_contentareawidget_indetailview").find("input:checkbox:checked").trigger("click");
        }
    });

    /* for Include/Exclude Category Constraint Type 2013/05/28 */

    $("body").delegate("ol.formlist li.is_include_category_li :radio", "change", function () {
        var isIncludeCategory = $(this).val() == $('#UsedForCategoryConstraint').val();
        $.widgetSettingDisplayCategory(isIncludeCategory);
    });

    $("body").delegate("tr.is_include_category_tr td.setting_td .is_include_category_li > :radio", "change", function () {
        var isIncludeCategory = $(this).val() == $('#UsedForCategoryConstraint').val();
        $.widgetDevSettingDisplayCategory(isIncludeCategory);
    });

    $("body").delegate(".include_category_tr .display_td :checkbox", "click", function (event, isContinue) {
        if (isContinue == "false")
            return;
        var ckBox = $(this);
        if (ckBox.prop("checked")) {
            if ($(".exclude_category_tr .display_td :checkbox").siblings(".display_field_value_hidden").length < 1) {
                $(".exclude_category_tr .display_td :checkbox").trigger("click", ["false"]);
            }
        }
        else {
            if ($(".exclude_category_tr .display_td :checkbox").siblings(".display_field_value_hidden").length >= 1) {
                $(".exclude_category_tr .display_td :checkbox").trigger("click", ["false"]);
            }
        }
    });
    $("body").delegate(".exclude_category_tr .display_td :checkbox", "click", function (event, isContinue) {
        if (isContinue == "false")
            return;
        var ckBox = $(this);
        if (ckBox.prop("checked")) {
            if ($(".include_category_tr .display_td :checkbox").siblings(".display_field_value_hidden").length < 1) {
                $(".include_category_tr .display_td :checkbox").trigger("click", ["false"]);
            }
        }
        else {
            if ($(".include_category_tr .display_td :checkbox").siblings(".display_field_value_hidden").length >= 1) {
                $(".include_category_tr .display_td :checkbox").trigger("click", ["false"]);
            }
        }
    });
    $("body").delegate(".vi-expandable-tree li > a:not(.item)", "click", function () {
        var li = $(this).closest("li");
        if (li.hasClass("expanded")) {
            li.removeClass("expanded");
        } else {
            li.addClass("expanded");
        }
    });
});
; (function ($) {
    $.extend($, {
        widgetSettingDisplayCategory: function (isIncludeCategory) {
            var categoryHtmlData = $('#UsedForCategoryConstraint').data("settingCategoryHtmlData");

            if (isIncludeCategory.toString().toLowerCase() == "true") {
                if ($("ol.formlist li.include_category_li").length <= 0) {
                    $("ol.formlist li.is_include_category_li").after(categoryHtmlData);
                }
                if ($("ol.formlist li.exclude_category_li").length > 0) {
                    $('#UsedForCategoryConstraint').data("settingCategoryHtmlData", $("ol.formlist li.exclude_category_li").detach());
                }
                $("ol.formlist li.include_category_li").show();
            }
            else {
                if ($("ol.formlist li.exclude_category_li").length <= 0) {
                    $("ol.formlist li.is_include_category_li").after(categoryHtmlData);
                }
                if ($("ol.formlist li.include_category_li").length > 0) {
                    $('#UsedForCategoryConstraint').data("settingCategoryHtmlData", $("ol.formlist li.include_category_li").detach());
                }
                $("ol.formlist li.exclude_category_li").show();
            }
        },
        widgetDevSettingDisplayCategory: function (isIncludeCategory) {
            var categoryHtmlData = $('#UsedForCategoryConstraint').data("devSettingCategoryHtmlData");

            if (isIncludeCategory.toString().toLowerCase() == "true") {
                if ($("div.widget_dev_setting table td.include_category_td").length <= 0) {
                    $("div.widget_dev_setting table tr.include_category_tr").append(categoryHtmlData);
                }
                if ($("div.widget_dev_setting table td.exclude_category_td").length > 0) {
                    $('#UsedForCategoryConstraint').data("devSettingCategoryHtmlData", $("div.widget_dev_setting table td.exclude_category_td").detach());
                }

                $("div.widget_dev_setting table tr.include_category_tr").show();
                $("div.widget_dev_setting table tr.exclude_category_tr").hide();
            }
            else {
                if ($("div.widget_dev_setting table td.exclude_category_td").length <= 0) {
                    $("div.widget_dev_setting table tr.exclude_category_tr").append(categoryHtmlData);
                }
                if ($("div.widget_dev_setting table td.include_category_td").length > 0) {
                    $('#UsedForCategoryConstraint').data("devSettingCategoryHtmlData", $("div.widget_dev_setting table td.include_category_td").detach());
                }

                $("div.widget_dev_setting table tr.exclude_category_tr").show();
                $("div.widget_dev_setting table tr.include_category_tr").hide();
            }
        }
    });
})(jQuery);
/* end of 2013/05/28 */

/*artTemplate - Template Engine*/
var template = function (id, content) {
    return template[
        typeof content === 'object' ? 'render' : 'compile'
    ].apply(template, arguments);
};

(function (exports, global) {
    "use strict";
    exports.version = '1.4.0';
    exports.openTag = '<%';
    exports.closeTag = '%>';
    exports.parser = null;

    exports.render = function (id, data) {
        var cache = _getCache(id);
        if (cache === undefined) {
            return _debug({
                id: id,
                name: 'Render Error',
                message: 'Not Cache'
            });
        }
        return cache(data);
    };

    exports.compile = function (id, source) {
        var debug = arguments[2];
        if (typeof source !== 'string') {
            debug = source;
            source = id;
            id = null;
        }

        try {
            var Render = _compile(source, debug);
        } catch (e) {
            e.id = id || source;
            e.name = 'Syntax Error';
            return _debug(e);
        }

        function render(data) {
            try {
                return new Render(data).template;
            } catch (e) {
                if (!debug) {
                    return exports.compile(id, source, true)(data);
                }
                e.id = id || source;
                e.name = 'Render Error';
                e.source = source;
                return _debug(e);
            };
        };

        render.prototype = Render.prototype;
        render.toString = function () {
            return Render.toString();
        };

        if (id) {
            _cache[id] = render;
        }

        return render;
    };

    exports.helper = function (name, helper) {
        _helpers[name] = helper;
    };

    var _cache = {};
    var _isNewEngine = ''.trim;
    var _isServer = _isNewEngine && !global.document;
    var _keyWordsMap = {};

    var _forEach = function () {
        var forEach = Array.prototype.forEach || function (block, thisObject) {
            var len = this.length >>> 0;
            for (var i = 0; i < len; i++) {
                if (i in this) {
                    block.call(thisObject, this[i], i, this);
                }
            }
        };

        return function (array, callback) {
            forEach.call(array, callback);
        };
    }();

    var _create = Object.create || function (object) {
        function Fn() { };
        Fn.prototype = object;
        return new Fn;
    };

    var _helpers = exports.prototype = {
        $forEach: _forEach,
        $render: exports.render,
        $getValue: function (value) {
            return value === undefined ? '' : value;
        }
    };

    _forEach((
        'break,case,catch,continue,debugger,default,delete,do,else,false,finally,for,function,if'
        + ',in,instanceof,new,null,return,switch,this,throw,true,try,typeof,var,void,while,with'

        + ',abstract,boolean,byte,char,class,const,double,enum,export,extends,final,float,goto'
        + ',implements,import,int,interface,long,native,package,private,protected,public,short'
        + ',static,super,synchronized,throws,transient,volatile'

        // ECMA 5 - use strict
        + ',arguments,let,yield'

    ).split(','), function (key) {
        _keyWordsMap[key] = true;
    });

    var _compile = function (source, debug) {
        var openTag = exports.openTag;
        var closeTag = exports.closeTag;
        var parser = exports.parser;

        var code = source;
        var tempCode = '';
        var line = 1;
        var uniq = { $out: true, $line: true };

        var variables = "var $helpers=this,"
        + (debug ? "$line=0," : "");

        var replaces = _isNewEngine
        ? ["$out='';", "$out+=", ";", "$out"]
        : ["$out=[];", "$out.push(", ");", "$out.join('')"];

        var concat = _isNewEngine
            ? "if(content!==undefined){$out+=content;return content}"
            : "$out.push(content);";

        var print = "function(content){" + concat + "}";

        var include = "function(id,data){"
        + "if(data===undefined){data=$data}"
        + "var content=$helpers.$render(id,data);"
        + concat
        + "}";

        _forEach(code.split(openTag), function (code, i) {
            code = code.split(closeTag);
            var $0 = code[0];
            var $1 = code[1];

            // code: [html]
            if (code.length === 1) {
                tempCode += html($0);
                // code: [logic, html]
            } else {
                tempCode += logic($0);
                if ($1) {
                    tempCode += html($1);
                }
            }
        });
        code = tempCode;

        if (debug) {
            code = 'try{' + code + '}catch(e){'
            + 'e.line=$line;'
            + 'throw e'
            + '}';
        }

        code = variables + replaces[0] + code + 'this.template=' + replaces[3];

        try {
            var render = new Function('$data', code);
            var proto = render.prototype = _create(_helpers);
            proto.toString = function () {
                return this.template;
            };
            return render;
        } catch (e) {
            e.temp = 'function anonymous($data) {' + code + '}';
            throw e;
        };

        function html(code) {
            line += code.split(/\n/).length - 1;

            code = code
            .replace(/('|"|\\)/g, '\\$1')
            .replace(/\r/g, '\\r')
            .replace(/\n/g, '\\n');

            code = replaces[1] + "'" + code + "'" + replaces[2];

            return code + '\n';
        };

        function logic(code) {
            var thisLine = line;

            if (parser) {
                code = parser(code);

            } else if (debug) {
                code = code.replace(/\n/g, function () {
                    line++;
                    return '$line=' + line + ';';
                });
            }

            if (code.indexOf('=') === 0) {
                code = code.substring(1).replace(/[\s;]*$/, '');
                if (_isNewEngine) {
                    code = '$getValue(' + code + ')';
                }
                code = replaces[1] + code + replaces[2];
            }

            if (debug) {
                code = '$line=' + thisLine + ';' + code;
            }
            getKey(code);
            return code + '\n';
        };

        function getKey(code) {
            code = code.replace(/\/\*.*?\*\/|'[^']*'|"[^"]*"|\.[\$\w]+/g, '');
            _forEach(code.split(/[^\$\w\d]+/), function (name) {
                if (/^this$/.test(name)) {
                    throw {
                        message: 'Prohibit the use of the "' + name + '"'
                    };
                }
                if (!name || _keyWordsMap.hasOwnProperty(name) || /^\d/.test(name)) {
                    return;
                }
                if (!uniq.hasOwnProperty(name)) {
                    setValue(name);
                    uniq[name] = true;
                }
            });

        };

        function setValue(name) {
            var value;

            if (name === 'print') {
                value = print;
            } else {
                if (name === 'include') {
                    value = include;
                } else {
                    if (_helpers.hasOwnProperty(name)) {
                        value = '$helpers.' + name;
                    } else {
                        value = '$data.' + name;
                    }
                }
            }
            variables += name + '=' + value + ',';
        };
    };

    var _getCache = function (id) {
        var cache = _cache[id];
        if (cache === undefined && !_isServer) {
            var elem = document.getElementById(id);

            if (elem) {
                exports.compile(id, elem.value || elem.innerHTML);
            }
            return _cache[id];

        } else if (_cache.hasOwnProperty(id)) {
            return cache;
        }
    };

    var _debug = function (e) {
        var content = '[template]:\n'
            + e.id
            + '\n\n[name]:\n'
            + e.name;

        if (e.message) {
            content += '\n\n[message]:\n'
            + e.message;
        }

        if (e.line) {
            content += '\n\n[line]:\n'
            + e.line;
            content += '\n\n[source]:\n'
            + e.source.split(/\n/)[e.line - 1].replace(/^[\s\t]+/, '');
        }

        if (e.temp) {
            content += '\n\n[temp]:\n'
            + e.temp;
        }

        if (global.console) {
            console.error(content);
        }

        function error() {
            return error + '';
        };

        error.toString = function () {
            return '{Template Error}';
        };
        return error;
    };
})(template, this);

if (typeof module !== 'undefined' && module.exports) {
    module.exports = template;
}

; (function ($) {
    var ViMutipleRow = function (element, options) {
        var defaults = {
            addTrigger: ".addlink",
            removeTrigger: ".deletelink:not(.disabled)",
            leastOne: true,
            itemSelector: null,
            allowMaxNumber: 100,
            maxRowIndex: 0,
            init: function (inst) { },
            generateJson: function () { },
            rowTemplate: function (row, rowIndex) { },
            insertRowCall: function (row, rowNum, rowIndex) { },
            beforeRemoveRowCall: function (row, rowNum, rowIndex) { },
            removeRowCall: function (rowNum, rowIndex) { }
        };

        var setting = this.setting = $.extend({}, defaults, options);

        this.vars = {
            maxRowIndex: 0,
            operateType: {
                insert: "insert",
                remove: "remove"
            }
        };
        this.mutipleRow = $(element);
        this.initialize();
    };

    ViMutipleRow.prototype = {
        initialize: function () {
            var _this = this,
                setting = _this.setting,
                vars = _this.vars,
                addTrigger = setting.addTrigger,
                removeTrigger = setting.removeTrigger,
                mutipleRow = _this.mutipleRow;

            _this.mutipleRow.addClass("mutiple_row_container");
            _this.items = _this.getItems();

            vars.maxRowIndex = Math.max(_this.items.length, setting.maxRowIndex);

            mutipleRow.delegate(addTrigger, "click", function () {
                var allRows = _this.getItems();
                var row = $(this).closest("tr");
                var rowNum = _this.getRowNum(row);
                var rowIndex = vars.maxRowIndex = Math.max(vars.maxRowIndex, allRows.length);
                _this.insertRow(row, rowNum, rowIndex);

                return false;
            });

            mutipleRow.delegate(removeTrigger, "click", function () {
                var allRows = _this.getItems();
                var row = $(this).closest("tr");
                var rowNum = _this.getRowNum(row);
                var rowIndex = vars.maxRowIndex = Math.max(vars.maxRowIndex, allRows.length);
                _this.removeRow(row, rowNum, rowIndex);

                return false;
            });

            _this.checkRow();

            if (setting.init && $.isFunction(setting.init)) {
                setting.init.call(_this);
            }
        },
        insertRow: function (row, rowNum, rowIndex) {
            var _this = this,
                setting = _this.setting,
                vars = _this.vars,
                tbody = row ? row.closest("tbody") : _this.mutipleRow.find("tbody");

            var newRowHtml = setting.rowTemplate(row, rowIndex);
            var rowCount = tbody.children("tr").length;

            if (rowCount >= setting.allowMaxNumber) {
                return false;
            }

            row ? row.after(newRowHtml) : tbody.append(newRowHtml);
            vars.maxRowIndex++;
            _this.checkRow();

            var newRow = row ? row.next() : tbody.children().first();
            _this.ensureItems();

            if (setting.insertRowCall && $.isFunction(setting.insertRowCall)) {
                setting.insertRowCall.call(_this, newRow, rowNum, rowIndex);
            }
        },
        removeRow: function (row, rowNum, rowIndex) {
            var _this = this,
                setting = _this.setting,
                vars = _this.vars;

            if (setting.beforeRemoveRowCall && $.isFunction(setting.beforeRemoveRowCall)) {
                setting.beforeRemoveRowCall.call(_this, row, rowNum, rowIndex);
            }

            row.remove();
            _this.ensureItems();

            if (setting.removeRowCall && $.isFunction(setting.removeRowCall)) {
                setting.removeRowCall.call(_this, rowNum, rowIndex);
            }
            _this.checkRow();
        },
        ensureItems: function () {
            this.getItems();
        },
        getItems: function () {
            var _this = this,
                setting = _this.setting,
                mutipleRow = _this.mutipleRow;

            if (setting.itemSelector) {
                _this.items = $(setting.itemSelector);
            } else {
                _this.items = mutipleRow.find("tbody > tr");
            }

            return _this.items;
        },
        checkRow: function () {
            var _this = this,
                setting = _this.setting,
                vars = _this.vars,
                mutipleRow = _this.mutipleRow,
                addTrigger = setting.addTrigger,
                tbody = mutipleRow.find("tbody");

            if (setting.leastOne) {
                var allRows = _this.getItems().length,
                    removeTriggerEls = tbody.find(setting.removeTrigger);

                if (allRows === 1) {
                    removeTriggerEls.hide();
                } else if (allRows === 0) {
                    _this.insertRow(null, 0, 0);
                    var firstRow = tbody.children().first();
                    firstRow.find(setting.removeTrigger).hide();
                } else {
                    removeTriggerEls.show();
                }
            }

            var rowCount = tbody.children("tr").length;
            if (rowCount >= setting.allowMaxNumber) {
                tbody.find(addTrigger).addClass("disabled");
            } else {
                tbody.find(addTrigger).removeClass("disabled");
            }
        },
        generateJson: function () {
            var _this = this,
                setting = _this.setting;

            setting.generateJson && setting.generateJson.call(_this);
        },
        getRowNum: function (row) {
            var _this = this,
                mutipleRow = _this.mutipleRow;

            if (row.is("tr")) {
                return _this.items.length + 1;
            } else {
                return 0;
            }
        }
    };

    $.fn.viMutipleRow = function (options) {
        return this.each(function (key, value) {
            var element = $(this);
            // Return early if this element already has a plugin instance
            if (element.data('viMutipleRow')) return element.data('viMutipleRow');
            // Pass options to plugin constructor
            var viMutipleRow = new ViMutipleRow(this, options);
            // Store plugin object in this element's data
            element.data('viMutipleRow', viMutipleRow);
        });
    };
})(jQuery);

; (function ($, window) {
    var ViMultipleItem = function (element, options) {
        var defaults = {
            leastOne: true,
            items: "tr",
            itemsContainer: "table",
            allowMaxCount: 20,
            addTrigger: ".addlink",
            removeTrigger: ".deletelink:not(.disabled)",
            init: function (inst) { },
            itemTemplate: function (item, itemIndex) { },
            insertItemCall: function (item, itemIndex) { },
            beforeRemoveItemCall: function (item, itemIndex) { },
            removeItemCall: function (itemIndex) { }
        };

        this.vars = {
            maxIndex: 0
        };

        this.settings = $.extend({}, defaults, options);
        this.viMultipleItem = element;
        this.initialize();
    };

    ViMultipleItem.prototype = {
        initialize: function () {
            var that = this,
				settings = that.settings,
                vars = that.vars,
                addTrigger = settings.addTrigger,
                removeTrigger = settings.removeTrigger,
				viMultipleItem = that.viMultipleItem;

            viMultipleItem.addClass("multiple_item_container");
            that.items = that._getItems();
            that.itemsContainer = $(settings.itemsContainer);


            vars.maxIndex = that.items.length;

            viMultipleItem.delegate(addTrigger, "click", function () {
                var allItems = that._getItems();

                var item = $(this).closest(settings.items);
                var itemIndex = vars.maxIndex;

                that.insertItem(item, itemIndex);

                return false;
            });

            viMultipleItem.delegate(removeTrigger, "click", function () {
                var allItems = that._getItems();

                var item = $(this).closest(settings.items);
                var itemIndex = that.getItemIndex(item);

                that.removeItem(item, itemIndex);

                return false;
            });

            that._checkItem();

            settings.init && settings.init.call(that);
        },

        _getItems: function () {
            var that = this,
				settings = that.settings;

            return $(settings.itemsContainer).children(settings.items);
        },

        _checkItem: function () {
            var that = this,
				settings = that.settings;

            if (settings.leastOne) {
                var items = that.items,
                    itemsCount = items.length,
                    itemsContainer = that.itemsContainer,
                    removeTriggerEls = itemsContainer.find(settings.removeTrigger);

                if (itemsCount === 1) {
                    removeTriggerEls.hide();
                } else if (itemsCount === 0) {
                    that.insertItem(null, 0);

                    items = that.items;
                    var firstItem = items.first();
                    firstItem.find(settings.removeTrigger).hide();
                } else {
                    removeTriggerEls.show();
                }
            }
        },

        getItemIndex: function (item) {
            var that = this,
                settings = that.settings;

            if (item.is(settings.items)) {
                return that.items.index(item);
            } else {
                return 0;
            }
        },

        insertItem: function (item, itemIndex) {
            var that = this,
				settings = that.settings,
                vars = that.vars;

            if (that.items.length > settings.allowMaxCount) {
                return;
            }

            var itemHtml = settings.itemTemplate(item, itemIndex);
            var newItem = null;

            if (item) {
                item.after(itemHtml);
                newItem = item.next();
            } else {
                that.itemsContainer.append(itemHtml);
                newItem = that._getItems().last();
            }

            vars.maxIndex++;
            that.items = that._getItems();
            that._checkItem();

            settings.insertItemCall && settings.insertItemCall.call(that, newItem, itemIndex);
        },

        removeItem: function (item, itemIndex) {
            var that = this,
				settings = that.settings;

            settings.beforeRemoveItemCall && settings.beforeRemoveItemCall.call(that, item, itemIndex);

            if (item) {
                item.remove();
            }

            that.items = that._getItems();
            that._checkItem();

            settings.removeItemCall && settings.removeItemCall.call(that, itemIndex);
        }
    };

    $.fn.viMultipleItem = function (options) {
        return this.each(function (i, n) {
            var element = $(n);
            if (element.data("viMultipleItem")) {
                return element.data("viMultipleItem");
            }
            var viMultipleItem = new ViMultipleItem(element, options);
            element.data("viMultipleItem", viMultipleItem);
        });
    };
})(jQuery, window);

; (function ($) {
    $.extend($, {
        /**
        * Converts the given decimal into list formatting.
        * @param decimal: 
        */
        ListFormattingDecimalFormat: function (decimal, parentheses) {
            var str = "";
            if ($.type(decimal) === "number") {
                str += decimal;
                parentheses ? str += ")" : str += ".";
            }
            return str;
        },
        /**
        * Converts the given decimal into letters.
        * @param decimal: 
        */
        ListFormattingDecimalToLetter: function (decimal, isSupper, parentheses) {
            var str = "";
            if ($.type(decimal) === "number") {
                var aCharAscii = isSupper ? 65 : 97;

                var loopTimes = Math.floor(decimal / 26) + 1;
                var charCode = (--decimal) % 26;

                for (var i = 0; i < loopTimes; i++) {
                    str += String.fromCharCode(charCode + aCharAscii);
                }

                parentheses ? str += ")" : str += ".";
            }

            return str;
        },
        /**
         * Converts the given decimal into roman letters.
         * @param decimal: decimal positive decimal between 0 and 4000
         * @return: string with roman letters
         * false, if param decimal is not valid
         */
        ListFormattingDecimalToRoman: function (decimal, isSupper, parentheses) {
            var newRoman = "";
            var curNumber = parseInt(decimal);

            var romanValues = isSupper ? [
                [1, 'I'],
                [5, 'V'],
                [10, 'X'],
                [50, 'L'],
                [100, 'C'],
                [500, 'D'],
                [1000, 'M']
            ] : [
                [1, 'i'],
                [5, 'v'],
                [10, 'x'],
                [50, 'l'],
                [100, 'c'],
                [500, 'd'],
                [1000, 'm']
            ];

            function mainIndex(value) {
                return (Math.floor(value / 2) * 2);
            }

            if (!isNaN(curNumber) && curNumber > 0 && curNumber < 4000) {
                var curIndex = romanValues.length - 1;

                while (curIndex >= 0) {
                    if (curNumber >= romanValues[curIndex][0]) {
                        var mainCount = Math.floor(curNumber / romanValues[mainIndex(curIndex)][0]);
                        var calcCount = mainCount % 5;

                        if (calcCount == 4) {
                            newRoman += romanValues[mainIndex(curIndex)][1] + romanValues[curIndex + 1][1];
                            curNumber -= mainCount * romanValues[mainIndex(curIndex)][0];
                        } else {
                            newRoman += romanValues[curIndex][1];
                            curNumber -= romanValues[curIndex][0];

                            while (--calcCount > 0) {
                                newRoman += romanValues[mainIndex(curIndex)][1];
                                curNumber -= romanValues[mainIndex(curIndex)][0];
                            }
                        }
                    }
                    curIndex--;
                }
                parentheses ? newRoman += ")" : newRoman += ".";
            } else {
                newRoman = false;
            }

            return newRoman;
        },
        formatFacilityHour: function (startHour, endHour, timeFormat) {
            if (startHour > endHour) {
                return "";
            } else {
                return $.datepicker.formatTime(timeFormat, { hour: parseInt(startHour) }, {}) + " - " + $.datepicker.formatTime(timeFormat, { hour: parseInt(endHour), minute: 59 }, {});
            }
        },
        formattedFacilityReservedHours: function (hours, timeFormat) {
            hours = hours.sortNumber();
            var result = "";
            var groupedHours = [];
            var currentGroupedIndex = 0;
            $(hours).each(function (i, n) {
                if (i == 0) {
                    groupedHours.push([hours[i], hours[i]]);
                }
                else {
                    if (hours[i] == hours[i - 1] + 1) {
                        groupedHours[currentGroupedIndex][1] = hours[i];
                    }
                    else {
                        groupedHours.push([hours[i], hours[i]]);
                        currentGroupedIndex++;
                    }
                }
            });
            $(groupedHours).each(function (i, n) {
                result += $.formatFacilityHour(n[0], n[1], timeFormat) + " <br/>";
            });
            if (result == "") {
                result = Vision.Resources.FacilityDirectory_Widget_ReservationSubmission_NoTimeSelected;
            }
            return result;
        },
        /* [name, value] array*/
        compressFormFieldArray: function (formFields) {
            var minChar = 97;
            var maxChar = 122;

            var totalCharCount = 26;
            var finalValue = {
                ks: [],
                vs: []
            };

            //0  -- a
            //26 -- aa
            var maxToStr = function (max) {
                var finalStr = "";
                var curMax = max;
                var mod = 0;
                if (curMax == 0)
                    return String.fromCharCode(minChar);

                while (curMax > 0) {
                    mod = curMax % totalCharCount;
                    curMax = Math.floor(curMax / totalCharCount);
                    finalStr = String.fromCharCode(minChar + mod - (finalStr.length <= 0 ? 0 : 1)) + finalStr;
                }
                return finalStr;
            }
            var convertKey = function (key) {
                key = key || "";
                var replacedKey = "";
                var splittedArray = key.split(".");
                $(splittedArray).each(function (i, n) {
                    var index = n.indexOf("[");
                    var toReplacedStr = index > 0 ? n.substr(0, index) : n;
                    if (finalValue.ks.length < i + 1) {
                        finalValue.ks.push({ max: 0, i: i, k: {} });
                        finalValue.ks[i].k[toReplacedStr] = maxToStr(finalValue.ks[i].max);
                        replacedKey += n.replace(toReplacedStr, maxToStr(finalValue.ks[i].max)) + ".";
                    } else {
                        if (finalValue.ks[i].k[toReplacedStr]) {
                            replacedKey += n.replace(toReplacedStr, finalValue.ks[i].k[toReplacedStr]) + ".";
                        } else {
                            finalValue.ks[i].max++;
                            finalValue.ks[i].k[toReplacedStr] = maxToStr(finalValue.ks[i].max);
                            replacedKey += n.replace(toReplacedStr, maxToStr(finalValue.ks[i].max)) + ".";
                        }
                    }
                });
                return replacedKey.substr(0, replacedKey.length - 1);
            }

            var normalize = function (fValue) {
                var newValue = {
                    ks: [],
                    vs: fValue.vs
                };
                $(fValue.ks).each(function (i, n) {
                    var array = [];
                    for (var kp in n.k) {
                        array.push([kp, n.k[kp]]);
                    }
                    newValue.ks.push({
                        i: n.i,
                        k: array
                    });
                });
                return newValue;
            }

            $(formFields).each(function () {
                var newName = convertKey(this[0]);
                finalValue.vs.push([newName, this[1]]);
            });

            return normalize(finalValue);
        }
    });

    $.extend($.fn, {
        selectRange: function (start, end) {
            return this.each(function () {
                if (this.setSelectionRange) {
                    this.focus();
                    this.setSelectionRange(start, end);
                }
                else
                    if (this.createTextRange) {
                        var range = this.createTextRange();
                        range.collapse(true);
                        range.moveEnd('character', end);
                        range.moveStart('character', start);
                        range.select();
                    }
            });
        },
        setSelection: function (selectionStart, selectionEnd) {
            if (this.lengh == 0) return this;
            input = this[0];

            if (input.createTextRange) {
                var range = input.createTextRange();
                range.collapse(true);
                range.moveEnd('character', selectionEnd);
                range.moveStart('character', selectionStart);
                range.select();
            } else if (input.setSelectionRange) {
                input.focus();
                input.setSelectionRange(selectionStart, selectionEnd);
            }

            return this;
        },
        setCursorPosition: function (position) {
            if (this.lengh == 0) return this;
            return $(this).setSelection(position, position);
        },
        insertAtCaret: function (content) {
            var $t = $(this)[0];
            if (document.selection) {
                this.focus();
                sel = document.selection.createRange();
                sel.text = content;
                this.focus();
            } else if ($t.selectionStart || $t.selectionStart == '0') {
                var startPos = $t.selectionStart;
                var endPos = $t.selectionEnd;
                var scrollTop = $t.scrollTop;
                $t.value = $t.value.substring(0, startPos) + content + $t.value.substring(endPos, $t.value.length);
                this.focus();
                $t.selectionStart = startPos + content.length;
                $t.selectionEnd = startPos + content.length;
                $t.scrollTop = scrollTop;
            } else {
                this.value += content; this.focus();
            }
        },
        characterCounter: function (options) {
            var defaultOptions = {
                target: ".remain_characters",
                container: function (item) {
                    return $(item).parent();
                },
                maxLength: 70,
            };
            options = $.extend({}, defaultOptions, options);
            $(this).each(function () {
                cauculate($(this));
            });

            function getSelectionText() {
                if (window.getSelection) {
                    return window.getSelection().toString();
                } else if (document.selection && document.selection.createRange) {
                    return document.selection.createRange().text;
                }
                return '';
            }

            $(this).keyup(function (e) { cauculate($(this)) });
            $(this).change(function (e) { cauculate($(this)) });
            $(this).keydown(function (e) {
                if (e.ctrlKey || (e.keyCode >= 37 && e.keyCode <= 40) || e.keyCode == 9) // ctrlKey or arrow keys or Tab
                    return true;

                if (e.keyCode != 8 && e.keyCode != 46) {// Backspace and Delete key
                    var count = $(this).val().length + 1;
                    var remainCount = options.maxLength - count;
                    if (remainCount < 0)
                        remainCount = 0;
                    if (count > options.maxLength && getSelectionText() == "") {
                        return false;
                    }
                }
            });

            function cauculate(element) {
                var value = element.val();
                if (options.ignoreCustomMsg) {
                    value = value.replace(/^Compose message.../g, "");
                }
                var remainCount = options.maxLength - value.length;
                if (remainCount < 0) {
                    var maxContent = value.substring(0, options.maxLength);
                    element.val(maxContent);
                }
                //update UI
                var remainCountText = remainCount < 0 ? 0 : remainCount;

                var target = null;
                if (typeof options.container == "function") {
                    target = options.container(element).find(options.target);
                } else {
                    target = $(element).closest(options.container).find(options.target);
                }
                target.text(remainCountText);
            };
        },
        adjustImageDimention: function (options) {
            var defaultOptions = {
                width: 140,
                height: 140,
                desireWidth: 100,
                ratios: '.75:1', //height to width
                roundedCorner: false,
                defaultColor: '#C9C9C9'
            }
            options = $.extend({}, defaultOptions, options);

            var imgWidth = options.width;
            var imgHeight = options.height;
            var containerWidth = options.desireWidth;
            var containerHeight = options.desireWidth;
            var ratiosWidth = options.ratios.split(":")[1];
            var ratiosHeight = options.ratios.split(":")[0];
            var imgContainer = $(this).parent();

            if (options.roundedCorner) {
                imgContainer.css({
                    height: containerHeight,
                    width: containerWidth,
                    overflow: 'hidden',
                    'border-radius': containerHeight,
                    'background-color': options.defaultColor,
                    'border': '1px solid ' + options.defaultColor
                });
            }
            else {
                var containerHeight = containerHeight * ratiosHeight
                var containerWidth = containerWidth * ratiosWidth;
                imgContainer.css({
                    height: containerHeight,
                    width: containerWidth,
                    overflow: 'hidden',
                    'border-radius': 5,
                    'background-color': options.defaultColor,
                    'border': '1px solid ' + options.defaultColor
                });
            }

            if (ratiosHeight > ratiosWidth) {
                //vertical
                var adjustedHeight = containerHeight;
                var adjustedWidth = (imgWidth * adjustedHeight) / imgHeight;
                if (adjustedWidth < containerWidth) {
                    adjustedWidth = containerWidth;
                    adjustedHeight = (imgHeight * adjustedWidth) / imgWidth;
                }
            }
            else {
                //horizontal and square
                var adjustedWidth = containerWidth;
                var adjustedHeight = (imgHeight * adjustedWidth) / imgWidth;
                if (adjustedHeight < containerHeight) {
                    adjustedHeight = containerHeight;
                    adjustedWidth = (imgWidth * adjustedHeight) / imgHeight;
                }
            }

            $(this).css({
                width: adjustedWidth,
                'max-width': adjustedWidth, //for front end
                height: adjustedHeight,
                position: 'relative',
                top: (Math.abs(adjustedHeight - containerHeight) / 2) * -1,
                left: (Math.abs(adjustedWidth - containerWidth) / 2) * -1,
                'border': 0
            });

        }
    });
})(jQuery);

$(function (e) {
    /***************Wiget Razor Format Container Show model properties - Start***************/

    window.razorTypes = new Array();
    window.razorDialogs = new Array();
    //window.dialogs = new Array();
    $("body").delegate("a.show_razor_model_property", "click", function (e) {
        var url = $(this).closest("div.help_notes_body").attr("showPropertyUrl");
        var followEle = this;
        if (typeof (url) != "undefined" && url.length > 0) {
            var typeName = $(this).attr('razorType');
            var urlWithTypeName = url + "?typeName=" + typeName;
            var opts = {
                title: typeName, width: 600, url: urlWithTypeName, useFrame: false, resize: true, lock: false,
                padding: 0,
                fixed: false,//should follow the element, if the element scroll, the dialog should follow the element.
                follow: followEle,
                onClosed: function () {
                    if (window.razorTypes) {
                        var elementIndex = $.inArray(typeName, window.razorTypes);
                        if (elementIndex >= 0) {
                            window.razorTypes.splice(elementIndex, 1);
                            window.razorDialogs.splice(elementIndex, 1);
                        }
                    }
                }
            };
            if (window.razorTypes) {
                //if not eixist
                var index = $.inArray(typeName, window.razorTypes);
                if (index < 0) {
                    var dialog = $.viClientDialog(opts).open();
                    window.razorTypes.push(typeName);
                    window.razorDialogs.push(dialog);
                } // exists, add z-index
                else {
                    window.razorDialogs[index].zIndex();
                }
            }
        }
        e.preventDefault();
    });
    /***************Wiget Razor Format Container Show model properties - End***************/

    /***************Send Email********************/
    ; (function ($) {
        $.extend($, {
            SendEmail: function (options) {
                if (options != null && options != undefined) {
                    var addresses = (options.addresses == null || options.addresses == undefined) ? "" : options.addresses;
                    var subject = (options.subject == null || options.subject == undefined) ? "" : "&subject=" + options.subject;
                    var body = (options.body == null || options.body == undefined) ? "" : "&body=" + options.body;
                    var cc = (options.cc == null || options.cc == undefined) ? "" : "&cc=" + options.cc;
                    var bcc = (options.bcc == null || options.bcc == undefined) ? "" : "&bcc=" + options.bcc;
                    var params = subject + body + cc + bcc;
                    if (params != "") {
                        params = "?" + params.substring(1);
                    }
                    window.location.href = "mailto:" + addresses + params;
                }
            }
        });
    })(jQuery);
});

/*************** Category Selector Start ********************/
var ViCategorySelector = function (element, options) {
    var defaults = {
        isLoaded: false,
        ajaxData: null,
        ajaxUrl: "",
        eventName: "click",
        targetEl: $(".vi-animation-container"),
        getAjaxDataFunc: null,
        animSpeed: 100,
        minWidth: 120,
        minHeight: 100,
        maxHeight: 500,
        beforeShow: function () {
            var dropDown = this;
            var settings = dropDown.setting;
            var targetEle = $(settings.targetEl);
            var data = $.isFunction(settings.getAjaxDataFunc) ? settings.getAjaxDataFunc() : settings.ajaxData;
            var url = settings.ajaxUrl;
            var isLoaded = settings.isLoaded;
            if (!isLoaded) {
                settings.isLoaded = true;
                targetEle.loading(true, { mask: true });
                $.vision().ajax({
                    url: url,
                    data: data,
                    type: 'GET',
                    success: function (data, textStatus, jqXHR) {
                        if ($.type(data) == 'string') {
                            targetEle.html(data);
                            targetEle.loading(null, null, true);
                        } else {
                            alert(Vision.Resources.EnotificationCategorySelector_LoadCheckboxFailed);
                            targetEle.loading(null, null, true);
                        }
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(Vision.Resources.UI_Common_FrontendAjaxGetFailed);
                        targetEle.loading(null, null, true);
                    }
                });
            }
        },
        init: function (_this) {
            var categorySelector = _this.dropDown,
                setting = _this.setting,
                input = categorySelector.is(":text") ? categorySelector : categorySelector.find(".vi-input"),
                hidden = input.next(),
                popuPanel = _this.dropDownPanel;
        }
    };
    var zIndex = $(element).getZIndex() + 1;
    var extendOptions = $.extend({ zIndex: zIndex }, defaults, options);
    this.categorySelector = $(element);
    this.categorySelector.viDropdown(extendOptions);
    $.extend(this, this.categorySelector.viDropdown(extendOptions).data("viDropdown"));
};

$.fn.viCategorySelector = function (options) {
    return this.each(function (key, value) {
        var element = $(this);
        if (element.data('viCategorySelector')) return element.data('viCategorySelector');
        var viCategorySelector = new ViCategorySelector(this, options);
        element.data('viCategorySelector', viCategorySelector);
    });
};

var ContentTypeCategoryModel = function (jsonData) {
    var obj = this.DeserializeFromJson(jsonData);
    this.ToCategories = obj.ToCategories || [];
    this.ToContentTypes = obj.ToContentTypes || [];
}
ContentTypeCategoryModel.prototype = {
    ToContentTypes: [],
    ToCategories: [],
    SerializeToJson: function () {
        return JSON.stringify(this);
    },
    DeserializeFromJson: function (jsonData) {
        return $.parseJSON(jsonData);
    },
    Reset: function (toCategories, toContentTypes) {
        this.ToCategories = toCategories || [];
        this.ToContentTypes = toContentTypes || [];
    }
};

Array.prototype.contains = function (element) {

    for (var i = 0; i < this.length; i++) {
        if (this[i] == element) {
            return true;
        }
    }
    return false;
}
Array.prototype.indexOf = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

ViCategorySelector.GenerateModelWithNewContentType = function (newContentTypeId, subCategories, value) {
    var model = new ContentTypeCategoryModel(value);
    if (!model.ToContentTypes.contains(newContentTypeId)) {
        model.ToContentTypes.push(parseInt(newContentTypeId));
        //remove sub categoryId
        $.each(subCategories, function (i, e) {
            model.ToCategories.remove(e);
        });

    }
    return model.SerializeToJson();
}

ViCategorySelector.GenerateModelWithRemovedContentType = function (removedContentTypeId, subCategories, value) {
    var model = new ContentTypeCategoryModel(value);
    if (model.ToContentTypes.contains(parseInt(removedContentTypeId))) {
        model.ToContentTypes.remove(parseInt(removedContentTypeId));
        //remove sub categoryId
        $.each(subCategories, function (i, e) {
            model.ToCategories.remove(e);
        });

    }
    return model.SerializeToJson();
}

ViCategorySelector.GenerateModelWithNewCategory = function (newCategoryId, value) {
    var model = new ContentTypeCategoryModel(value);
    if (!model.ToCategories.contains(newCategoryId))
        model.ToCategories.push(parseInt(newCategoryId));
    return model.SerializeToJson();
}

ViCategorySelector.GenerateModelWithRemovedCategory = function (removedCategoryId, value) {
    var model = new ContentTypeCategoryModel(value);
    if (model.ToCategories.contains(removedCategoryId)) {
        model.ToCategories.remove(parseInt(removedCategoryId));
    }
    return model.SerializeToJson();
}
/*************** Category Selector End ********************/

$(function () {
    /*
    Trigger all the function in the Script Stack queue. 
    Dependence the jquery.callbackmanager.js in the jquery-plugins
    */
    $.triggerScripts();
});

/* Mobile Reorder */

/* Random ID generator for elements */
var generateGUID = function () {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

// Execute fixes, workarounds and overrides before DOM moves
var mobileReorderInitOverrides = function () {
    /*
    This function can be overriden using project folder scripts
    if more mobile issues are found in the future

    This function runs before the DOM is moved
    */

    /* Missing iFrame SRC fix - Start */
    /* Save all iframes without src attributes */
    $("#sitebody .column").find("iframe[src=''], iframe:not([src])").each(function (idx, val) {
        /* Initialize iframe array */
        if (typeof window.mobileReorderIframes == 'undefined')
            window.mobileReorderIframes = {};

        /* If there's no ID for the iframe, generate an ID for iframe */
        var idAttr = $(val).attr('id');
        if (typeof idAttr == typeof undefined || idAttr == false || idAttr.length < 1)
            $(val).attr("id", generateGUID());

        /* Save all contents of the head and body to mobile reorder iframes */
        window.mobileReorderIframes[$(val).attr("id")] = {
            head: $(val).contents().find("head").detach(),
            body: $(val).contents().find("body").detach()
        };
    });
    /* Missing iFrame SRC fix - End */
};

// Execute fixes, workarounds and overrides after DOM moves
var mobileReorderOverrides = function () {
    /*
    This function can be overriden using project folder scripts
    if more mobile issues are found in the future

    This function runs after the DOM is moved
    */

    /* Missing iFrame SRC fix */
    /* Restore all iframes' data without src attributes */
    $("#sitebody .column").find("iframe[src=''], iframe:not([src])").each(function (idx, val) {
        /* Save all contents of the head and body to mobile reorder iframes */
        var iframeData = window.mobileReorderIframes[$(val).attr("id")];
        if (typeof iframeData != 'undefined') {
            /* 
            Use load instead to fix iframe delay issues in:
                - Firefox 
                - IE 10 or lower
            */
            if (($.browser.mozilla == true) ||
                ($.browser.msie && parseInt($.browser.version) < 11)
                ) {
                $(val).load(function () {
                    $(val).contents().find('html').empty();
                    $(val).contents().find('html').append(iframeData.head);
                    $(val).contents().find('html').append(iframeData.body);
                });
            }
            else {
                $(val).contents().find('html').empty();
                $(val).contents().find('html').append(iframeData.head);
                $(val).contents().find('html').append(iframeData.body);
            }
        }
    });
    /* Missing iFrame SRC fix - End */
};

// Reorder widgets for mobile view
var renderMobile = function () {
    mobileReorderInitOverrides();
    // Hide body before loading
    $('#sitebody').addClass("force_hide_column");

    // remove scripts to avoid javascript firing again on wrap(), then add mobile column
    $('#sitebody .column').find('script').remove();

    // wrap a div around the widget start comment, move widget html into div. Document original position.
    i = 0;
    $("#sitebody *").not('iframe').contents().filter(function () { return this.nodeType == 8; }).each(function () {
        if (this.nodeValue.indexOf('!!WidgetStart') >= 0) {

            var ordernum = this.nodeValue.match("vi-orderdata=\"(.*)\"  vi-hideonmobile");
            var showhide = this.nodeValue.match("vi-hideonmobile=\"(.*)\"Widget");
            var parentid = "";

            // Fetch parent id
            if ($(this).parent().attr('id') == undefined || $(this).parent().attr('id') == '') {
                try { parentid = $(this).parent().parent().attr('id'); } catch (err) { }
            } else {
                parentid = $(this).parent().attr('id');
            }

            $(this).wrap('<div class="mobile_reorder_widget clearfix"  vi-orderdata="' + ordernum[1] + '" vi-hideonmobile="' + showhide[1] + '" vi-deskorder="' + i + '" vi-column="' + parentid + '"></div>');
            i++;
        } else if (this.nodeValue.indexOf('!!WidgetEnd') >= 0) {
            thewidget = $(this).prevAll(".mobile_reorder_widget:first");
            widgetcontent = $(this).prevUntil(".mobile_reorder_widget").andSelf();
            if ($(this).parents('.home_collage').size() > 0) {
                home_collage = $(this).parents('.home_collage:first');
                thewidget.insertBefore(home_collage);
                $(this).appendTo(home_collage);
                widgetcontent = $(this).parents('.home_collage:first').detach().after($(this));
            }
            if ($(this).parents('.home_buttons').size() > 0) {
                home_buttons = $(this).parents('.home_buttons:first');
                thewidget.insertBefore(home_buttons);
                $(this).appendTo(home_buttons);
                widgetcontent = $(this).parents('.home_buttons:first').detach().after($(this));
            }

            widgetcontent.appendTo(thewidget);

            if ($('#sitebody').hasClass('homepagelayout') && thewidget.attr('vi-hideonmobile') == 'false') {
                thewidget.parentsUntil('#sitebody').each(function (index) {
                    var thisid = "";
                    if ($(this).attr('id')) { var thisid = $(this).attr('id') }
                    var colclass = "fake_col";
                    thewidget.wrapInner("<" + $(this).prop("tagName") + " class=\"" + $(this).attr('class') + " " + colclass + "\" id=\"" + thisid + "\"></" + $(this).prop("tagName") + ">");

                });
            }
        }
    });

    //if widgets are reordered	
    if ($("#sitebody").find(".mobile_reorder_widget[vi-orderdata!='0']").length > 0) {
        //hide any remaining columns
        $('#sitebody > *').not("#MobileColumnUserControl1, .home_floatarea, link").addClass("force_hide_column");
        //make list of ordered widgets
        var listItems = $('#sitebody').find(".mobile_reorder_widget").sort(function (a, b) { return $(a).attr('vi-orderdata') - $(b).attr('vi-orderdata'); });
        //append ordered widgets to mobile column
        listItems.each(function () {
            if ($(this).attr('vi-hideonmobile') == 'true')
                $(this).addClass("force_hide_column");
            $('#MobileColumnUserControl1').append($(this));
        });

        // Allow asynchronous widgets to load after the iframe loads
        $(".async_widget_container:not(.custominvoke)").each(function (i, item) {
            $(item).loadAsyncContainer()
        });
    }
    else {
        // If the page is not reordered but has hidden widgets
        if ($("#sitebody").find(".mobile_reorder_widget[vi-hideonmobile='true']").length > 0) {
            var listItems = $('#sitebody').find(".mobile_reorder_widget");
            listItems.each(function () {
                if ($(this).attr('vi-hideonmobile') == 'true')
                    $(this).addClass("force_hide_column");
            });
        }
    }

    mobileReorderOverrides();
    // Show body after loading
    $('#sitebody').removeClass("force_hide_column");
};

// Restore desktop original layout and columns
var restoreDesktop = function () {
    mobileReorderInitOverrides();
    if ($("#sitebody #MobileColumnUserControl1").find(".mobile_reorder_widget").length > 0) {
        //show hidden columns
        $('#sitebody > *').not("#MobileColumnUserControl1, .home_floatarea, link").removeClass("force_hide_column");
        $('#sitebody').find(".fake_col > *").unwrap();
        $('#sitebody').find(".fake_col:empty").remove();

        //make list of ordered widgets ordered for desktop
        var listItems = $('#sitebody').find(".mobile_reorder_widget").sort(function (a, b) { return $(a).attr('vi-deskorder') - $(b).attr('vi-deskorder'); });
        //append ordered widgets to correct column
        listItems.each(function () {
            parentcol = $(this).attr('vi-column');
            $('#sitebody').find('#' + parentcol).append(this);
        });

        // Allow asynchronous widgets to load after the iframe loads
        $(".async_widget_container:not(.custominvoke)").each(function (i, item) {
            $(item).loadAsyncContainer()
        });
    }
    else {
        // If the page is not reordered but has hidden widgets
        if ($("#sitebody").find(".mobile_reorder_widget[vi-hideonmobile='true']").length > 0) {
            var listItems = $('#sitebody').find(".mobile_reorder_widget");
            listItems.each(function () {
                if ($(this).attr('vi-hideonmobile') == 'true')
                    $(this).removeClass("force_hide_column");
            });
        }
    }

    //remove mobile column and divs
    $('#sitebody').find(".mobile_reorder_widget > *").unwrap();
    $('#sitebody').find(".mobile_reorder_widget:empty").remove();
    mobileReorderOverrides();
};

// Run this function after the body tag to hide all widgets without flicker
var manualRenderMobile = function () {
    var isReordered = window.reordered ? window.reordered == true : false;
    var hasHiddenWidgets = window.hashiddenwidgets ? window.hashiddenwidgets == true : false;
    var inPreviewMobile = window.parent ? (window.parent.inpreviewmobile ? window.parent.inpreviewmobile == true : false) : false;
    if (inPreviewMobile || isReordered || hasHiddenWidgets) {
        // Append if mobile column is missing
        if ($("#sitebody #MobileColumnUserControl1").length < 1)
            $('#sitebody').append("<div id=\"MobileColumnUserControl1\" class=\"column mobile_only clearfix\"></div>");

        if (window.innerWidth <= 647) {
            renderMobile();
            window.switchedToMobile = true;
        }
    }
}

$(function () {
    // Backup site body HTML to window DOM
    var isReordered = window.reordered ? window.reordered == true : false;
    var hasHiddenWidgets = window.hashiddenwidgets ? window.hashiddenwidgets == true : false;
    var inPreviewMobile = window.parent ? (window.parent.inpreviewmobile ? window.parent.inpreviewmobile == true : false) : false;

    // Add listener event to window resize
    // Only reorder if resized and page is reordered
    if (inPreviewMobile || isReordered || hasHiddenWidgets) {
        // Append if mobile column is missing
        if ($("#sitebody #MobileColumnUserControl1").length < 1)
            $('#sitebody').append("<div id=\"MobileColumnUserControl1\" class=\"column mobile_only clearfix\"></div>");

        if ($('.home_collage').size() > 0) {
            $('.home_collage').wrap("<div id=\"" + $('.home_collage').attr('id') + "\"></div>");
            $('.home_collage').attr('id', '');
        }
        if ($('.home_buttons').size() > 0) {
            $('.home_buttons').wrap("<div id=\"" + $('.home_buttons').attr('id') + "\"></div>");
            $('.home_buttons').attr('id', '');
        }

        $(window).resize(function () {
            if (this.resizeTO) clearTimeout(this.resizeTO);
            this.resizeTO = setTimeout(function () {
                $(this).trigger("resizeEnd");
            }, 150);
        });
        $(window).bind("resizeEnd", function () {
            // check window status 150ms
            if ((window.switchedToMobile == null || (window.switchedToMobile != null && window.switchedToMobile == false)) && window.innerWidth <= 647) {
                renderMobile();
                window.switchedToMobile = true;
            }
            else if (window.switchedToMobile && window.switchedToMobile == true && window.innerWidth > 647) {
                restoreDesktop();
                window.switchedToMobile = false;
            }
        });
    }
});

/*********** faqTabListManager Start**************/
; (function () {

    var faqTabListManager = function (options) {
        this.options = $(options);
    }

    faqTabListManager.prototype = {
        init: function () {
            var $thisObj = this;
            var $faqWidget = $thisObj.options;

            var tabheight = $faqWidget.find(".faq_tab_nav").height();
            $faqWidget.find('.faqtab_section').attr('style', 'min-height: ' + (tabheight - 42) + 'px');

            //Recalculate on window resize
            var resizeTimer;
            $(window).resize(function () {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(function () {
                    $thisObj.faqResizeTab();
                }, 200);
            });

            $thisObj.faqHashChangeFun();
            if ("onhashchange" in window) {
                window.onhashchange = function () {
                    $thisObj.faqHashChangeFun();
                }
            } else {
                $(".faq_tab_nav ul li a").click(function () {
                    $(this).closest('.faq_tab_nav ul li a').find('.active_faqtab').removeClass('active_faqtab');
                    $(this).addClass('active_faqtab');
                    var content = $($(this).attr("href"));
                    content.show().addClass('active_faqtab').siblings().hide().removeClass('active_faqtab');
                    $thisObj.faqResizeTab();
                });
            }

            $faqWidget.find(".faqtab_question").click(function () {
                $(this).toggleClass("faqquestion_open");
                var thisanswer = $(this).next(".faqtab_answer");
                thisanswer.toggleClass('faqanswer_open');
                $faqWidget.find('.faq_tab_contents').find(".faqquestion_open").not(this).removeClass("faqquestion_open");
                $faqWidget.find('.faq_tab_contents').find(".faqanswer_open").not(thisanswer).removeClass("faqanswer_open");
            });

            $faqWidget.find("#tabselect").change(function () {
                var content = $faqWidget.find("#tabselect").val();
                $faqWidget.find('.faq_tab_nav ul li a').each(function () {
                    var hrefattr = $(this).attr("href");
                    if (hrefattr == content) {
                        $(this).addClass('active_faqtab');
                    } else { $(this).removeClass('active_faqtab'); }
                });
                $(this).closest('.faq_tab_nav ul li a').find('.active_faqtab').removeClass('active_faqtab');
                $(this).addClass('active_faqtab');
                $(content).show().addClass('active_faqtab').siblings().hide().removeClass('active_faqtab');
                $thisObj.faqResizeTab();
            });
        },

        faqHashChangeFun: function () {
            var $thisObj = this;
            var $faqWidget = $thisObj.options;
            var hash = window.location.hash,
                el = $('.faq_tab_nav [href*="' + hash + '"]'),
                content = $(hash);

            if (el.length && !el.hasClass('active_faqtab') && content.length) {
                el.closest('.faq_tab_nav').find('.active_faqtab').removeClass('active_faqtab');
                el.addClass('active_faqtab');
                content.show().addClass('active_faqtab').siblings().hide().removeClass('active_faqtab');
                $thisObj.faqResizeTab();
            }
        },

        faqResizeTab: function () {
            var $thisObj = this;
            var $faqWidget = $thisObj.options;

            tabheight = $faqWidget.find(".faq_tab_nav").height();
            $faqWidget.find('.faqtab_section').attr('style', 'min-height: ' + (tabheight - 42) + 'px');
        }
    };

    $.extend($.fn, {
        faqTabList: function () {
            if ($(this).length <= 0)
                return null;
            $(this).each(function () {
                var manager = $(this).data("faqTabList");
                if (typeof manager == "undefined") {
                    manager = new faqTabListManager(this);
                    manager.init();
                    $(this).data("faqTabList", manager);
                }
            });
            return $($(this)[0]).data("faqTabList");
        }
    });
})(jQuery);
/*********** faqTabListManager End****************/

//Calendar touch 
(function () {
    var eventName = "";
    if ("ontouchstart" in window   // Chrome & Safari (IOS) && Firefox
         || "onpointerdown" in window   // IE 11 
         || window.MSPointerEvent) {
        eventName = "ontouchstart" in window ? "touchstart"
                     : "onpointerdown" in window ? "pointerdown"
                     : window.MSPointerEvent ? "MSPointerDown"
                     : "";
    }
    var _isIE = $.isIEBrowser();
    var _isIE9 = $.isIE9Browser();

    function isTouchScreenEvent(event) {
        var _isTouchScreen = false;
        if ("ontouchstart" in window) {
            _isTouchScreen = true;
        } else if ("onpointerdown" in window) {
            _isTouchScreen = event.originalEvent.pointerType == "touch";
        } else if (window.MSPointerEvent) {
            _isTouchScreen = event.originalEvent.pointerType == event.originalEvent.MSPOINTER_TYPE_TOUCH; // 2 ; http://blogs.msdn.com/b/ie/archive/2011/09/20/touch-input-for-ie10-and-metro-style-apps.aspx
        } else {
        }
        return _isTouchScreen;
    }

    var viAnchorTouching = function (container, options) {
        this._container = $(container);
        this._options = $.extend({}, viAnchorTouching.defaultOptions, options);
        this._targets = $(this._options.anchorTarget, this._container);
    }

    viAnchorTouching.prototype = {
        _init: function () {
            var $thisObj = this;
            var $thisTargets = $thisObj._targets;
            var $options = $thisObj._options;
            var $container = $thisObj._container;
            if (eventName.length > 0) {
                $thisTargets.bind(eventName, function (event) {
                    var $target = $(this);
                    if (isTouchScreenEvent(event) == false) {
                        return true;
                    }
                    //Click in anchor or its parent??
                    var thisShowPanel = $target.next($options.showPanel);
                    var hasShowPanel = thisShowPanel.length > 0;
                    if (!hasShowPanel) return true;

                    if (!thisShowPanel.hasClass('touch-active')) {
                        if (_isIE) {
                            $target.attr("data-href", $target.attr("href"));
                            $target.attr("href", "javascript:void(0);");
                        }

                        var container = $container;
                        if ($options.closeOtherTarget == true) {
                            container = $("body");
                        }
                        $($options.showPanel, container).filter('.touch-active').not(thisShowPanel).removeClass('touch-active');
                        thisShowPanel.addClass('touch-active');
                        return false;
                    }
                    else {
                        if (_isIE) {
                            $target.attr("href", $target.attr("data-href"));
                        }
                        thisShowPanel.removeClass('touch-active');
                    }
                });

                $('body').bind(eventName, function (event) {
                    if (isTouchScreenEvent(event) == false) {
                        return true;
                    }
                    else {
                        var showPanel = $(event.target).closest($options.showPanel);
                        if (showPanel.length == 0)
                            showPanel = $(event.target).next($options.showPanel);
                        if (showPanel.length > 0) {
                            return true;
                        }
                    }
                    var container = $container;
                    if ($options.closeOtherTarget == true) {
                        container = $("body");
                    }
                    $($options.showPanel, container).filter('.touch-active').removeClass('touch-active');
                });
            }
        }
    };
    viAnchorTouching.defaultOptions = {
        anchorTarget: ".touching-anchor",
        closeOtherTarget: true
    };

    $.extend($.fn, {
        anchorTouching: function (options) {
            if ($(this).length <= 0)
                return null;

            $(this).each(function (i, n) {
                var viAnchorTouchingObj = $(n).data("anchorTouching");
                if (typeof viAnchorTouchingObj == "undefined") {
                    viAnchorTouchingObj = new viAnchorTouching(n, options);
                    viAnchorTouchingObj._init();
                    $(n).data("anchorTouching", viAnchorTouchingObj);
                }
            });
            return $($(this)[0]).data("anchorTouching");
        }
    });
})(jQuery);

(function () {
    var clientResponsiveTableEnabled = false;
    if (window.visionOptions != undefined && window.visionOptions.clientResponsiveTableEnabled != undefined) {
        clientResponsiveTableEnabled = window.visionOptions.clientResponsiveTableEnabled;
    }
    //Responsive CMS6 Tables & Responsive Client data table - This will be on Mobile view only
    $(".front_end_body table:not(.non-responsive-table)").each(function () {
        if ($(this).filter(".listtable, .tableData").length > 0) {
            if ($(this).find(">tr>th,>thead>tr>th,>tbody>tr>th").length > 0) {
                //Responsive CMS6 Tables
                $(this).addClass("responsive-table-data-mb");

                //if (clientResponsiveTableEnabled) {
                //    // Responsive Client Data Tables.
                //    if ($(this).filter(".tabledata").length > 0) {
                //        $(this).addClass("responsive-table-data-dkt");
                //    }
                //}

                var allHeaders = [];
                $(this).find(">tr>th,>thead>tr>th,>tbody>tr>th").each(function (i, n) {
                    allHeaders.push($(this).text());
                });
                $(this).find("tbody>tr,>tr").each(function (i, n) {
                    $(n).find("td").each(function (j, m) {
                        $(m).attr("data-th", allHeaders[j]);
                        var title = $(m).attr("data-th");
                        var content = $(m).text() && $(m).html();
                        if (content.trim().length == 0 && title.trim().length == 0) {
                            $(m).addClass("hideEmptyRow");
                        }

                    });
                });

                $(this).find("td.poll_thumbnail_col").each(function () {
                    $(this).removeClass("poll_thumbnail_col");
                });
            }
        }
    });

    $('.faqtab_answer').each(function () {
        $(this).find("table:not(.non-responsive-table)").width("100%");
    });

    //Responsive Client List Tables & Responsive Client Scrolling Tables
    function responsiveTables() {
        $(".front_end_body table:not(.responsive-table-data-mb)").each(function () {
            //Responsive Client List Tables except calendar tables
            if ($(this).find(">tbody>tr,>thead>tr").length == 1 && $(this).find("tbody>tr>th,thead>tr>th").length == 0 && !$(this).hasClass("calendar_title")) {
                if ($(this).width() > $(window).width() || ($(this).width() > $(this).parent().width() && $(this).parent().width() != 0)) {
                    if (!$(this).parent().hasClass("responsive-table-list")) {
                        $(this).wrap("<div class=\"responsive-table-list\"></div>");
                        $(this).width("100%");
                        $(this).find("img, object").each(function () {
                            $(this).css("max-width", "100%");
                        });
                    }
                }
            }
            else if (!($(this).find(">tbody>tr,>thead>tr").length == 1 && $(this).find("tbody>tr>th,thead>tr>th").length == 0)) {
                //Responsive Client Scrolling Tables
                var maxWith;
                maxWidth = $(this).css("max-width");
                if ($(this).width() > $(window).width() || ($(this).width() > $(this).parent().width() && $(this).parent().width() > 0)) {
                    if ($('.faqtab_answer').length > 0) {
                        $(this).width("100%");
                    }
                    else if (!$(this).parent().hasClass('responsive-table-scroll')) {
                        $(this).css("max-width", "none");
                        $(this).wrap('<div class="responsive-table-scroll left_scroll"></div>');
                    } else {
                        $(this).css("max-width", maxWidth);
                    }
                } else if ($(this).parent().hasClass('responsive-table-scroll')) {
                    $(this).unwrap();
                }
            }
        });

        $('.responsive-table-scroll').scroll(function () {
            var currPos = $(this).scrollLeft();
            if (0 < currPos) {
                $(this).addClass('right_scroll');
            } else {
                $(this).removeClass('right_scroll');
            }
            $inner_table = $(this).find('>table');
            if (currPos + $(this).width() == $inner_table.outerWidth()) {
                $(this).removeClass('left_scroll');
            } else if (!$(this).hasClass('left_scroll')) {
                $(this).addClass('left_scroll');
            }
        });
    }

    function adjustVideos() {
        $("iframe[src*=youtube]").each(function () {
            if (!$(this).parent().hasClass("videoWrapper")) {
                $(this).wrap("<div class='videoWrapper'></div>");
            }
        });
    }

    if (clientResponsiveTableEnabled) {
        responsiveTables();
        adjustVideos();
        $(window).resize(function () {
            if (this.resizeTo) clearTimeout(this.resizeTo);
            this.resizeTo = setTimeout(responsiveTables(), 150);
        });
    }

    /* import button at backend */
    $(".import-button[data-url]").click(function () {
        var postData = $.parseJSON($(this).attr("data-url-post") || "{}");
        var opts = {
            title: $(this).text(),
            url: $(this).attr("data-url"),
            useFrame: false,
            //don't remove
            width: 545,
            data: postData,
            onClosed: function (result) {
                if (result && result.IsOk === true) {
                    $.refreshTempMessage(result.Message);
                    setTimeout(function () {
                        $.vision().refresh();
                    }, 300);
                }
            }
        };
        $.viClientDialog(opts).open();
    });
    /* import button at backend */

    /* add/remove autocomplete for all fields under .auto-complete-container */
    $(".auto-complete-container[data-auto-complete]").each(function () {
        var autoCompleteSetting = $(this).attr("data-auto-complete") || "off";
        if (autoCompleteSetting == "off") {
            $(this).find("form,input,select,textarea").attr("autocomplete", autoCompleteSetting);
        } else {
            $(this).find("form,input,select,textarea").removeAttr("autocomplete");
        }
    });

})(jQuery);

/*********** viPanelPopupManager Start**************/
; (function ($, undefined) {

    var ViPanelPopupManager = function viPanelPopupManager(element, options) {
        this.button = $(element);
        this.options = $(options);
        this.visible = false;

        var defaults = {
            animSpeed: 100,
            height: 250,
            width: 200
        };
        var zIndex = $(element).getZIndex() + 1;
        this.setting = $.extend({ zIndex: zIndex }, defaults, options);

        this.container = null;
        this.init();
    }

    ViPanelPopupManager.prototype = {

        init: function () {

            var $thisObj = this;

            this.addPanelDiv();

            this.bindButton();

            $(window).resize(function () {
                $thisObj.snapToAnchor();
            });

            $("body").click(function (e) {
                var dateContainers = $(e.target).closest(".ui-datepicker");
                var dateNowContainers = $(e.target).closest(".ui-datepicker-current");
                var dateArrowRightContainers = $(e.target).closest(".ui-icon-circle-triangle-e");
                var dateArrowLeftContainers = $(e.target).closest(".ui-icon-circle-triangle-w");
                var dateContainer = dateContainers.length + dateNowContainers.length + dateArrowRightContainers.length + dateArrowLeftContainers.length;
                var allContainers = $(e.target).closest(".vi-panel-container");
                if ((allContainers.length <= 0 || allContainers.index($thisObj.container) < 0) && (dateContainer <= 0)) {
                    $thisObj.closePanel();
                }
            });
        },

        bindButton: function () {
            var $this = this;

            this.button.on("click", function (event) {
                event.preventDefault();

                //added to prevent double-click
                $(this).prop('disabled', true);
                $this.openPanel();
                $(this).prop('disabled', false);
                return false;
            });
        },

        addPanelDiv: function () {
            var body = document.body;

            if (!body) {
                throw new Error('viPanelPopupManager: "documents.body" not ready');
            };

            var wrap = document.createElement("div");
            $(wrap).attr("class", "vi-panel-container");
            body.appendChild(wrap, body.firstChild);
            this.container = $(wrap);
            this.loading = $("<div class='vi-panel-loading'></div>");
            this.container.append(this.loading);
            if (this.setting.width) {
                this.loading.css({
                    "min-width": this.setting.width + "px"
                });
            }
            if (this.setting.height) {
                this.loading.css({
                    "min-height": this.setting.height + "px"
                });
                this.container.css({
                    "max-height": this.setting.height + "px"
                });
            }

            this.container.hide();
        },

        openPanel: function () {
            var $container = this.container;
            if (!this.visible) {
                this.visible = true;
                if ($container.find(".vi-panel-loading").length > 0) this.loadUrl();
                $container.slideDown(this.setting.animSpeed, function () {
                    $(this).show();
                });
                this.snapToAnchor();
            } else this.closePanel();
        },

        closePanel: function () {
            var $this = this;
            this.container.slideUp(this.setting.animSpeed, function () {
                $(this).hide();
                $this.visible = false;
            });

        },

        loadUrl: function () {
            var $container = this.container;
            var $url = this.button.data("url");
            var data = {};
            if (this.button.data("url-post")) {
                data = this.button.data("url-post");
            }
            if ($.vision) {
                $.vision().ajax($url,
                {
                    data: data,
                    cache: false,
                    success: function (content) {
                        if (content == null) content = "<span>Error loading " + URL + "</span>";
                        $container.html(content);
                    }
                });
            } else if ($.frontendAjax) {
                $.frontendAjax($url,
                    {
                        data: data,
                        cache: false,
                        success: function (content) {
                            if (content == null) content = "<span>Error loading " + URL + "</span>";
                            $container.html(content);
                        }
                    });
            } else {
                $.ajax({
                    url: $url,
                    cache: false,
                    data: data,
                    success: function (content) {
                        if (content == null) content = "<span>Error loading " + URL + "</span>";
                        $container.html(content);
                    }
                });
            }
        },

        snapToAnchor: function () {
            var $container = this.container;

            var pos = this.button.offset();
            var $top = pos.top + this.button.outerHeight();
            var $left = pos.left - $container.outerWidth() + this.button.outerWidth();
            $container.css({
                position: "absolute",
                top: $top + "px",
                left: $left + "px"
            });
        }
    };
    $.fn.viPanelPopupManager = function (options) {
        return this.each(function (key, value) {
            var element = $(this);
            // Return early if this element already has a plugin instance
            if (element.data("viPanelPopupManager")) return element.data("viPanelPopupManager");
            // Pass options to plugin constructor

            var viPanelPopupManager = new ViPanelPopupManager(this, options);
            // Store plugin object in this element's data
            element.data("viPanelPopupManager", viPanelPopupManager);
        });
    };


    $(".export-button[data-url]").viPanelPopupManager({ width: 550, height: 300 });
})(jQuery);


(function () {
    $.fn.replaceOptions = function (options) {
        var self, $option;

        this.empty();
        self = this;

        $.each(options, function (index, option) {
            $option = $("<option></option>")
              .attr("value", option.value)
              .text(option.text);
            self.append($option);
        });
    };
})(jQuery);

/*********** viPanelPopupManager End****************/

/* SHOULD PUT THIS LOGIC AT THE END OF THIS DOCUMENT, Otherwise, it won't work for some case: e.g. copyfromfuncwhensubmit */
/* Form Field Compress */
$(function () {
    // We shall use the delegate, otherwise, some fields have copyFromFuncWhenSubmit haven't been executed.
    $(document).delegate("form.largeformfieldsform", "submit", function () {
        var $form = $(this);
        if ($form.valid()) {
            var formFields = [];
            $form.find("input:not([type='submit'],[type='button'],[type='file'],[type='reset']),select,textarea").each(function () {
                if (!$(this).hasClass("noncompressfield")) {
                    if ("checkbox" != $(this).attr("type") || $(this).prop("checked")) {
                        formFields.push([$(this).attr("name") + "", $(this).val()]);
                        $(this).attr("disabled", "disabled");
                    }
                }
            });
            // avoid the event has been registered twice.
            var largefieldHidden = $form.find("input[type='hidden'][name='____combinedcompressfields']");
            if (largefieldHidden.length <= 0) {
                largefieldHidden = $("<input type='hidden' name='____combinedcompressfields'/>");
                $form.append(largefieldHidden);
            }
            var compressFields = $.compressFormFieldArray(formFields);

            largefieldHidden.val(JSON.stringify(compressFields));
        }
    });
});

(function ($) {
    if ($.validator) {
        $.validator.methods.date = function (value, element) {
            if (value != null && value != "") {
                var matches = value.match(/[aApP]\.[mM]\.$/);
                if (matches != null) {
                    value = value.replace(matches[0], matches[0].replace(/\./g, ''));
                }
            }

            return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
        };
    }
})(jQuery);
/* SHOULD PUT THIS LOGIC AT THE END OF THIS DOCUMENT */
;
/// <reference path="../Resources/en-us/custom.js" />

(function ($) {
    function asyncUploadManager(target, options) {
        // should be form.
        if (!$(target).is("form"))
            return;

        this._options = $.extend(this._options, options);
        this._target = $(target);
        this._init();
    }
    asyncUploadManager.prototype = {
        _options: {
            uploadUrl: "/AsyncUpload.axd",
            progressUrl: "/UploadProgress.axd",
            cancelUrl: "/UploadProgress.axd?cancel=true",
            fileSelector: "input[type='file']",
            identifierAttr: "uploadid",
            asyncSubmitFormCss: "async_submit_form",
            uploadFileHiddenInputSuffix: "_upload_hidden", // or function(file,index){}
            getProgressInterval: 500,
            uploadAllFilesOneTime: false,
            popupProgressBarInTopWindow: false,
            redirectIframeID: null,
            redirectIframeDialogOptions:{},
            autoSubmitAfterSelected: false,
            allowAlwaysUpload: false
        },
        _target: null,
        _dialog: null,
        _dialogContent: null,
        _dialogShown: false,
        _cancel: false,
        _init: function () {            
            var $this = this;
            $this._cancel = false;
            if ($this._options.uploadUrl.indexOf("?") < 0) {
                $this._options.uploadUrl = $this._options.uploadUrl + "?1=1";
            }
            if ($this._dialogContent == null) {
                $this._dialogContent = $this._prepareProgressDialog();
            }
            if ($this._options.autoSubmitAfterSelected) {
                // >= IE 9
                var ie = $this.ie();
                if(ie == false || ie>=9){
                    $this._target.delegate("input[type='file']", "change", function () {
                        $this._target.submit();
                    });
                }
                else {
                    // if the file is changed, we need invoke this event in some other place.
                    $this._target.find("input[type='file']").change(function () {
                        $this._target.submit();
                    });
                }
            }
            $this._target.submit(function () {                
                if ($this._options.allowAlwaysUpload) {
                    $(this).data("file_uploaded", false);
                }
                if ($(this).data("file_uploaded") == true) {
                    return true;
                }
                              
                $this._prepareToSubmitFileHiddens();
                
                // if has jQuery Validation
                if ($(this).validate) {
                    if (!$(this).validate().form()) {
                        return false;
                    }
                }

                var form = $(this);
                var allFileInputs = form.find($this._options.fileSelector);
                var hasUploadedFile = false;
                allFileInputs.each(function (i, n) {
                    hasUploadedFile = hasUploadedFile || $(n).val() != "";
                });
                if (!hasUploadedFile) {
                    return true;
                }

                $this._cancel = false;
                $this._clearAll();
                var needUploadFileCount = 0;
                allFileInputs.each(function (i, n) {
                    var fileInput = $(n);
                    var uploadid = fileInput.attr($this._options.identifierAttr);
                    if (fileInput.val() != "") {
                        needUploadFileCount++;
                        fileInput.replaceWith(fileInput.clone());
                        var newForm = $('<form enctype="multipart/form-data" action="' + $this._options.uploadUrl + '&identifier=' + uploadid + '" method="post" style="display:none" class="' + $this._options.asyncSubmitFormCss + '"></form>');

                        var fullName = fileInput.val();
                        var fileNameFirstIndex = fullName.lastIndexOf("\\") + 1;
                        var fileName = fullName.substr(fileNameFirstIndex);
                        newForm.attr({ id: uploadid + "_form", target: uploadid + "_iframe", filename: fileName });
                        newForm.append(fileInput);
                        var newIframe = $('<iframe style="display:none"/>').attr({ id: uploadid + "_iframe", name: uploadid + "_iframe" });
                        $("body").append(newForm).append(newIframe);
                    }
                });

                $("form." + $this._options.asyncSubmitFormCss).each(function () {
                    var toUploadFile = $(this).find($this._options.fileSelector);
                    var uploadid = toUploadFile.attr($this._options.identifierAttr);
                    $this._updateFileList(
                        {
                            UploadID: uploadid,
                            StatusText: Vision.Resources.AsyncUpload_DefaultStatusText,
                            Percent: 0,
                            FileName: $(this).attr("filename"),
                            SizeStr: Vision.Resources.AsyncUpload_DefaultSizeStr,
                            IsValid: true
                        });
                });

                var succeedIDs = [];
                var ajaxSubmitUploadForm = function (currentForm) {
                    var toUploadFile = $(currentForm).find($this._options.fileSelector);
                    var uploadid = toUploadFile.attr($this._options.identifierAttr);
                    $this._updateFileList(
                        {
                            UploadID: uploadid,
                            StatusText: Vision.Resources.AsyncUpload_DefaultStatusText,
                            Percent: 0,
                            FileName: $(currentForm).attr("filename"),
                            SizeStr: Vision.Resources.AsyncUpload_DefaultSizeStr,
                            IsValid: true
                        });

                    currentForm.submit();
                    var count = 0;
                    var interval = setInterval(function () {
                        if ($this._cancel == true) {
                            clearInterval(interval);
                            $this._clearAll();
                            return;
                        }
                        // don't invoke extend session time out.
                        $.ajax(
                                $this._options.progressUrl + "?t=" + (count++),
                                {
                                    data: { id: uploadid },
                                    success: function (uploadFile) {
                                        if (uploadFile != false) {
                                            $this._updateFileList(uploadFile);
                                            if (uploadFile.Status >= 3) {
                                                if ($.inArray(uploadFile.UploadID, succeedIDs) < 0) {
                                                    succeedIDs.push(uploadFile.UploadID);
                                                }
                                                // upload successfully.
                                                //if (uploadFile.Status == 3) {
                                                if (succeedIDs.length >= needUploadFileCount) {
                                                    // all files have been uploaded successfully.
                                                    setTimeout(function () {
                                                        //console.log(succeedIDs);
                                                        $this._dialog.close(true);
                                                    }, 2000);
                                                }
                                                //}
                                                // upload finished.
                                                clearInterval(interval);
                                                $(currentForm).remove();
                                                $("iframe[name='" + $(currentForm).attr("target") + "']").remove();

                                                if (!$this._options.uploadAllFilesOneTime) {
                                                    proccessNextAjaxUploadForm();
                                                }
                                            }
                                        }
                                    },
                                    type: 'get',
                                    dataType: 'json'
                                });
                    }, $this._options.getProgressInterval);
                }

                var proccessNextAjaxUploadForm = function () {
                    if ($("form." + $this._options.asyncSubmitFormCss).length > 0) {
                        var _currentForm = $("form." + $this._options.asyncSubmitFormCss)[0];
                        ajaxSubmitUploadForm(_currentForm);
                    }
                }
                
                if ($this._options.uploadAllFilesOneTime) {
                    $("form." + $this._options.asyncSubmitFormCss).each(function () {
                        ajaxSubmitUploadForm(this);
                    });
                } else {
                    proccessNextAjaxUploadForm();
                }

                //$("form." + $this._options.asyncSubmitFormCss).each(function (i, n) {
                //    ajaxSubmitUploadForm(n);
                //});

                if (needUploadFileCount > 0) {
                    return false;
                }
            });
        },
        _prepareProgressDialog: function () {
            var $this = this;
            if ($this._options.popupProgressBarInTopWindow == true) {
                $ = (window.top || window).$;
            }
            var dialogContent = $("<div class='progress_container' style='display:none'></div>");
            var progressDiv = $("<div class='progress_div'/>");
            dialogContent.append(progressDiv);
            var progressTable = $('<table class="progress_table"><thead><tr><th class="name_td">' + Vision.Resources.AsyncUpload_ProgressBar_ColumnTitles_Name + '</th><th class="size_td">' + Vision.Resources.AsyncUpload_ProgressBar_ColumnTitles_Size + '</th><th class="progress_td">' + Vision.Resources.AsyncUpload_ProgressBar_ColumnTitles_Progress + '</th></tr></thead><tbody></tbody></table>');
            progressDiv.append(progressTable);
            dialogContent.append('<div class="progress_notice">' + Vision.Resources.AsyncUpload_ProgressBar_Notice + '</div>');
            return dialogContent;
        },
        _prepareToSubmitFileHiddens: function () {
            var $this = this;
            var uploadFileHiddenInputSuffixType = typeof $this._options.uploadFileHiddenInputSuffix;
            if (uploadFileHiddenInputSuffixType == "string") {
                uploadFileHiddenInputSuffixFunc = function (file, index) {
                    return $this._options.uploadFileHiddenInputSuffix;
                }
            } else if (uploadFileHiddenInputSuffixType == "function") {
                uploadFileHiddenInputSuffixFunc = $this._options.uploadFileHiddenInputSuffix;
            } else {
                uploadFileHiddenInputSuffixFunc = function (file, index) {
                    return "_upload_hidden";
                }
            }

            var allFileInputs = $this._target.find($this._options.fileSelector);
            allFileInputs.each(function (i, n) {
                var hiddenInputSuffix = uploadFileHiddenInputSuffixFunc(n, i)

                var fileInput = $(n);
                fileInput.siblings(".async_upload_cus_hiddens").remove();
                var fileInputName = fileInput.attr("name");
                //uploadIDHidden
                var uploadIDHidden = $("<input class='async_upload_cus_hiddens' type='hidden'/>");
                uploadIDHidden.val(fileInput.attr($this._options.identifierAttr));
                uploadIDHidden.attr("name", fileInputName + hiddenInputSuffix);
                fileInput.after(uploadIDHidden);
                //orignalNameHidden
                var orignalNameHidden = $("<input class='async_upload_cus_hiddens' type='hidden'/>");
                orignalNameHidden.attr("name", fileInputName + hiddenInputSuffix + ".UploadedOriginalNameHidden");
                orignalNameHidden.val($(fileInput).prev("input.file_input_cus").val());
                fileInput.after(orignalNameHidden);
                //fileChangedHidden
                var fileChangedHidden = $("<input class='async_upload_cus_hiddens' type='hidden'/>");
                fileChangedHidden.attr("name", fileInputName + hiddenInputSuffix + ".UploadedFileChangedHidden");
                fileChangedHidden.val($(fileInput).val().length > 0 ? "true" : "false");
                fileInput.after(fileChangedHidden);
            });
        },
        _showProgressDialog: function () {
            var $this = this;
            if (!$this._dialogShown && !$this._cancel) {
                
                var $dialogWindow = window;
                if ($this._options.popupProgressBarInTopWindow == true) {
                    $dialogWindow = window.top || window;
                }

                // show dialog
                var progressDialog = $dialogWindow.$.viClientDialog({
                    id: "progress_dialog",
                    title: Vision.Resources.AsyncUpload_ProgressBar_Titles_Uploading,
                    //width: 480,
                    actions: [],
                    html: $this._dialogContent,
                    useFrame: false,
                    onClosed: function (data) {
                        // handle old file inputs
                        var oldFileInputs = $this._target.find($this._options.fileSelector);
                        oldFileInputs.each(function (i, n) {
                            var newFileInput = $("<input type='file'/>");
                            newFileInput.attr(
                                {
                                    "name": $(n).attr("name"),
                                    "style": $(n).attr("style"),
                                    "class": $(n).attr("class"),
                                    "multiple": $(n).attr("multiple"),
                                    "accept": $(n).attr("accept")
                                }).attr($this._options.identifierAttr, $(n).attr($this._options.identifierAttr));
                            $(n).hide();
                            $(n).parent().append(newFileInput);
                            //$(n).replaceWith(newFileInput);

                            if ($this._cancel) {
                                // Cancel Upload in Ajax Post.
                                $.ajax(
                                $this._options.cancelUrl,
                                {
                                    data: { id: $(n).attr($this._options.identifierAttr) },
                                    success: function (result) {
                                    },

                                    type: 'get'
                                });
                            }
                        });
                        oldFileInputs.each(function (i, n) {
                            $(n).remove();
                        });

                        $this._dialogShown = false;

                        var succeed = typeof data != 'undefined' && data == true;
                        if (succeed) {
                            // if has jQuery Validation
                            $this._target.find($this._options.fileSelector).each(function () {
                                if ($(this).rules) {
                                    $(this).rules("remove");
                                }
                            });

                            // popup iframe lightbox
                            if ($this._options.redirectIframeID) {
                                var redirectDialogOptions = $.extend({}, $this._options.redirectIframeDialogOptions, {
                                    id: $this._options.redirectIframeID,
                                    html: $this._dialogContent,
                                    useFrame: true,
                                    redirectFrame: true
                                });
                                var redirectDialog = $dialogWindow.$.viClientDialog(redirectDialogOptions);
                                setTimeout(function () {
                                    $this._target.data("file_uploaded", true);
                                    $this._target.submit();
                                }, 200);
                                redirectDialog.open();
                            }
                            else {
                                $this._target.data("file_uploaded", true);
                                $this._target.submit();
                            }
                        }
                        else {
                            $this._cancel = !succeed;
                            //window.location = window.location.href;                       
                            $this._clearAll();
                        }
                    }
                });
                $this._dialogContent.show();
                progressDialog.open();

                $this._dialog = progressDialog;
                $this._dialogShown = true;
            }
        },
        _clearAll: function () {
            var $this = this;
            // clear iframe
            $("form." + $this._options.asyncSubmitFormCss).each(function (i, n) {
                var uploadid = $(this).find($this._options.fileSelector).attr($this._options.identifierAttr);
                $(n).remove();
                $("iframe[name='" + $(n).attr("target") + "']").remove();
            });
            // clear dialog progress.
            $this._dialogContent.find("div.progress_div table tbody").html("");
        },
        _createProgressBar: function (options) {
            var css = "progress";
            var status = options.status || "";
            if (status == "Error") {
                css = "invalid_file";
            }
            var pecentage = options.pecentage || 0.00;
            var width = options.width || 100;
            var pecentageStr = Math.round(pecentage * 100, 4) / 100 + "%";
            var progress = $("<span/>").addClass(css).width(pecentageStr).text(pecentageStr);
            var container = $("<div/>").addClass("progress_total");
            return $(container).append(progress);
        },
        _updateFileList: function (uploadFile) {
            if (typeof uploadFile == 'undefined' || uploadFile.UploadID == null) {
                return;
            }
            var $this = this;
            $this._showProgressDialog();

            var progressTableBody = $this._dialogContent.find(".progress_table tbody");

            var status = uploadFile.StatusText;
            var pecentage = uploadFile.Percent == NaN ? 0 : uploadFile.Percent;
            var progress = $this._createProgressBar({ pecentage: pecentage, status: status });

            var progressTd = progressTableBody.find("td[uploadid='" + uploadFile.UploadID + "']");
            // should check the file is valid.
            if (progressTd.length <= 0) {
                progressTd = $("<td uploadid='" + uploadFile.UploadID + "'/>");
                progressTd.addClass("progress_td");
                if (uploadFile.IsValid) {
                    progressTd.append($(progress));
                }
                else {
                    var message = uploadFile.Message;
                    if (!message) {
                        message = uploadFile.StatusText;
                    }
                    var finalErrorMsg = message.length > 18 ? message.substr(0, 15) + "..." : message;

                    var errorSpan = $("<span class='invalid_file'/>").html(finalErrorMsg).attr("title", uploadFile.Message);
                    var errorContainer = $("<div class='progress_total'/>");
                    errorContainer.append(errorSpan);
                    progressTd.append(errorContainer);
                }

                var fileName = uploadFile.FileName;
                var finalFileName = fileName;
                if (fileName.length > 20) {
                    finalFileName = fileName.substr(0, 3) + "..." + fileName.substr(fileName.length - 14, 14);
                }
                var fileNameSpan = $("<span title='" + fileName + "'/>").html(finalFileName);
                var nametd = $("<td/>").append(fileNameSpan).addClass("name_td");
                var sizetd = $("<td/>").append(uploadFile.SizeStr).addClass("size_td");
                var row = $("<tr uploadid='" + uploadFile.UploadID + "'/>").append(nametd).append(sizetd).append(progressTd).addClass("show-tooltip");
                progressTableBody.append(row);
            } else {
                if (uploadFile.IsValid) {
                    progressTd.find("div.progress_total").replaceWith(progress);
                    var row = $(progressTableBody).find("tr[uploadid='" + uploadFile.UploadID + "']");
                    row.find("td.size_td").html(uploadFile.SizeStr);
                }
                else {
                    var message = uploadFile.Message;
                    if (!message) {
                        message = uploadFile.StatusText;
                    }
                    var finalErrorMsg = message.length > 18 ? message.substr(0, 15) + "..." : message;
                    var errorSpan = $("<span class='invalid_file'/>").html(finalErrorMsg).attr("title", uploadFile.Message);
                    var errorContainer = $("<div class='progress_total'/>");
                    errorContainer.append(errorSpan);
                    progressTd.html(errorContainer);

                    var row = $(progressTableBody).find("tr[uploadid='" + uploadFile.UploadID + "']");
                    row.find("td.size_td").html(uploadFile.SizeStr);

                }
            }
        },
        ie:function(){
            var userAgent = navigator.userAgent.toLowerCase();
            return (userAgent.indexOf('msie') != -1) ? parseInt(userAgent.split('msie')[1]) : false;
        }
    };

    // Only support 1 HTML5 file upload in each form.
    function asyncHTML5UploadManager(target, options) {
        // should be form.
        if (!$(target).is("form"))
            return;

        this._options = $.extend(this._options, options);
        this._target = $(target);
        this._init();
    }
    asyncHTML5UploadManager.isSupport = function () {
        try
        {
            var result = window.FormData && ("upload" in ($.ajaxSettings.xhr())) && window.File && window.FileList && window.FileReader;
            return result != null && result != false;
        }
        catch (e)
        {
            return false;
        }
    }
    asyncHTML5UploadManager.prototype = {
        _options: {
            uploadUrl: "/AsyncUpload.axd",
            progressUrl: "/UploadProgress.axd",
            cancelUrl: "/UploadProgress.axd?cancel=true",
            fileSelector: "input[type='file']",
            identifierAttr: "uploadid",
            asyncSubmitFormCss: "async_submit_form",
            uploadFileHiddenInputSuffix: "_upload_hidden", // or function(file,index){}
            getProgressInterval: 500,
            uploadAllFilesOneTime: false,
            popupProgressBarInTopWindow: false,
            redirectIframeDialogOptions: {},
            redirectIframeID: null,
            autoSubmitAfterSelected: false,
            allowAlwaysUpload:false,
            maxMultipleUploadImageCount: null,
            maxAllowedImageCountHintFormat:null,
            maxFileSizeHintFormat : null,
            useDataInsteadProp: false,
            allowAlertWhenError: null
        },
        _target: null,
        _dialog: null,
        _dialogContent: null,
        _dialogShown: false,
        _cancel: false,        
        _filesInfo: { files: [], InvalidFileIDs:[], TotalInvalidFilesSelected: 0, TotalUploadedFiles: 0, TotalValidFilesSelected: 0, BytesTotalLength: 0, BytesUploadedLength: 0 },
        _init: function () {
            var $this = this;
            $this._cancel = false;            
            if ($this._options.uploadUrl.indexOf("?") < 0) {
                $this._options.uploadUrl = $this._options.uploadUrl + "?1=1";
            } 

            if ($this._dialogContent == null) {
                $this._dialogContent = $this._prepareProgressDialog();
            }
            if ($this._options.autoSubmitAfterSelected) {
                $this._target.delegate("input[type='file']","change", function () {                   
                    if ($this._options.maxMultipleUploadImageCount) {
                        var uploadedFiles = $(this)[0].files;                        
                        if (uploadedFiles && uploadedFiles.length > $this._options.maxMultipleUploadImageCount) {
                            alert($this._options.maxAllowedImageCountHintFormat);
                            //Reset for calling again
                            $this._target.find("input[type='file']").val('');
                            return false;
                        }
                    }
                    $this._target.submit();
                });
            }
            $this._target.submit(function () {
                $this._filesInfo = { files: [], InvalidFileIDs: [], TotalInvalidFilesSelected: 0, TotalUploadedFiles: 0, TotalValidFilesSelected: 0, BytesTotalLength: 0, BytesUploadedLength: 0 };
                if ($this._options.allowAlwaysUpload) {
                    $(this).data("file_uploaded", false);
                }
                if ($(this).data("file_uploaded") == true) {
                    return true;
                }
                
                // if has jQuery Validation
                if ($(this).validate) {
                    if (!$(this).validate().form()) {
                        if ($this._options.allowAlertWhenError && $(this).validate().errorList.length > 0) {                            
                            alert($(this).validate().errorList[0].message);
                            //Reset for calling again                            
                            if ($.isIEBrowser()) {                                
                                $this._target.find("input[type='file']").replaceWith($this._target.find("input[type='file']").clone(true));
                            }
                            else {
                                $this._target.find("input[type='file']").val('');
                            }
                        }
                        return false;
                    }
                }

                var form = $(this);
                var allFileInputs = form.find($this._options.fileSelector);
                var hasUploadedFile = $this._options.useDataInsteadProp || false;
                allFileInputs.each(function (i, n) {
                    hasUploadedFile = hasUploadedFile || $(n).val() != "";
                });
                if (!hasUploadedFile) {
                    return true;
                }

                var html5Files = [];
                if (!$this._options.useDataInsteadProp) {
                    $(allFileInputs).each(function (j,m) {
                        var uploadid = $(m).attr($this._options.identifierAttr);
                        $(m.files).each(function (i,n) {
                            n.__identifier = uploadid + "_" + i;
                            n.__fileInput = m;
                            n.__fileInputID = uploadid;
                            html5Files.push(n);
                        });
                    });
                }
                else {
                    $(allFileInputs).each(function (j, m) {
                        var uploadid = $(m).attr($this._options.identifierAttr);
                        var files = $(m).data("files") || [];
                        $(files).each(function (i, n) {
                            n.__identifier = uploadid + "_" + i;
                            n.__fileInput = m;
                            n.__fileInputID = uploadid;
                            html5Files.push(n);    
                        });
                    });
                }
                
                if ($this._options.maxMultipleUploadImageCount) {
                    if (html5Files.length > $this._options.maxMultipleUploadImageCount) {
                        alert($this._options.maxAllowedImageCountHintFormat);
                        return false;
                    }                    
                }

                $this._filesInfo._files = html5Files;
                $this._filesInfo.TotalValidFilesSelected = html5Files.length;
                $this._prepareToSubmitFileHiddens(html5Files);                

                $this._cancel = false;
                $this._clearAll();
                var needUploadFileCount = html5Files.length;

                var succeedIDs = [];

                $(html5Files).each(function () {
                    var file = this;

                    $this._filesInfo.BytesTotalLength += file.size;                    

                    var xhr = new XMLHttpRequest();
                    xhr.upload.addEventListener("progress", function (e) {                        
                    }, false);
                    xhr.onreadystatechange = function (e) {
                    }
                    xhr.open("POST", $this._options.uploadUrl + "&identifier=" + file.__identifier, true);
                    //xhr.setRequestHeader("Content-Type", "multipart/form-data");
                    var formData = new FormData();
                    formData.append(file.__identifier, file);
                    xhr.send(formData);

                    $this._updateFileList(
                        {
                            UploadID: file.__identifier,
                            StatusText: Vision.Resources.AsyncUpload_DefaultStatusText,
                            Percent: 0,
                            FileName: file.name,
                            SizeStr: Vision.Resources.AsyncUpload_DefaultSizeStr,
                            IsValid: true
                        });
                    var count = 0;
                    var interval = setInterval(function () {
                        if ($this._cancel == true) {
                            clearInterval(interval);
                            $this._clearAll();
                            return;
                        }
                        // don't invoke extend session time out.
                        $.ajax(
                                $this._options.progressUrl + "?t=" + (count++),
                                {
                                    data: { id: file.__identifier },
                                    success: function (uploadFile) {
                                        if (uploadFile != false) {
                                            //use file.size for avoid confusing because
                                            if(uploadFile.UploadedLength > file.size)
                                                file.__uploadedLength = file.size;
                                            else
                                                file.__uploadedLength = uploadFile.UploadedLength;
                                                
                                            var totalLength = 0;
                                            $(html5Files).each(function(){
                                                totalLength += (this.__uploadedLength||0);
                                            });
                                            $this._filesInfo.BytesUploadedLength = totalLength;
                                            if (uploadFile.Status > 3 && $this._filesInfo.InvalidFileIDs.indexOf(uploadFile.UploadID) == -1) {
                                                $this._filesInfo.InvalidFileIDs.push(uploadFile.UploadID);
                                                $this._filesInfo.TotalInvalidFilesSelected++;
                                            }

                                            if (uploadFile.Status >= 3) {
                                                if ($.inArray(uploadFile.UploadID, succeedIDs) < 0) {
                                                    succeedIDs.push(uploadFile.UploadID);
                                                    if (uploadFile.Status == 3) {
                                                        $this._filesInfo.TotalUploadedFiles++;
                                                    }
                                                }
                                                // upload successfully.
                                                //if (uploadFile.Status == 3) {
                                                if (succeedIDs.length >= needUploadFileCount) {
                                                    // all files have been uploaded successfully.
                                                    setTimeout(function () {
                                                        //console.log(succeedIDs);
                                                        $this._dialog.close(true);
                                                    }, 2000);
                                                }
                                                //}
                                                // upload finished.
                                                clearInterval(interval);
                                            }
                                            $this._updateFileList(uploadFile);
                                        }
                                    },
                                    type: 'get',
                                    dataType: 'json'
                                });
                    }, $this._options.getProgressInterval);
                });

                if (needUploadFileCount > 0) {
                    return false;
                }
            });
        },
        _prepareProgressDialog: function () {
            var $this = this;
            if ($this._options.popupProgressBarInTopWindow == true) {
                $ = (window.top || window).$;
            }
            var dialogContent = $("<div class='progress_container' style='display:none'></div>");
            var progressDiv = $("<div class='progress_div'/>");
            dialogContent.append(progressDiv);
            var progressTable = $('<table class="progress_table"><thead><tr><th class="name_td">' + Vision.Resources.AsyncUpload_ProgressBar_ColumnTitles_Name + '</th><th class="size_td">' + Vision.Resources.AsyncUpload_ProgressBar_ColumnTitles_Size + '</th><th class="progress_td">' + Vision.Resources.AsyncUpload_ProgressBar_ColumnTitles_Progress + '</th></tr></thead><tbody></tbody></table>');
            progressDiv.append(progressTable);
            dialogContent.append(
                  '<div class="progress_total_info">'
                + '<span id="TotalInvalidSelectedCount" class="invalid">0 invalid files</span>'
                + '<br />'
                + '<span id="TotalUploadedSize">0 KB</span>&nbsp;/&nbsp;'
                + '<span id="TotalSelectedSize">0 KB</span>'
                + '<br />'
                + '<span id="TotalUploadedCount">0 files uploaded</span>&nbsp;/&nbsp;'
                + '<span id="TotalValidSelectedCount">0 valid files</span>'
                + '<br />'
                + '<div id="TotalPercentage"></div>'
                + '</div>');
            dialogContent.append('<div class="progress_notice">' + Vision.Resources.AsyncUpload_ProgressBar_Notice + '</div>');

            return dialogContent;
        },
        _prepareToSubmitFileHiddens: function (files) {
            // always only 1 file input element.
            var $this = this;
            
            var uploadFileHiddenInputSuffixFunc = null;
            var uploadFileHiddenInputSuffixType = typeof $this._options.uploadFileHiddenInputSuffix ;
            if (uploadFileHiddenInputSuffixType == "string") {
                uploadFileHiddenInputSuffixFunc = function (file, index) {
                    return $this._options.uploadFileHiddenInputSuffix;
                }
            } else if (uploadFileHiddenInputSuffixType == "function") {
                uploadFileHiddenInputSuffixFunc = $this._options.uploadFileHiddenInputSuffix;
            } else {
                uploadFileHiddenInputSuffixFunc = function (file, index) {
                    return "_succeeds[" + i + "]._hidden";
                }
            }
            var removedCusHiddenFileInputs = [];
            $(files).each(function (i, n) {
                var hiddenInputSuffix = uploadFileHiddenInputSuffixFunc(n.__fileInput, i)
                var fileInput = $(n.__fileInput);
                if (removedCusHiddenFileInputs.indexOf(n.__fileInputID) < 0) {
                    fileInput.siblings(".async_upload_cus_hiddens").remove();
                    removedCusHiddenFileInputs.push(n.__fileInputID);
                }

                var fileInputName = fileInput.attr("name");
                //uploadIDHidden
                var uploadIDHidden = $("<input class='async_upload_cus_hiddens' type='hidden'/>");
                uploadIDHidden.val(n.__identifier);
                uploadIDHidden.attr("name", fileInputName + hiddenInputSuffix);
                fileInput.after(uploadIDHidden);
                //orignalNameHidden
                var orignalNameHidden = $("<input class='async_upload_cus_hiddens' type='hidden'/>");
                orignalNameHidden.attr("name", fileInputName + hiddenInputSuffix + ".UploadedOriginalNameHidden");
                orignalNameHidden.val(n.name);
                fileInput.after(orignalNameHidden);
                //fileChangedHidden
                var fileChangedHidden = $("<input class='async_upload_cus_hiddens' type='hidden'/>");
                fileChangedHidden.attr("name", fileInputName + hiddenInputSuffix + ".UploadedFileChangedHidden");
                fileChangedHidden.val($(fileInput).val().length > 0 ? "true" : "false");
                fileInput.after(fileChangedHidden);
            });
        },
        _showProgressDialog: function () {
            var $this = this;
            if (!$this._dialogShown && !$this._cancel) {

                var $dialogWindow = window;
                if ($this._options.popupProgressBarInTopWindow == true) {
                    $dialogWindow = window.top || window;
                }

                // show dialog
                var progressDialog = $dialogWindow.$.viClientDialog({
                    id: "progress_dialog",
                    title: Vision.Resources.AsyncUpload_ProgressBar_Titles_Uploading,
                    //width: 480,
                    actions: [],
                    html: $this._dialogContent,
                    useFrame: false,
                    onClosed: function (data) {
                        // handle old file inputs
                        var oldFileInputs = $this._target.find($this._options.fileSelector);
                        oldFileInputs.each(function (i, n) {
                            var newFileInput = $("<input type='file'/>");
                            newFileInput.attr(
                                {
                                    "name": $(n).attr("name"),
                                    "style": $(n).attr("style"),
                                    "class": $(n).attr("class"),
                                    "multiple": $(n).attr("multiple"),
                                    "accept": $(n).attr("accept")
                                }).attr($this._options.identifierAttr, $(n).attr($this._options.identifierAttr));
                            $(n).hide();
                            $(n).parent().append(newFileInput);
                            //$(n).replaceWith(newFileInput);

                            if ($this._cancel) {
                                // Cancel Upload in Ajax Post.
                                $.ajax(
                                $this._options.cancelUrl,
                                {
                                    data: { id: $(n).attr($this._options.identifierAttr) },
                                    success: function (result) {
                                    },

                                    type: 'get'
                                });
                            }
                        });
                        oldFileInputs.each(function (i, n) {
                            $(n).remove();
                        });

                        $this._dialogShown = false;

                        var succeed = typeof data != 'undefined' && data == true;
                        if (succeed) {
                            // if has jQuery Validation
                            $this._target.find($this._options.fileSelector).each(function () {
                                if ($(this).rules) {
                                    $(this).rules("remove");
                                }
                            });

                            // popup iframe lightbox
                            if ($this._options.redirectIframeID) {
                                var redirectDialogOptions = $.extend({}, $this._options.redirectIframeDialogOptions, {
                                    id: $this._options.redirectIframeID,
                                    html: $this._dialogContent,
                                    useFrame: true,
                                    redirectFrame: true
                                });
                                var redirectDialog = $dialogWindow.$.viClientDialog(redirectDialogOptions);

                                setTimeout(function () {
                                    $this._target.data("file_uploaded", true);
                                    $this._target.submit();
                                }, 200);
                                redirectDialog.open();
                            }
                            else {
                                $this._target.data("file_uploaded", true);
                                $this._target.submit();
                            }
                        }
                        else {
                            $this._cancel = !succeed;
                            //window.location = window.location.href;                       
                            $this._clearAll();
                        }
                    }
                });
                $this._dialogContent.show();
                progressDialog.open();

                $this._dialog = progressDialog;
                $this._dialogShown = true;
            }
        },
        _clearAll: function () {
            var $this = this;
            // clear dialog progress.
            $this._dialogContent.find("div.progress_div table tbody").html("");
        },
        _createProgressBar: function (options) {
            var css = "progress";
            var status = options.status || "";
            if (status == "Error") {
                css = "invalid_file";
            }
            var pecentage = options.pecentage || 0.00;
            pecentage = pecentage > 100 ? 100 : pecentage;
            var width = options.width || 100;
            var pecentageStr = Math.round(pecentage * 100, 4) / 100 + "%";
            var progress = $("<span/>").addClass(css).width(pecentageStr).text(pecentageStr);
            var container = $("<div/>").addClass("progress_total");
            return $(container).append(progress);
        },
        _updateFileList: function (uploadFile) {
            if (typeof uploadFile == 'undefined' || uploadFile.UploadID == null) {
                return;
            }
            var $this = this;
            $this._showProgressDialog();
            
            var progressTableBody = $this._dialogContent.find(".progress_table tbody");

            var status = uploadFile.StatusText;
            var pecentage = uploadFile.Percent == NaN ? 0 : uploadFile.Percent;
            var progress = $this._createProgressBar({ pecentage: pecentage, status: status });

            var progressTd = progressTableBody.find("td[uploadid='" + uploadFile.UploadID + "']");
            // should check the file is valid.
            if (progressTd.length <= 0) {
                progressTd = $("<td uploadid='" + uploadFile.UploadID + "'/>");
                progressTd.addClass("progress_td");
                if (uploadFile.IsValid) {
                    progressTd.append($(progress));
                }
                else {
                    var message = uploadFile.Message;
                    if (!message) {
                        message = uploadFile.StatusText;
                    }
                    var finalErrorMsg = message.length > 18 ? message.substr(0, 15) + "..." : message;

                    var errorSpan = $("<span class='invalid_file'/>").html(finalErrorMsg).attr("title", uploadFile.Message);
                    var errorContainer = $("<div class='progress_total'/>");
                    errorContainer.append(errorSpan);
                    progressTd.append(errorContainer);
                }

                var fileName = uploadFile.FileName;
                var finalFileName = fileName;
                if (fileName.length > 20) {
                    finalFileName = fileName.substr(0, 3) + "..." + fileName.substr(fileName.length - 14, 14);
                }
                var fileNameSpan = $("<span title='" + fileName + "'/>").html(finalFileName);
                var nametd = $("<td/>").append(fileNameSpan).addClass("name_td");
                var sizetd = $("<td/>").append(uploadFile.SizeStr).addClass("size_td");
                var row = $("<tr uploadid='" + uploadFile.UploadID + "'/>").append(nametd).append(sizetd).append(progressTd).addClass("show-tooltip");
                progressTableBody.append(row);
            } else {
                if (uploadFile.IsValid) {
                    progressTd.find("div.progress_total").replaceWith(progress);
                    var row = $(progressTableBody).find("tr[uploadid='" + uploadFile.UploadID + "']");
                    row.find("td.size_td").html(uploadFile.SizeStr);
                }
                else {
                    var message = uploadFile.Message;
                    if (!message) {
                        message = uploadFile.StatusText;
                    }
                    var finalErrorMsg = message.length > 18 ? message.substr(0, 15) + "..." : message;
                    var errorSpan = $("<span class='invalid_file'/>").html(finalErrorMsg).attr("title", uploadFile.Message);
                    var errorContainer = $("<div class='progress_total'/>");
                    errorContainer.append(errorSpan);
                    progressTd.html(errorContainer);

                    var row = $(progressTableBody).find("tr[uploadid='" + uploadFile.UploadID + "']");
                    row.find("td.size_td").html(uploadFile.SizeStr);
                }
            }

            //Update the other statistics...
            $('#TotalInvalidSelectedCount').html($this._filesInfo.TotalInvalidFilesSelected + " invalid " + $this.formatFileDesc($this._filesInfo.TotalInvalidFilesSelected));
            $('#TotalUploadedCount').html($this._filesInfo.TotalUploadedFiles + " " + $this.formatFileDesc($this._filesInfo.TotalUploadedFiles) + " uploaded");
            $('#TotalValidSelectedCount').html($this._filesInfo.TotalValidFilesSelected + " valid " + $this.formatFileDesc($this._filesInfo.TotalValidFilesSelected));
            $('#TotalSelectedSize').html($this.formatFileSizeWithAutoSizeType($this._filesInfo.BytesTotalLength));
            $('#TotalUploadedSize').html($this.formatFileSizeWithAutoSizeType($this._filesInfo.BytesUploadedLength));
        },        
        formatFileDesc: function (count) {
            return (count > 1 || count == 0) ? "files" : "file";
        },
        formatFileSizeWithAutoSizeType: function (fileSize) {
            var Size1K = 1024;
            var Size1M = 1024 * 1024;
            var Size1G = 1024 * 1024 * 1024;
            if (fileSize < Size1K) {
                return fileSize + " B";
            }
            else if (fileSize < Size1M) {
                return Math.round(fileSize * 100 / Size1K) / 100 + " KB";
            }
            else if (fileSize < Size1G) {
                return Math.round(fileSize * 100 / Size1M) / 100 + " MB";
            }
            else {
                return Math.round(fileSize * 100 / Size1G) / 100 + " GB";
            }
        }
    };


    $.fn.extend({
        asyncUpload: function (options) {
            var $this = $(this);
            var _asyncUpload = new asyncUploadManager($this, options);
            $this.data('asyncUploadManager', _asyncUpload);
            return $this;
        },
        asyncUploadHtml5: function (options) {
            var $this = $(this);
            var _asyncUpload = asyncHTML5UploadManager.isSupport() ? new asyncHTML5UploadManager($this, options) : new asyncUploadManager($this, options);
            $this.data('asyncUploadHtml5Manager', _asyncUpload);
            return $this;
        }
    });

    $(function () {
        $("body").delegate("input.file_input_cus", "click", function () {
            $(this).next("input.file_input_ori").click();//Safari does not support "click" of file input, instead of using css "opacity"
        });
        $("body").delegate("input.file_input_cus", "focus", function () {
            $(this).blur();
        });
        $("body").delegate("input.file_input_ori", "change", function () {
            var fileName = $(this).val();
            var last = fileName.lastIndexOf("\\");
            if (last >= 0) {
                fileName = fileName.substring(last+1);
            }
            $(this).prev("input.file_input_cus").val(fileName);
        });
        $("body").delegate("input.file_input_cusbtn", "click", function () {
            $(this).prev("input.file_input_ori").click();//Safari does not support "click" of file input, instead of using css "opacity"
            $(this).blur();
        });
        $("body").delegate("a.cancel_upload_file", "click", function () {
            var input_item = $(this).siblings(".file_input_item");
            input_item.html(input_item.html());
            input_item.find(".file_input_cus").val('');
        });
    });

})(jQuery);;
/*!
 * jQuery resize event - v1.1 - 3/14/2010
 * http://benalman.com/projects/jquery-resize-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */

// Script: jQuery resize event
//
// *Version: 1.1, Last updated: 3/14/2010*
// 
// Project Home - http://benalman.com/projects/jquery-resize-plugin/
// GitHub       - http://github.com/cowboy/jquery-resize/
// Source       - http://github.com/cowboy/jquery-resize/raw/master/jquery.ba-resize.js
// (Minified)   - http://github.com/cowboy/jquery-resize/raw/master/jquery.ba-resize.min.js (1.0kb)
// 
// About: License
// 
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
// 
// About: Examples
// 
// This working example, complete with fully commented code, illustrates a few
// ways in which this plugin can be used.
// 
// resize event - http://benalman.com/code/projects/jquery-resize/examples/resize/
// 
// About: Support and Testing
// 
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
// 
// jQuery Versions - 1.3.2, 1.4.1, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-3.6, Safari 3-4, Chrome, Opera 9.6-10.1.
// Unit Tests      - http://benalman.com/code/projects/jquery-resize/unit/
// 
// About: Release History
// 
// 1.1 - (3/14/2010) Fixed a minor bug that was causing the event to trigger
//       immediately after bind in some circumstances. Also changed $.fn.data
//       to $.data to improve performance.
// 1.0 - (2/10/2010) Initial release

(function ($, window, undefined) {
    '$:nomunge'; // Used by YUI compressor.

    // A jQuery object containing all non-window elements to which the resize
    // event is bound.
    var elems = $([]),

      // Extend $.resize if it already exists, otherwise create it.
      jq_resize = $.resize = $.extend($.resize, {}),

      timeout_id,

      // Reused strings.
      str_setTimeout = 'setTimeout',
      str_resize = 'resize',
      str_data = str_resize + '-special-event',
      str_delay = 'delay',
      str_throttle = 'throttleWindow';

    // Property: jQuery.resize.delay
    // 
    // The numeric interval (in milliseconds) at which the resize event polling
    // loop executes. Defaults to 75.

    jq_resize[str_delay] = 75;

    // Property: jQuery.resize.throttleWindow
    // 
    // Throttle the native window object resize event to fire no more than once
    // every <jQuery.resize.delay> milliseconds. Defaults to true.
    // 
    // Because the window object has its own resize event, it doesn't need to be
    // provided by this plugin, and its execution can be left entirely up to the
    // browser. However, since certain browsers fire the resize event continuously
    // while others do not, enabling this will throttle the window resize event,
    // making event behavior consistent across all elements in all browsers.
    // 
    // While setting this property to false will disable window object resize
    // event throttling, please note that this property must be changed before any
    // window object resize event callbacks are bound.

    jq_resize[str_throttle] = true;

    // Event: resize event
    // 
    // Fired when an element's width or height changes. Because browsers only
    // provide this event for the window element, for other elements a polling
    // loop is initialized, running every <jQuery.resize.delay> milliseconds
    // to see if elements' dimensions have changed. You may bind with either
    // .resize( fn ) or .bind( "resize", fn ), and unbind with .unbind( "resize" ).
    // 
    // Usage:
    // 
    // > jQuery('selector').bind( 'resize', function(e) {
    // >   // element's width or height has changed!
    // >   ...
    // > });
    // 
    // Additional Notes:
    // 
    // * The polling loop is not created until at least one callback is actually
    //   bound to the 'resize' event, and this single polling loop is shared
    //   across all elements.
    // 
    // Double firing issue in jQuery 1.3.2:
    // 
    // While this plugin works in jQuery 1.3.2, if an element's event callbacks
    // are manually triggered via .trigger( 'resize' ) or .resize() those
    // callbacks may double-fire, due to limitations in the jQuery 1.3.2 special
    // events system. This is not an issue when using jQuery 1.4+.
    // 
    // > // While this works in jQuery 1.4+
    // > $(elem).css({ width: new_w, height: new_h }).resize();
    // > 
    // > // In jQuery 1.3.2, you need to do this:
    // > var elem = $(elem);
    // > elem.css({ width: new_w, height: new_h });
    // > elem.data( 'resize-special-event', { width: elem.width(), height: elem.height() } );
    // > elem.resize();

    $.event.special[str_resize] = {

        // Called only when the first 'resize' event callback is bound per element.
        setup: function () {
            // Since window has its own native 'resize' event, return false so that
            // jQuery will bind the event using DOM methods. Since only 'window'
            // objects have a .setTimeout method, this should be a sufficient test.
            // Unless, of course, we're throttling the 'resize' event for window.
            if (!jq_resize[str_throttle] && this[str_setTimeout]) { return false; }

            var elem = $(this);

            // Add this element to the list of internal elements to monitor.
            elems = elems.add(elem);

            // Initialize data store on the element.
            $.data(this, str_data, { w: elem.width(), h: elem.height() });

            // If this is the first element added, start the polling loop.
            if (elems.length === 1) {
                loopy();
            }
        },

        // Called only when the last 'resize' event callback is unbound per element.
        teardown: function () {
            // Since window has its own native 'resize' event, return false so that
            // jQuery will unbind the event using DOM methods. Since only 'window'
            // objects have a .setTimeout method, this should be a sufficient test.
            // Unless, of course, we're throttling the 'resize' event for window.
            if (!jq_resize[str_throttle] && this[str_setTimeout]) { return false; }

            var elem = $(this);

            // Remove this element from the list of internal elements to monitor.
            elems = elems.not(elem);

            // Remove any data stored on the element.
            elem.removeData(str_data);

            // If this is the last element removed, stop the polling loop.
            if (!elems.length) {
                clearTimeout(timeout_id);
            }
        },

        // Called every time a 'resize' event callback is bound per element (new in
        // jQuery 1.4).
        add: function (handleObj) {
            // Since window has its own native 'resize' event, return false so that
            // jQuery doesn't modify the event object. Unless, of course, we're
            // throttling the 'resize' event for window.
            if (!jq_resize[str_throttle] && this[str_setTimeout]) { return false; }

            var old_handler;

            // The new_handler function is executed every time the event is triggered.
            // This is used to update the internal element data store with the width
            // and height when the event is triggered manually, to avoid double-firing
            // of the event callback. See the "Double firing issue in jQuery 1.3.2"
            // comments above for more information.

            function new_handler(e, w, h) {
                var elem = $(this),
                  data = $.data(this, str_data);

                // If called from the polling loop, w and h will be passed in as
                // arguments. If called manually, via .trigger( 'resize' ) or .resize(),
                // those values will need to be computed.
                if (!data) {
                    data = $.data(this, str_data, { w: elem.width(), h: elem.height() })
                } else {
                    data.w = w !== undefined ? w : elem.width();
                    data.h = h !== undefined ? h : elem.height();
                }

                old_handler.apply(this, arguments);
            };

            // This may seem a little complicated, but it normalizes the special event
            // .add method between jQuery 1.4/1.4.1 and 1.4.2+
            if ($.isFunction(handleObj)) {
                // 1.4, 1.4.1
                old_handler = handleObj;
                return new_handler;
            } else {
                // 1.4.2+
                old_handler = handleObj.handler;
                handleObj.handler = new_handler;
            }
        }

    };

    function loopy() {

        // Start the polling loop, asynchronously.
        timeout_id = window[str_setTimeout](function () {

            // Iterate over all elements to which the 'resize' event is bound.
            elems.each(function () {
                var elem = $(this),
                  width = elem.width(),
                  height = elem.height(),
                  data = $.data(this, str_data);

                // If element size has changed since the last time, update the element
                // data store and trigger the 'resize' event.
                if (width !== data.w || height !== data.h) {
                    elem.trigger(str_resize, [data.w = width, data.h = height]);
                }

            });

            // Loop.
            loopy();

        }, jq_resize[str_delay]);

    };

})(jQuery, this);



; (function ($) {
    /**
    * Utility tool
    */
    $(function () {
        var body = document.body,
            div = body.appendChild(div = document.createElement("div"));

        $.extend(div.style, {
            minHeight: "100px",
            height: "auto",
            padding: 0,
            borderWidth: 0
        });

        $.support.minHeight = div.offsetHeight === 100;
        $.support.selectstart = "onselectstart" in div;

        // set display to none to avoid a layout bug in IE
        // http://dev.jquery.com/ticket/4014
        body.removeChild(div).style.display = "none";
    });

    $.extend($.fn, {
        disableSelection: function () {
            return this.bind(($.support.selectstart ? "selectstart" : "mousedown") +
                ".disableSelection", function (event) {
                    event.preventDefault();
                });
        },
        // check the element has scrollBar
        hasScrollbar: function () {
            var element = $(this).get(0);
            var hasScrollbar = false;
            hasScrollbar |= element.scrollHeight > element.clientHeight && $(element).css("overflow") == "auto";

            return hasScrollbar;
        },
    });
})(jQuery);

; (function ($, window, undefined) {

    if (document.compatMode === 'BackCompat') {
        throw new Error('viClientDialog: Document types require more than xhtml1.0');
    };

    var _singleton,
        _count = 0,
        _root = $(document.getElementsByTagName('html')[0]),
        _expando = 'viClientDialog' + +new Date,
        _isIE6 = window.VBArray && !window.XMLHttpRequest,
        _isMobile = 'createTouch' in document && !('onmousemove' in document)
            || /(iPhone|iPad|iPod)/i.test(navigator.userAgent),
        _isFixed = !_isIE6 && !_isMobile;


    var viClientDialog = function (config) {

        config = config || {};

        if (typeof config === 'string' || config.nodeType === 1) {
            config = { content: config, fixed: !_isMobile };
        };

        var api, defaults = viClientDialog.defaults;
        var elem = config.follow = this.nodeType === 1 && this || config.follow;

        // combine the dafault config
        for (var i in defaults) {
            if (config[i] === undefined) {
                config[i] = defaults[i];
            };
        };

        config.id = elem && elem[_expando + 'follow'] || config.id || _expando + _count;
        api = viClientDialog.list[config.id];

        if (api) {
            if (elem) {
                api.follow(elem)
            };
            api.zIndex();
            return api;
        };

        if (!_isFixed) {
            config.fixed = false;
        };

        viClientDialog.defaults.zIndex = config.zIndex;

        _count++;

        return viClientDialog.list[config.id] = _singleton ?
            _singleton.constructor(config) : new viClientDialog.fn.constructor(config);
    };

    viClientDialog.version = '1.0.0';

    viClientDialog.fn = viClientDialog.prototype = {

        /** @inner */
        constructor: function (config) {
            var dom;

            this.closed = false;
            this.config = config;
            this.dom = dom = this.dom || this._getDom();

            dom.wrap.addClass("v-viClientDialog"); // already add this class for identifying dialog.

            config.skin && dom.wrap.addClass(config.skin);

            dom.wrap.css('position', config.fixed ? 'fixed' : 'absolute');
            dom.content.css('padding', config.padding);
            if (!config.fixed)
                dom.title.css("cursor", "move");

            config.actions.length == 0 ? dom.close.hide() : dom.close.show();

            this.buildActionIcons();

            var width = config.width;
            if (typeof width == "number") {
                var contentPaddingMargin = dom.content.outerWidth() - dom.content.width();
                width += contentPaddingMargin/2;
            }
            
            if (config.isFullScreen) {                
                var winHeight = $(window).height();
                if (!dom.borderHeight) {
                    dom.borderHeight = $(dom.wrap).outerHeight();
                }                
                config.height = winHeight - dom.borderHeight; //for vi-main 
                $(dom.wrap).height(winHeight - dom.borderHeight / 2); //
            }

            this.title(config.title)
                .content(config.html)
                .size(width, config.height)
                .time(config.time);

            this.center();

            this.zIndex();
            config.lock && this.lock();

            this._addEvent();
            this[config.visible ? 'open' : 'hidden']();

            _singleton = null;

            if (!dom.wrap.data("viClientDialog")) {
                dom.wrap.data("viClientDialog", this);
            }

            if (config.url && !config.useFrame) {                
                //this.ajaxRequest(config, false);
            } else if (config.url && config.useFrame) {
                // to do
            } else {                
                config.initialize && config.initialize.call(this);
            }

            // add class 'overflow-y:auto' to 'vi-content'
            if (config.resize == true)
                dom.content.css("overflow-y", "auto");

            return this;
        },


        /**
        * set content
        * @param    {String, HTMLElement, Object}   content(optional)
        */
        content: function (message) {

            var prev, next, parent, display,
                that = this,
                $content = that.dom.content,
                content = $content[0];

            if (this._elemBack) {
                this._elemBack();
                delete this._elemBack;
            };

            if (message && ($.type(message) == "string" || (jQuery && (message instanceof jQuery)))) {
                $content.html(message);
            }

            if (message && message.nodeType === 1) {
                display = message.style.display;
                prev = message.previousSibling;
                next = message.nextSibling;
                parent = message.parentNode;

                this._elemBack = function () {
                    if (prev && prev.parentNode) {
                        prev.parentNode.insertBefore(message, prev.nextSibling);
                    } else if (next && next.parentNode) {
                        next.parentNode.insertBefore(message, next);
                    } else if (parent) {
                        parent.appendChild(message);
                    };
                    message.style.display = display;
                    that._elemBack = null;
                };

                $content.html('');
                content.appendChild(message);
                $(message).show();

            };

            that.winResize();

            return that;
        },


        /**
        * set title
        * @param    {String, Boolean}   title content. if false will hide the title
        */
        title: function (content) {

            var dom = this.dom,
                outer = dom.outer,
                $title = dom.title,
                className = 'vi-state-noTitle';

            if (content === false) {
                $title.hide().html('');
                outer.addClass(className);
            } else {
                $title.show().html(content);
                outer.removeClass(className);
            };

            return this;
        },

        /**
        * ajax request
        * @param {Object}
        * @param {Function} ajaxrequest callback
        */
        ajaxRequest: function (options, callback) {
            var that = this,
                opt = options || {};
            // When in frontend, there is no vision();
            var method = opt.method || "GET"; 
            $("body").loading(true, { mask: true, opacity: 0.8 }, false);
            if ($.vision) {
                $.vision().ajax(opt.url,
                {
                    cache: false,
                    type:method,
                    data: $.extend({ _dialogAjax: true }, opt.data || {}),
                    success: function (content) {
                        that.content(content);

                        callback && callback.call(that);
                        opt.initialize && opt.initialize.call(that);
                    }
                });
            } else if ($.frontendAjax) {
                $.frontendAjax(opt.url,
                    {
                        cache: false,
                        type: method,
                        data: $.extend({ _dialogAjax: true }, opt.data || {}),
                        success: function (content) {
                            that.content(content);

                            callback && callback.call(that);
                            opt.initialize && opt.initialize.call(that);
                        }
                    });
            } else {
                $.ajax({
                    url: opt.url,
                    cache: false,
                    type: method,
                    data: $.extend({ _dialogAjax: true }, opt.data || {}),
                    success: function (content) {
                        that.content(content);

                        callback && callback.call(that);
                        opt.initialize && opt.initialize.call(that);
                    }
                });
            }
        },


        /** @inner center position */
        position: function () {

            var dom = this.dom,
                config = this.config,
                wrap = dom.wrap[0],
                $window = dom.window,
                $document = dom.document,
                fixed = this.config.fixed,
                dl = fixed ? 0 : $document.scrollLeft(),
                dt = fixed ? 0 : $document.scrollTop(),
                ww = $window.width(),
                wh = $window.height(),
                ow = wrap.offsetWidth,
                oh = wrap.offsetHeight,
                left = (ww - ow) / 2 + dl,
                //top = (wh - oh) * 382 / 1000 + dt,// gold
                top = (wh - oh) * 500 / 1000 + dt,
                style = wrap.style;

            style.left = Math.max(parseInt(left), dl) + 'px';
            if (config.isFullScreen) {                
                style.top = 0;
            }
            else if (config.disableTop === false)
                style.top = Math.max(parseInt(top), dt) + 'px';

            if (this._follow) {
                this._follow.removeAttribute(_expando + 'follow');
                this._follow = null;
            }

            return this;
        },
        
        /**
        *   size
        *   @param  {Number, String}    width
        *   @param  {Number, String}    height
        */
        size: function (width, height) {

            var dom = this.dom,
                style = dom.main[0].style;

            if (typeof width === 'number') {
                width = width + 'px';
            };

            if (typeof height === 'number') {
                dom.content.css("overflow", "auto");

                if (dom.content.hasScrollbar) {
                    dom.content.css("overflow-x", "hidden");
                } else {
                    dom.content.css("overflow-x", "auto");
                }

                height = height + 'px';
            };

            if (typeof width != "undefined" && width)
                style.width = width;

            if (typeof height != "undefined" && height)
                style.height = height;

            return this;
        },


        /**
        * follow element
        * @param    {HTMLElement}
        */
        follow: function (elem) {

            var $elem = $(elem),
                config = this.config;


            if (!elem || !elem.offsetWidth && !elem.offsetHeight) {

                return this.position(this._left, this._top);
            };

            var fixed = config.fixed,
                expando = _expando + 'follow',
                dom = this.dom,
                $window = dom.window,
                $document = dom.document,

                winWidth = $window.width(),
                winHeight = $window.height(),
                docLeft = $document.scrollLeft(),
                docTop = $document.scrollTop(),
                offset = $elem.offset(),

                width = elem.offsetWidth,
                height = elem.offsetHeight,
                left = fixed ? offset.left - docLeft : offset.left,
                top = fixed ? offset.top - docTop : offset.top,

                wrap = this.dom.wrap[0],
                style = wrap.style,
                wrapWidth = wrap.offsetWidth,
                wrapHeight = wrap.offsetHeight,
                setLeft = left - (wrapWidth - width) / 2,
                setTop = top + height,

                dl = fixed ? 0 : docLeft,
                dt = fixed ? 0 : docTop;


            setLeft = setLeft < dl ? left :
            (setLeft + wrapWidth > winWidth) && (left - wrapWidth > dl)
            ? left - wrapWidth + width
            : setLeft;


            setTop = (setTop + wrapHeight > winHeight + dt)
            && (top - wrapHeight > dt)
            ? top - wrapHeight
            : setTop;


            style.left = parseInt(setLeft) + 'px';
            style.top = parseInt(setTop) + 'px';


            this._follow && this._follow.removeAttribute(expando);
            this._follow = elem;
            elem[expando] = config.id;

            return this;
        },


        /** open dialog */
        open: function () {
            var that = this,
                config = that.config;

            that.dom.wrap.css('visibility', 'hidden');
            if (config.url && !config.useFrame) {
                that.ajaxRequest(config, function () {
                    $("body").loading(false, null, true);

                    that.dom.wrap.css('visibility', 'visible');
                    that.dom.outer.addClass('vi-state-visible');

                    if (that._isLock) {
                        that._lockMask.show();
                    };

                    if (config.autoAdjustHeight) {
                        that.dom.content.bind("resize", function (e) {
                            that.adjustHeight();
                            e.stopPropagation();
                        });

                        that.dom.content.children().bind("resize", function (e) {
                            that.adjustHeight();
                            e.stopPropagation();
                        });
                    }
                });
            } else if ((config.url || config.redirectFrame) && config.useFrame) {
                $("body").loading(true, { mask: true, opacity: 0.8 });
                var iframe = $('<iframe '
                                   + (config.url?('src="' + config.url):'')
                                   + '" title="' + config.title
                                   + '" frameborder="0" style="border:0;display:block;" name="' + config.id + '" id="' + config.id + '"></iframe>').width(config.width).height(config.height);
                
                that.content(iframe);

                iframe.iframeLoad(function () {
                    that.dom.wrap.css('visibility', 'visible');
                    that.dom.outer.addClass('vi-state-visible');
                    if (that._isLock) {
                        that._lockMask.show();
                    };
                    $("body").loading(false, null, true);
                });
                that.center();
                                                
                that.winResize();
            } else {
                that.dom.wrap.css('visibility', 'visible');
                that.dom.outer.addClass('vi-state-visible');

                if (that._isLock) {
                    that._lockMask.show();
                };
                that.winResize();

                if (config.autoAdjustHeight) {
                    that.dom.content.bind("resize", function (e) {
                        that.adjustHeight();
                        e.stopPropagation();
                    });
                }
            }

            return that;
        },


        /** hide dialog */
        hidden: function () {
            this.dom.wrap.css('visibility', 'hidden');
            this.dom.outer.removeClass('vi-state-visible');

            if (this._isLock) {
                this._lockMask.hide();
            };

            return this;
        },


        /** close dialog */
        close: function (data) {
            if (this.closed) {
                return this;
            };

            var dom = this.dom,
                $wrap = dom.wrap,
                list = viClientDialog.list,
                beforeunload = this.config.beforeunload;

            if (beforeunload && beforeunload.call(this) === false) {
                return this;
            };


            if (viClientDialog.focus === this) {
                viClientDialog.focus = null;
            };


            if (this._follow) {
                this._follow.removeAttribute(_expando + 'follow');
            }

            if (this._elemBack) {
                this._elemBack();
            };

            this.config.onClosed && this.config.onClosed(data);

            this.time();
            this.unlock();
            this._removeEvent();
            delete list[this.config.id];


            if (_singleton) {

                $wrap.remove();

                // use singleton
            } else {

                _singleton = this;

                dom.title.html('');
                dom.content.html('');

                $wrap[0].className = $wrap[0].style.cssText = '';
                dom.outer[0].className = 'vi-outer';

                $wrap.css({
                    left: 0,
                    top: 0,
                    position: _isFixed ? 'fixed' : 'absolute'
                });

                for (var i in this) {
                    if (this.hasOwnProperty(i) && i !== 'dom') {
                        delete this[i];
                    };
                };

                this.hidden();

            };

            this.closed = true;
            return this;
        },


        /**
        * time close
        * @param    {Number}    unit: ms, null will stop timer
        */
        time: function (time) {

            var that = this,
                timer = this._timer;

            timer && clearTimeout(timer);

            if (time) {
                this._timer = setTimeout(function () {
                    that.close();
                }, time);
            };


            return this;
        },


        /** stick dialog */
        zIndex: function () {

            var dom = this.dom,
                top = viClientDialog.focus,
                index = viClientDialog.defaults.zIndex++;
            
            var maxIndex = this.getMaxzIndexofOtherDialogs();
            if(maxIndex>=index){
                index = maxIndex;
            }

            dom.wrap.css('zIndex', index);
            this._lockMask && this._lockMask.css('zIndex', index - 1);

            top && top.dom.outer.removeClass('vi-state-focus');
            viClientDialog.focus = this;
            dom.outer.addClass('vi-state-focus');

            return this;
        },
        getMaxzIndexofOtherDialogs:function(){
            var maxZIndex = 0;
            $(viClientDialog.defaults.otherDialogs).each(function () {
                if($(this)[0].style.zIndex > maxZIndex){
                    maxZIndex = $(this)[0].style.zIndex;
                }
            });
            return maxZIndex;
        },

        /** lock */
        lock: function () {

            if (this._isLock) {
                return this;
            };

            var that = this,
                config = this.config,
                dom = this.dom,
                div = document.createElement('div'),
                $div = $(div),
                index = viClientDialog.defaults.zIndex - 1;

            this.zIndex();
            dom.outer.addClass('vi-state-lock');

            $div.css({
                zIndex: index,
                position: 'fixed',
                left: 0,
                top: 0,
                width: '100%',
                height: '100%',
                overflow: 'hidden'
            }).addClass('vi-mask');

            if (!_isFixed) {
                $div.css({
                    position: 'absolute',
                    width: $(window).width() + 'px',
                    height: $(document).height() + 'px'
                });
            };

            $div.bind('dblclick', function () {
                if (config.dblUnlock) {
                    that.close();
                }
            });

            document.body.appendChild(div);

            this._lockMask = $div;
            this._isLock = true;

            return this;
        },


        /** unlock */
        unlock: function () {

            if (!this._isLock) {
                return this;
            };

            this._lockMask.unbind();
            this._lockMask.hide();
            this._lockMask.remove();

            this.dom.outer.removeClass('vi-state-lock');
            this._isLock = false;

            return this;
        },


        // get dom
        _getDom: function () {

            var body = document.body;
            var config = this.config;

            if (!body) {
                throw new Error('viClientDialog: "documents.body" not ready');
            };

            var wrap = document.createElement('div');

            wrap.style.cssText = 'position:absolute;left:0;top:0';
            if (!config.visible) {
                wrap.style.cssText = 'visibility: hidden';
            }
            wrap.innerHTML = viClientDialog._templates;
            body.appendChild(wrap, body.firstChild);

            var name,
                i = 0,
                dom = {},
                els = wrap.getElementsByTagName('*'),
                elsLen = els.length;

            for (; i < elsLen; i++) {
                name = els[i].className.split('vi-')[1];
                if (name) {
                    dom[name] = $(els[i]);
                };
            };

            dom.window = $(window);
            dom.document = $(document);
            dom.wrap = $(wrap);

            if (config.resize) {
                dom.resize.css("display", "inline-block");
            }

            return dom;
        },

        // center dialog
        center: function () {
            var elem = this.config.follow || this._follow;
            elem ? this.follow(elem) : this.position();
        },

        
        winResize: function () {            
            /// <summary>window resize</summary>
            var that = this;
            if (that.config.isFullScreen) {
                
                var winHeight = $(window).height();
                $(that.dom.wrap).height(winHeight - that.dom.borderHeight / 2);
                $(that.dom.main).height(winHeight - that.dom.borderHeight);
            } else {
                that.adjustHeight();
                that.center();
            }

            return that;
        },

        adjustHeight: function () {
            /// <summary>adapter the dialog height when the dialog is fixed and the dialog height more than the window height</summary>
            var that = this,
                config = that.config,
                dom = that.dom,
                $window = dom.window;

            if (config && config.fixed && config.height === "auto") {

                if (dom.wrap.outerHeight(true) > $window.height()) {
                    var spaceHeight = dom.wrap.outerHeight(true) - dom.c.outerHeight() + 10 + (dom.content.outerHeight(true) - dom.content.height());                    
                    that.size(dom.main.outerWidth(), $window.height() - spaceHeight - 30);
                }

                var contentHeight = that.getContentHeight();
                if (contentHeight > dom.main.innerHeight()) {
                    var spaceHeight = dom.wrap.outerHeight(true) - dom.c.outerHeight() + 10 + (dom.content.outerHeight(true) - dom.content.height());
                    that.size(dom.main.outerWidth(), Math.min($window.height() - spaceHeight - 30, contentHeight));
                } else {
                    that.size(dom.main.outerWidth(), "auto");
                }

                // set vertical middel
                var wrap = dom.wrap[0],
                    wh = $window.height(),
                    oh = wrap.offsetHeight,
                    top = (wh - oh) * 500 / 1000,
                    style = wrap.style;

                style.top = Math.max(parseInt(top), 0) + 'px';
            }
        },

        // get content height
        getContentHeight: function (includeMargin) {
            var that = this,
                config = that.config,
                includeMargin = includeMargin || true,
                dom = that.dom;

            var contentHeight = config.minHeight || 0;
            dom.content.children().each(function (i, n) {
                if ($(n).is(":visible")) {
                    contentHeight += $(n).outerHeight(includeMargin);
                }
            });

            return contentHeight;
        },

        // build action icons
        buildActionIcons: function () {
            var that = this,
                config = that.config,
                dom = that.dom;

            var actions = config.actions,
                customIcons = config.customIcons;

            actions.length == 0 ? dom.close.hide() : dom.close.show();
            var actionsContainer = dom.actions.children("ul");
            var actionsChildren = actionsContainer.find("> li > a").toArray();

            if ($.isArray(customIcons) && customIcons.length > 0) {
                var actionsChildrenNames = $.map(actionsChildren, function (n) {
                    return $(n).attr("data-name");
                });
                $(customIcons).each(function (i, n) {
                    if ($.isPlainObject(n) && $.inArray(n.name, actionsChildrenNames) == -1) {
                        actionsContainer.append("<li><a href=\"javascript:/*viClientDialog*/;\" data-name=\"" + n.name + "\" class=\"" + n.cssClass + "\">" + n.content + "</a></li>");
                        var actionDom = actionsContainer.find("li > a[data-name='" + n.name + "']");
                        actionDom.bind("click", function () {
                            var item = $(this);
                            n.eventCall && n.eventCall.call(that, item);
                        });;
                        dom[n.name] = actionDom;
                    }
                });
            } else {
                //remove the customIcon dom
                actionsContainer.find("> li:not(:has('a.vi-close'))").remove();
            }
        },

        // proxy event
        _addEvent: function () {

            var that = this,
                dom = this.dom;


            // listen click event
            dom.wrap
            .bind('click', function (event) {

                var target = event.target;

                if (target === dom.close[0]) {
                    that.close();
                    return false;
                };
            })
            .bind('mousedown', function () {
                if (that.config.lock == false)
                    that.zIndex();
            });
        },


        // remove proxy event
        _removeEvent: function () {
            var that = this;
            that.dom.wrap.unbind();

            if (that.config.autoAdjustHeight) {
                that.dom.content.unbind("resize");
                that.dom.content.children().unbind("resize");
            }
        }

    };

    viClientDialog.fn.constructor.prototype = viClientDialog.fn;


    $.fn.dialog = $.fn.viClientDialog = function () {
        var config = arguments;
        this[this.live ? 'live' : 'bind']('click', function () {
            viClientDialog.apply(this, config);
            return false;
        });
        return this;
    };



    /** top dialog API */
    viClientDialog.focus = null;



    /**
    * get the dialog by ID, return API
    * @param    {String}    dialog ID
    * @return   {Object}    dialog API (instance)
    */
    viClientDialog.get = function (id) {
        return id === undefined
        ? viClientDialog.list
        : viClientDialog.list[id];
    };

    viClientDialog.list = {};



    // global shortcut key
    $(document).bind('keydown', function (event) {
        var target = event.target,
            nodeName = target.nodeName,
            rinput = /^input|textarea$/i,
            api = viClientDialog.focus,
            keyCode = event.keyCode;

        // if the IME show, the ESC short cut will close the IME, so if the target element is
        // input or textarea element, then do nothing.
        //if (!api || !api.config.esc || rinput.test(nodeName)) {
        if (!api || !api.config.esc) {
            return;
        };
        
        var enableCloseAction = $.isArray(api.config.actions) && $.inArray("close", api.config.actions) > -1;
        // ESC
        keyCode === 27 && enableCloseAction && api.close();
    });



    // change browser window resize the dialog position
    $(window).bind('resize', function () {        
        var dialogs = viClientDialog.list;
        for (var id in dialogs) {
            // add by Yahongbo 02/01/2013
            if (dialogs[id].config.fixed && dialogs[id].config.lock)
                dialogs[id].winResize();
        }
    });



   // XHTML template
    // @see http://marijnhaverbeke.nl/uglifyjs
    viClientDialog._templates =
    '<div class="vi-outer">'
    + '<div class="vi-c">'
    + '<div class="vi-titleBar">'
    + '<div class="vi-title"></div>'
    + '<div class="vi-actions">'
    + '<ul>'
    + '<li>'
    + '<a class="vi-close" href="javascript:/*viClientDialog*/;">'
    + '\xd7'
    + '</a>'
    + '</li>'
    + '</ul>'
    + '</div>'
    + '</div>'
    + '<div class="vi-main">'
    + '<div class="vi-content"></div>'
    + '</div>'
    + '<div class="vi-se"><span class="vi-resize"></span></div>'
    + '</div>'
    + '</div>';



    /**
     * default config
     */
    viClientDialog.defaults = {

        // html
        html: '<div class="vi-loading"><span>loading..</span></div>',

        // title
        title: 'message',

        // initialize call
        initialize: null,

        // before close call
        beforeunload: null,

        // content width, should set 'auto' or number
        width: 'auto',

        // content height, should set 'auto' or number
        height: 'auto',

        // padding
        padding: '0 16px',

        // skin
        skin: "viClientDialog",

        // time close
        time: null,

        // support Esc shortcut key colse
        esc: true,

        // init visible
        visible: false,

        // action buttons for show or hide the "close" icon,
        // if actions:[] will hide the "close" icon, else show close.
        // just compatible the telerik.window api
        actions: ["close"],

        // custom icons: [{ name: 'help', cssClass: 'vi-help', content: '\x3f', eventCall: function() {} }]
        customIcons: [],

        // make dialog follow the element
        follow: null,

        // lock
        lock: true,

        // fixed
        fixed: true,

        // zindex
        zIndex: 10000,

        // ajax url
        url: null,

        // use the iframe
        useFrame: false,

        // double click unlock
        dblUnlock: false,

        // resize the dialog
        resize: false,

        // after close call
        onClosed: function (data) { },

        // auto adjust height
        autoAdjustHeight: true,

        //disable top on position
        disableTop: false,

        // other dialogs: RadDialog
        otherDialogs: ".RadWindow",

        isFullScreen : false
    };

    this.viClientDialog = $.viDialog = $.viClientDialog = viClientDialog;
}(this.vi || this.jQuery, this));



/**
* Plugin: ViClientDialog drag module
*/
; (function ($) {
    // drag event
    var DragEvent = function () {
        var that = this,
            proxy = function (name) {
                var fn = that[name];
                that[name] = function () {
                    return fn.apply(that, arguments);
                };
            };

        proxy('start');
        proxy('over');
        proxy('end');
    };


    DragEvent.prototype = {

        // Start drag
        // onstart: function () {},
        start: function (event) {
            $(document)
            .bind('mousemove', this.over)
            .bind('mouseup', this.end);

            this._sClientX = event.clientX;
            this._sClientY = event.clientY;
            this.onstart(event.clientX, event.clientY);

            return false;
        },

        // Dragging
        // onover: function () {},
        over: function (event) {
            this._mClientX = event.clientX;
            this._mClientY = event.clientY;
            this.onover(
                event.clientX - this._sClientX,
                event.clientY - this._sClientY
            );

            return false;
        },

        // End drag
        // onend: function () {},
        end: function (event) {
            $(document)
            .unbind('mousemove', this.over)
            .unbind('mouseup', this.end);

            this.onend(event.clientX, event.clientY);
            return false;
        }

    };

    var $window = $(window),
        $document = $(document),
        html = document.documentElement,
        isIE6 = !('minWidth' in html.style),
        isLosecapture = !isIE6 && 'onlosecapture' in html,
        isSetCapture = 'setCapture' in html,
        dragstart = function () {
            return false
        };

    var dragInit = function (event) {
        if (viClientDialog.focus.config.isFullScreen) {
            return;
        }

        var dragEvent = new DragEvent,
            api = viClientDialog.focus,
            dom = api.dom,
            $wrap = dom.wrap,
            $outer = dom.outer,
            $title = dom.title,
            $main = dom.main,
            wrap = $wrap[0],
            title = $title[0],
            main = $main[0],
            wrapStyle = wrap.style,
            mainStyle = main.style;


        var isResize = event.target === dom.resize[0] ? true : false;
        var isFixed = wrap.style.position === 'fixed',
            minX = isFixed ? 0 : $document.scrollLeft(),
            minY = isFixed ? 0 : $document.scrollTop(),
            maxX = $window.width() - wrap.offsetWidth + minX,
            maxY = $window.height() - wrap.offsetHeight + minY;

        dom.title.disableSelection();

        var startWidth, startHeight, startLeft, startTop;


        // dialog ready drag
        dragEvent.onstart = function (x, y) {

            if (isResize) {
                startWidth = main.offsetWidth;
                startHeight = main.offsetHeight;
            } else {
                startLeft = wrap.offsetLeft;
                startTop = wrap.offsetTop;
            };

            $document.bind('dblclick', dragEvent.end)
            .bind('dragstart', dragstart);

            if (isLosecapture) {
                $title.bind('losecapture', dragEvent.end)
            } else {
                $window.bind('blur', dragEvent.end)
            };

            isSetCapture && title.setCapture();

            $outer.addClass('vi-state-drag');
        };

        // dialog dragging
        dragEvent.onover = function (x, y) {

            if (isResize) {
                var width = x + startWidth,
                    height = y + startHeight;

                wrapStyle.width = 'auto';
                mainStyle.width = Math.max(0, width) + 'px';
                wrapStyle.width = wrap.offsetWidth + 'px';

                mainStyle.height = Math.max(0, height) + 'px';

            } else {
                var left = Math.max(minX, Math.min(maxX, x + startLeft)),
                    top = Math.max(minY, Math.min(maxY, y + startTop));

                wrapStyle.left = left + 'px';
                wrapStyle.top = top + 'px';
            };


        };

        // end drag
        dragEvent.onend = function (x, y) {

            $document.unbind('dblclick', dragEvent.end)
            .unbind('dragstart', dragstart);

            if (isLosecapture) {
                $title.unbind('losecapture', dragEvent.end);
            } else {
                $window.unbind('blur', dragEvent.end)
            };

            isSetCapture && title.releaseCapture();

            $outer.removeClass('vi-state-drag');
        };


        dragEvent.start(event);

    };


    $(document).bind('mousedown', function (event) {
        var api = viClientDialog.focus;
        if (!api) return;

        var target = event.target,
            config = api.config,
            dom = api.dom;

        if (config.drag !== false && target === dom.title[0]
        || config.resize !== false && target === dom.resize[0]) {

            dragInit(event);
            return false;
        };
    });


}(this.vi || this.jQuery));;
$(function () {
    var basePath = window.visionOptions.virtualApplicationPath;
    var useDesignThemFontSizeCss = window.visionOptions.useDesignThemFontSizeCss;
    var folderPath = useDesignThemFontSizeCss == true ? window.visionOptions.currentDesignFolderPath : window.visionOptions.mainFolderPath;//mainFolderPath;
    if (!folderPath)
        folderPath = window.visionOptions.mainFolderPath;
    var cookieName = basePath.replace(/\//g,"_") + "FontSize";
    var resizeTimer;
    var resizeFaqTabs = function () {
        $(".faq_widget").each(function () {
            var tabheight = $(this).find(".faq_tab_nav").height();
            $(this).find(".faqtab_section").attr("style", "min-height: " + (tabheight - 42) + "px");
        });
    };

    var SetFontSize = function (fontsize) {
        $("#active_font").attr("href", folderPath + fontsize).attr("data-css", fontsize);
        $.cookie(cookieName, fontsize, { expires: 365, path: '/' });
        if ($(".faq_tab_nav").length > 0) {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function () {
                resizeFaqTabs();
            }, 200);
        }

    };

    var GetFontSize = function() {
        var fontsize = $.cookie(cookieName);
        if (fontsize && fontsize.indexOf('/') < 0)
            return fontsize;
        return "x-small.css";
    };

    // intialize the font size.
    var initialFontSize = GetFontSize();
    $("#active_font").attr("href", folderPath + initialFontSize).attr("data-css", initialFontSize);

    $(".font_larger").live("click", function () {
        switch ($("#active_font").attr("data-css")) {
            case "medium.css": SetFontSize("large.css"); break;
            case "small.css": SetFontSize("medium.css"); break;
            case "x-small.css": SetFontSize("small.css"); break;
            case "xx-small.css": SetFontSize("x-small.css"); break;
        }
        return false;
    });

    $(".font_smaller").live("click", function () {
        switch ($("#active_font").attr("data-css")) {
            case "large.css": SetFontSize("medium.css"); break;
            case "medium.css": SetFontSize("small.css"); break;
            case "small.css": SetFontSize("x-small.css"); break;
            case "x-small.css": SetFontSize("xx-small.css"); break;
        }
        return false;
    });

    $(".text_size").live("click", function () {
        SetFontSize("x-small.css");
        return false;
    });
});
;
/// <reference path="../jquery/jquery-1.7.2.js" />
/// <reference path="../ms/MicrosoftAjax.js" />
Type.registerNamespace("Visionjs");
Type.registerNamespace("Visionjs.Components");
Type.registerNamespace("Visionjs.Components.JobPosts");

Visionjs.VisionBase = function () {
}
Visionjs.VisionBase.registerClass("Visionjs.VisionBase", null);

Visionjs.Components.JobPosts.JobApplFormManager = function (options) {
    this._options = $.extend({
        questionSelector: ".form_question_area",
        childQuestionSelector: ".child_question",
        blockSelector: "div.job_appl_form_block_layout",
        checkSkipRuleWhenInit:true,
    }, options);
    this._target = $(this._options.target);
    this._form = $(this._target).closest("form");
    this.initialize();

}
Visionjs.Components.JobPosts.JobApplFormManager.prototype = {
    _options: {},
    _target: null,
    _form: null,
    _questions:[],
    initialize: function () {
        var $thisJAM = this;
        // Initialize Questions
        $thisJAM.refreshQuestions();

        if ($thisJAM._options.checkSkipRuleWhenInit)
            $thisJAM.checkSkipRules();

        // Initialize Skip Rules
        $($thisJAM._form).delegate("input,select,textarea", "change", function () {
            var $thisEle = $(this);
            var thisTagName = $thisEle[0].tagName;
            var skipRuleSource = $thisEle.closest($thisJAM.getQuestionSelectors());
            if (skipRuleSource && skipRuleSource.length > 0) {
                var currentQuestionID = parseInt(skipRuleSource.attr("data-question-id"));
                $thisJAM.checkSkipRules(currentQuestionID);
            }
        });
    },
    checkSkipRules: function (questionID) {
        var $thisJAM = this;
        var questions = [];
        if (questionID) {
            questions = $thisJAM.getQuestion(questionID);
        } else {
            questions = $thisJAM.getAllQuestions();
        }

        var allSkipRules = [];
        var toSkipQuestionIDs = [];
        var toSkipBlockIDs = [];
        $(questions).each(function () {
            var questionTarget = $(this._target);
            var currentQuestionID = this.getQuestionId();
            var skipRuleAttr = questionTarget.attr("data-skip-rules");
            if (skipRuleAttr) {
                var skipRulesOfCurrentQuestion = $.parseJSON(skipRuleAttr);
                $(skipRulesOfCurrentQuestion).each(function (i, n) {
                    if (n.SkipQuestionID != null && toSkipQuestionIDs.indexOf(n.SkipQuestionID) < 0)
                        toSkipQuestionIDs.push(n.SkipQuestionID);
                    if (n.SkipBlockID != null && toSkipBlockIDs.indexOf(n.SkipBlockID) < 0)
                        toSkipBlockIDs.push(n.SkipBlockID);
                });
            }
        });
        $(toSkipQuestionIDs).each(function (i, n) {
            $($thisJAM.getQuestion(n)).each(function () { 
                this.display(!$thisJAM.canSkipQuestion(this));
            });
        });
        $(toSkipBlockIDs).each(function (i, n) {
            $thisJAM.displayBlock(n, !$thisJAM.canSkipBlock(n));
        });
    },
    refreshQuestions: function () {
        var $thisJAM = this;
        // Initialize Questions
        $thisJAM._questions = $thisJAM.newQuestions($($thisJAM._target).find($thisJAM.getQuestionSelectors()));
    },
    getBlockSelectors: function (blockID) {
        if (blockID) {
            return this._options.blockSelector + "[data-block-id='" + blockID + "']";
        } else {
            return this._options.blockSelector;
        }
    },
    getQuestionSelectors: function (questionID) {
        if (questionID) {
            return this._options.questionSelector + "[data-question-id='" + questionID + "']";
        } else {
            return this._options.questionSelector;
        }
    },
    newQuestions: function (questionEle, order) {
        return Visionjs.Components.JobPosts.JobApplFormQuestion.NewQuestions(questionEle,this, order);
    },
    getAllQuestions: function () {
        return this._questions;
    },
    getQuestion: function (questionID, order) { // Might return multiple questions.
        var $thisJAM = this;
        var resultQuestions = [];
        $($thisJAM._questions).each(function () {
            if (this.getQuestionId() == questionID) {
                if (typeof order == "undefined" || order == this.getBlockOrder())
                    resultQuestions.push(this);
            }
        });
        if (resultQuestions.length == 0) {
            var theQuestionEle = $($thisJAM.getQuestionSelectors(questionID));
            resultQuestions = $thisJAM.newQuestions(theQuestionEle, order);
        }
        return resultQuestions;
    },
    canSkipQuestion: function (question) {
        var $thisJAM = this;

        var toSkipQuestionID = question.getQuestionId();
        var toSkipOrderOfQuestion= question.getBlockOrder();
        var theBlockIDOfToSkipQuestion = question.getBlockId();
        
        var allSkipRulesOfCurrentQuestion = [];
        $($thisJAM.getQuestionSelectors()).each(function () {
            var blockOfCurrentQuestion = $(this).closest($thisJAM.getBlockSelectors());
            var currentBlockID = parseInt(blockOfCurrentQuestion.attr("data-block-id"));
            var currentBlockOrder = parseInt(blockOfCurrentQuestion.attr("data-block-order"));
            var currentQuestionID = parseInt($(this).attr("data-question-id"));
            
            var skipRulesAttrValue = $(this).attr("data-skip-rules");
            if (skipRulesAttrValue) {
                $($.parseJSON(skipRulesAttrValue)).each(function () {
                    if (this.SkipQuestionID != null && this.SkipQuestionID == toSkipQuestionID) {
                        var skipRule = $.extend({}, this, { Order: currentBlockOrder });
                        if (theBlockIDOfToSkipQuestion != currentBlockID
                            || (theBlockIDOfToSkipQuestion == currentBlockID && toSkipOrderOfQuestion == currentBlockOrder))
                            allSkipRulesOfCurrentQuestion.push(skipRule);
                    }
                });
            }
        }); 
        return $thisJAM.canBeSkippedBy(allSkipRulesOfCurrentQuestion);
    },
    displayBlock: function (blockID, display) {
        var theBlock = $(this.getBlockSelectors(blockID));
        var theAddActionBlockPanel = $(".job_appl_form_block_layout_action.add_block_action[data-block-id='" + blockID + "']");
        if (display) {
            theBlock.show();
            theAddActionBlockPanel.show();
        } else {
            theBlock.hide();
            theAddActionBlockPanel.hide();
        }
    },
    canSkipBlock: function (blockID) {
        var $thisJAM = this;

        var allSkipRulesOfCurrentBlock = [];
        $($thisJAM.getQuestionSelectors()).each(function () {
            var blockOfCurrentQuestion = $(this).closest($thisJAM.getBlockSelectors());
            var currentBlockID = parseInt(blockOfCurrentQuestion.attr("data-block-id"));
            var currentBlockOrder = parseInt(blockOfCurrentQuestion.attr("data-block-order"));

            if (currentBlockID != blockID) {
                var skipRulesAttrValue = $(this).attr("data-skip-rules");
                if (skipRulesAttrValue) {
                    $($.parseJSON(skipRulesAttrValue)).each(function () {
                        if (this.SkipBlockID != null && this.SkipBlockID == blockID) {
                            var skipRule = $.extend({}, this, { Order: currentBlockOrder });
                            allSkipRulesOfCurrentBlock.push(skipRule);
                        }
                    });
                }
            }

        });

        return $thisJAM.canBeSkippedBy(allSkipRulesOfCurrentBlock);
    },
    canBeSkippedBy: function (skipRules) {
        var $thisJAM = this;

        var canSkip = false;
        $(skipRules).each(function (i, n) {
            var skipRule = n;
            var resultAnswersOfCurrentQuestion = [];
            $($thisJAM.getQuestion(skipRule.QuestionID, skipRule.Order)).each(function () {
                $(this.getResultAnswers()).each(function () {
                    resultAnswersOfCurrentQuestion.push(this);
                });
            });

            if (skipRule.ConditionalOperator == 0) {// Answered
                if (skipRule.AnswerID == null) {
                    canSkip = resultAnswersOfCurrentQuestion.length > 0;
                } else {
                    var resultAnswersOfCurrentSkipRuleAnswer = [];
                    $(resultAnswersOfCurrentQuestion).each(function () {
                        if (this.id == skipRule.AnswerID) {
                            resultAnswersOfCurrentSkipRuleAnswer.push(this);
                        }
                    });
                    $(resultAnswersOfCurrentSkipRuleAnswer).each(function () {
                        var resultAnswer = this;
                        if (!resultAnswer.canExpressionConditional || skipRule.TextFilter == null || skipRule.TextFilter == "" ) {
                            canSkip = true;
                        }
                        else {
                            if (resultAnswer.text != null && resultAnswer.text != "") {
                                switch (skipRule.ExpressionOperator) {
                                    case 0: // Equals                                    
                                        canSkip = resultAnswer.text.toLowerCase() == skipRule.TextFilter.toLowerCase();
                                        break;
                                    case 2:// GreaterThan
                                        canSkip = resultAnswer.text.toLowerCase() > skipRule.TextFilter.toLowerCase();
                                        break
                                    case 3: // LessThan
                                        canSkip = resultAnswer.text.toLowerCase() < skipRule.TextFilter.toLowerCase();
                                        break;
                                    case 1: // contains
                                    default: //contains
                                        canSkip = resultAnswer.text.toLowerCase().indexOf(skipRule.TextFilter.toLowerCase()) >= 0;
                                        break;
                                }
                            }
                        }
                        if (canSkip)
                            return false;
                    });
                }
            }
            else if (skipRule.ConditionalOperator == 1) {// NotAnswered
                if (skipRule.AnswerID == null) {
                    canSkip = resultAnswersOfCurrentQuestion.length <= 0;
                } else {
                    var resultAnswersOfCurrentSkipRuleAnswer = [];
                    $(resultAnswersOfCurrentQuestion).each(function () {
                        if (this.id == skipRule.AnswerID) {
                            resultAnswersOfCurrentSkipRuleAnswer.push(this);
                        }
                    });
                    if (resultAnswersOfCurrentSkipRuleAnswer.length <= 0)
                        canSkip = true;
                    else {
                        $(resultAnswersOfCurrentSkipRuleAnswer).each(function () {
                            var resultAnswer = this;
                            if (resultAnswer.canExpressionConditional && skipRule.TextFilter != null && skipRule.TextFilter != "") {
                                if (resultAnswer.text == null || resultAnswer.text == "")
                                    canSkip = true;
                                else {
                                    switch (skipRule.ExpressionOperator) {
                                        case 0: // Equals                                    
                                            canSkip = !(resultAnswer.text.toLowerCase() == skipRule.TextFilter.toLowerCase());
                                            break;
                                        case 2:// GreaterThan
                                            canSkip = !(resultAnswer.text.toLowerCase() > skipRule.TextFilter.toLowerCase());
                                            break
                                        case 3: // LessThan
                                            canSkip = !(resultAnswer.text.toLowerCase() < skipRule.TextFilter.toLowerCase())
                                            break;
                                        case 1: // contains
                                        default: //contains
                                            canSkip = !(resultAnswer.text.toLowerCase().indexOf(skipRule.TextFilter.toLowerCase()) >= 0);
                                            break;
                                    }
                                }
                            }
                            if (canSkip)
                                return false;
                        })
                    }
                }
            }
            if (canSkip)
                return false;
        });
        return canSkip;
    }
};
Visionjs.Components.JobPosts.JobApplFormManager.registerClass("Visionjs.Components.JobPosts.JobApplFormManager", Visionjs.VisionBase);

Visionjs.Components.JobPosts.JobApplFormQuestion = function (options) {
    this._options = $.extend({}, options);
    this._target = $(this._options.target);
    this._JAM = this._options.JAM;
    this.initialize();
}
Visionjs.Components.JobPosts.JobApplFormQuestion.prototype = {
    _options:{},
    _target: null,
    _questionId: 0,
    _JAM: null,
    _order:0,
    _blockTarget:null,
    initialize: function () {
        var $thisQuestion = this;
        this._questionId = $($thisQuestion._target).attr("data-question-id");
        this._blockTarget = $($thisQuestion._target).closest($thisQuestion._JAM.getBlockSelectors());
        this._order = parseInt(this._blockTarget.attr("data-block-order"));
        this._blockId = parseInt(this._blockTarget.attr("data-block-id"));
    },
    getBlockOrder: function () {
        return this._order;
    },
    getBlockId: function () {
        return this._blockId;
    },
    getQuestionId: function () {
        return this._questionId;
    },
    display:function(display){
        if(display){
            $(this._target).show();
        }else{
            $(this._target).hide();
        }
    },
    isMatrixQuestion: function () {
        return $(this._target).find(this._JAM._options.childQuestionSelector).length > 0;
    },
    //ResultAnswer: {id:1, text:"", type:1}
    getResultAnswers: function () {
        var $thisQuestion = this;
        var resultAnswers = [];
        // don't include Matrix 
        if (!$thisQuestion.isMatrixQuestion()) {
            $($thisQuestion._target).find("input[type='hidden'][data-answer-setting-type]").each(function () {
                var answerTypeSetting = $(this).attr("data-answer-setting-type");
                if (answerTypeSetting) {
                    try {
                        var answerTypeSettingCls = $.evalFunc("Visionjs.Components.JobPosts." + answerTypeSetting);
                        if (Type.isClass(answerTypeSettingCls)) {
                            var answerSetting = new answerTypeSettingCls({
                                target: $(this),
                                question: $thisQuestion
                            });
                            var resultAnswer = answerSetting.getResultAnswer();

                            if (resultAnswer != null) {
                                resultAnswers.push(resultAnswer);
                            }
                        }
                    }catch(ex){}
                }
            });
        }
        return resultAnswers;
    }
};
Visionjs.Components.JobPosts.JobApplFormQuestion.NewQuestions = function (questionEle,JAM, order) {
    var questions = [];
    $(questionEle).each(function () {
        var qEle = this;
        try {
            var questionTypeClass = null;
            var questionType = $(this).attr("data-question-type");
            if (!questionType) {
                questionType = "JobApplFormQuestion";
            }
            questionTypeClass = $.evalFunc("Visionjs.Components.JobPosts." + questionType);
            if (Type.isClass(questionTypeClass)) {
                var question = new questionTypeClass({
                    target: qEle,
                    JAM: JAM
                });
                if (typeof order == "undefined" || order == question.getBlockOrder())
                    questions.push(question);
            }
        } catch (e) {}
    });
    return questions;
}
Visionjs.Components.JobPosts.JobApplFormQuestion.registerClass("Visionjs.Components.JobPosts.JobApplFormQuestion", Visionjs.VisionBase);


Visionjs.Components.JobPosts.JobApplFormAnswerSetting = function (options) {
    this._options = $.extend({}, options);
    this._target = $(this._options.target);
    this._question = this._options.question;
    this._JAM = this._question._JAM;
    this.initialize();
}
Visionjs.Components.JobPosts.JobApplFormAnswerSetting.prototype = {
    _options: {},
    _target: null,
    _JAM:null,
    _forAnswerPrefix: null,
    _answerId:0,
    _answerData: {},
    _resultAnswerInputName: "ResultAnswer.Text",
    _question:null,
    initialize: function () {
        this._forAnswerPrefix = $(this._target).attr("data-for-answer");
        this._answerData = $.parseJSON($(this._target).attr("data-answer-data"))
        this._answerId = this._answerData.id;
    },
    //ResultAnswer: {id:1, text:"", canExpressionConditional:true, order:0}
    getResultAnswer: function () {
        var $thisAnswerSetting = this;
        return {
            id: $thisAnswerSetting._answerId,
            text: $thisAnswerSetting.getResultAnswerValue(),
            canExpressionConditional: $thisAnswerSetting._answerData.canExpressionConditional,
            order: $thisAnswerSetting.getResultAnswerOrder()
        };
    },
    getResultAnswerOrder: function () {
        var $thisAnswerSetting = this;
        return $thisAnswerSetting._question.getBlockOrder();
    },
    getResultAnswerValue: function () {
        var $thisAnswerSetting = this;
        var resultAnswerTextInputName = $thisAnswerSetting._forAnswerPrefix + "." + $thisAnswerSetting._resultAnswerInputName;
        var currentResultAnswerTextInput = $($thisAnswerSetting._question._target).find("[name='" + resultAnswerTextInputName + "']");
        return currentResultAnswerTextInput.val();
    }
};
Visionjs.Components.JobPosts.JobApplFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplFormAnswerSetting", Visionjs.VisionBase);

Visionjs.Components.JobPosts.JobApplFieldBasicFormAnswerSetting = function (options) {
    Visionjs.Components.JobPosts.JobApplFieldBasicFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplFieldBasicFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplFieldBasicFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

Visionjs.Components.JobPosts.JobApplFieldCalendarFormAnswerSetting = function (options) {
    this._resultAnswerInputName = "ResultAnswerSetting.FormResultAnswerDateValue";
    Visionjs.Components.JobPosts.JobApplFieldCalendarFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplFieldCalendarFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplFieldCalendarFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

Visionjs.Components.JobPosts.JobApplFieldEmailFormAnswerSetting = function (options) {
    Visionjs.Components.JobPosts.JobApplFieldEmailFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplFieldEmailFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplFieldEmailFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

//ToDo
Visionjs.Components.JobPosts.JobApplFieldFileUploadFormAnswerSetting = function (options) {
    this._resultAnswerInputName = "ResultAnswerSetting.UploadedFile";
    Visionjs.Components.JobPosts.JobApplFieldFileUploadFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplFieldFileUploadFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplFieldFileUploadFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

Visionjs.Components.JobPosts.JobApplFieldLargeFormAnswerSetting = function (options) {
    Visionjs.Components.JobPosts.JobApplFieldLargeFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplFieldLargeFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplFieldLargeFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);
//No Password
Visionjs.Components.JobPosts.JobApplFieldPasswordFormAnswerSetting = function (options) {
    Visionjs.Components.JobPosts.JobApplFieldPasswordFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplFieldPasswordFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplFieldPasswordFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

Visionjs.Components.JobPosts.JobApplFieldPhoneFormAnswerSetting = function (options) {
    Visionjs.Components.JobPosts.JobApplFieldPhoneFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplFieldPhoneFormAnswerSetting.prototype = {
    getResultAnswerValue: function () {
        var $thisAnswerSetting = this;
        var currentQuestion = $($thisAnswerSetting._question._target);
        var phoneValue = currentQuestion.find("[name='" + $thisAnswerSetting._forAnswerPrefix + ".ResultAnswerSetting.DefaultPhone']").val();
        var phoneExtValue = currentQuestion.find("[name='" + $thisAnswerSetting._forAnswerPrefix + ".ResultAnswerSetting.DefaultPhoneExt']").val();
        var value = phoneValue;
        if (phoneExtValue)
            value += "ext." + phoneExtValue;
        return value;
    }
};
Visionjs.Components.JobPosts.JobApplFieldPhoneFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplFieldPhoneFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

Visionjs.Components.JobPosts.JobApplFieldSSNFormAnswerSetting = function (options) {
    Visionjs.Components.JobPosts.JobApplFieldSSNFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplFieldSSNFormAnswerSetting.prototype = {
    getResultAnswerValue: function () {
        var $thisAnswerSetting = this;
        var currentQuestion = $($thisAnswerSetting._question._target);
        var ssn1 = currentQuestion.find("[name='" + $thisAnswerSetting._forAnswerPrefix + ".ResultAnswerSetting.SocialSecurityNumber1']").val();
        var ssn2 = currentQuestion.find("[name='" + $thisAnswerSetting._forAnswerPrefix + ".ResultAnswerSetting.SocialSecurityNumber2']").val();
        var ssn3 = currentQuestion.find("[name='" + $thisAnswerSetting._forAnswerPrefix + ".ResultAnswerSetting.SocialSecurityNumber3']").val();
        return ssn1 + ssn2 + ssn3;
    }
};
Visionjs.Components.JobPosts.JobApplFieldSSNFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplFieldSSNFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

Visionjs.Components.JobPosts.JobApplXMLCountryListFormAnswerSetting = function (options) {
    Visionjs.Components.JobPosts.JobApplXMLCountryListFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplXMLCountryListFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplXMLCountryListFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

Visionjs.Components.JobPosts.JobApplXMLUSStatesFormAnswerSetting = function (options) {
    Visionjs.Components.JobPosts.JobApplXMLUSStatesFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplXMLUSStatesFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplXMLUSStatesFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

Visionjs.Components.JobPosts.JobApplSelectionBooleanFormAnswerSetting = function (options) {
    Visionjs.Components.JobPosts.JobApplSelectionBooleanFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplSelectionBooleanFormAnswerSetting.prototype = {
    getResultAnswerValue: function () {
        var $thisAnswerSetting = this;
        var currentQuestion = $($thisAnswerSetting._question._target);
        var value = currentQuestion.find("input[type='checkbox'][name='" + $thisAnswerSetting._forAnswerPrefix + ".ResultAnswerSetting.Selected']").prop("checked");
        return value.toString();
    }
};
Visionjs.Components.JobPosts.JobApplSelectionBooleanFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplSelectionBooleanFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

Visionjs.Components.JobPosts.JobApplSelectionStandardFormAnswerSetting = function (options) {
    Visionjs.Components.JobPosts.JobApplSelectionStandardFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplSelectionStandardFormAnswerSetting.prototype = {
    getResultAnswer: function () {
        var $thisAnswerSetting = this;
        var currentQuestion = $($thisAnswerSetting._question._target);
        var selectedElement = currentQuestion.find("input[name='" + $thisAnswerSetting._forAnswerPrefix + ".ResultAnswerSetting.Selected']");
        var copyfromfuncwhensubmit = selectedElement.attr("copyfromfuncwhensubmit");
        try {
            var selected = $.evalFunc(copyfromfuncwhensubmit)().toString().toLowerCase();
            if (selected=="true") { 
                return {
                    id: $thisAnswerSetting._answerId,
                    text: null,
                    canExpressionConditional: $thisAnswerSetting._answerData.canExpressionConditional,
                    order: $thisAnswerSetting.getResultAnswerOrder()
                };
            }
        }
        catch (e) {
        }
        return null;
    }
};
Visionjs.Components.JobPosts.JobApplSelectionStandardFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplSelectionStandardFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

Visionjs.Components.JobPosts.JobApplSelectionOtherFormAnswerSetting = function (options) {
    Visionjs.Components.JobPosts.JobApplSelectionOtherFormAnswerSetting.initializeBase(this, arguments);
}
Visionjs.Components.JobPosts.JobApplSelectionOtherFormAnswerSetting.prototype = {
    getResultAnswer: function () {
        var $thisAnswerSetting = this;
        var currentQuestion = $($thisAnswerSetting._question._target);
        var selectedElement = currentQuestion.find("input[name='" + $thisAnswerSetting._forAnswerPrefix + ".ResultAnswerSetting.Selected']");
        var textElement = currentQuestion.find("input[name='" + $thisAnswerSetting._forAnswerPrefix + ".ResultAnswerSetting.Text']");
        var copyfromfuncwhensubmit = selectedElement.attr("copyfromfuncwhensubmit");
        try {
            var selected = $.evalFunc(copyfromfuncwhensubmit)().toString().toLowerCase();
            if (selected == "true") {
                return {
                    id: $thisAnswerSetting._answerId,
                    text: textElement.val(),
                    canExpressionConditional: $thisAnswerSetting._answerData.canExpressionConditional,
                    order: $thisAnswerSetting.getResultAnswerOrder()
                };
            }
        }
        catch (e) {
        }
        return null;
    }
};
Visionjs.Components.JobPosts.JobApplSelectionOtherFormAnswerSetting.registerClass("Visionjs.Components.JobPosts.JobApplSelectionOtherFormAnswerSetting", Visionjs.Components.JobPosts.JobApplFormAnswerSetting);

;
