﻿/******************************************************************
* GLOBAL EVENTS
*****************************************************************/

function document_onload() {
    FixBoxes();

    FixFireFoxOnClick();

    FixIE6BGImages();

    FixIE5Onclick();

    try {
        fix800x600();
    }
    catch (e) { }

    if (Browser.Name == "Safari") {

        var active = this.GetFontSize();

        if (active == 'small') {
            //wtf safari!
            SetFontSize('medium');
            SetFontSize('small');
        }
    }
    SetFormLoading(false);
}

function document_unload() {
    var fontSize = GetFontSize();
    if (fontSize == null) {
        fontSize = "small";
    }

    SetCookie("fontSize", fontSize, null);
}

function popup_document_onload() {
    FixBoxes();

    ShowValidationErrors();

    FixIE6BGImages();
}

function window_onload() {
    if (navigator.userAgent.match(/iPad/i)) {
        var SearchBox = document.getElementById("ctl00_Header1_SearchBox1_SearchBox");
    }
    else {
        var SearchBox = document.getElementById("Header1_SearchBox1_SearchBox");
    }
    if (SearchBox) SearchBox.style.visibility = "visible";
}

function window_onresize() {
    PerformLayout();
}

document.getElementsByClassName = function (cl) {
    var retnode = [];
    var myclass = new RegExp('\\b' + cl + '\\b');
    var elem = this.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
};

function SetFormLoading(isLoading) {
    if (document.getElementById('aspnetForm') != null)
        document.getElementById('aspnetForm').style.visibility = isLoading ? 'hidden' : 'visible';
    if (document.getElementById('loadingBody') != null)
        document.getElementById('loadingBody').style.visibility = isLoading? 'visible' : 'hidden';
}
function SetElementWidths(maxWidth) {
    SetNodesWidths("mid_top_large_border", maxWidth);
    SetNodesWidths("mid_bottom_large_border", maxWidth);
    SetNodesWidths("mid_bottom_small_border", maxWidth)
    SetNodesWidths("mid_top_small_border", maxWidth)
}
function SetNodesWidths(className, maxWidth) {
    var nodes = document.getElementsByClassName(className);
    for (var index = 0; index < nodes.length; index++) {
        if (nodes[index].attributes["dynamicwidth"] != null && nodes[index].attributes["dynamicwidth"].value.toString().toLowerCase() == "true") {
            if (maxWidth == null) {

                nodes[index].style.width = nodes[index].parentNode.offsetWidth - 23;
            }
            else {
                nodes[index].style.width = nodes[index].parentNode.offsetWidth > maxWidth ? maxWidth : nodes[index].parentNode.offsetWidth;
            }
        }
    }

}

function RadWindow_OnClose(radWindow) {
    var iframe = radWindow.GetContentFrame();
    iframe.src = path("~/blank.htm");
    radWindow.Center();

    if (screen.width == 800) {
        document.body.style.overflow = "auto";
    }
}

function DefaultButtonHandler(defaultButton) {
    if (Event.keyCode == 13) {
        defaultButton.click();
    }
}

function PerformLayout() {
    // Get the container elemenet (TR).
    var container = document.getElementById("applicationContentRow");
    if (container == null) var container = window.parent.document.getElementById("applicationContentRow");

    // Get the content elemenet (IFrame).
    var content = document.getElementById("applicationContent");

    if (content == null) {
        content = window.parent.document.getElementById("applicationContent");
    }
    if (content == null) {
        content = document.getElementById("ctl00_contentTD");
    }
    if (container == null) {
        container = document.getElementById("ctl00_contentRow");
    }
    if (content == null) {
        content = window.parent.document.getElementById("ctl00_contentTD");
    }
    if (container == null) {
        container = window.parent.document.getElementById("ctl00_contentRow");
    }
    //Note: Setting to Zero first is important as it's the only way Firefox will perform the resize.
    content.style.height = "0px";
    content.style.height = container.offsetHeight + "px";
}


function RefreshTicker() {
    var win = window;

    while (win.parent != null && win.parent != win) {
        win = win.parent;
    }

    var timer = win.ctl00_Ticker2_TickerTimer;

    timer.Stop();

    win.eval(timer.PostBackString);
}


function FixIE6BGImages() {
    if (Browser.Name == "Internet Explorer" && Browser.Version == 6) {
        document.execCommand("BackgroundImageCache", false, true);
    }
}

//Fix for IE5.5 which causes an issue with <A HREF="Javascript:xxx()">
function FixIE5Onclick() {
    if (Browser.Name == "Internet Explorer" && Browser.Version == 5.5) {
        document.onclick = DocumentOnClickHandlerIE55;
    }
}

//Fix IE box-corners positioning issue.
function FixBoxes() {
    if (Browser.Name == "Internet Explorer") {
        var DivEls = document.getElementsByTagName("DIV");

        for (var i = 0; i < DivEls.length; i++) {
            if (DivEls[i].className.indexOf("homepage_box") != -1) {
                var ctrlHeight = DivEls[i].offsetHeight;
                if (ctrlHeight % 2 == 0) {
                    DivEls[i].style.height = ctrlHeight + 1;
                }
            }
//            else if (DivEls[i].className.indexOf("block_resize") != -1 && DivEls[i].className.indexOf("block_resize_content") == -1) {
//                var ctrlHeight = DivEls[i].offsetHeight;

//                if (ctrlHeight % 2 != 0) {
//                    DivEls[i].style.height = ctrlHeight + 1;
//                }

//                var ctrlWidth = DivEls[i].offsetWidth;
//                if (ctrlWidth % 2 != 0) {
//                    DivEls[i].style.width = ctrlWidth - 1;
//                }
//            }
        }
    }
}

function GetTopmostWindow() {
    

    /* The below code is not required due to the removal of IFrames*/

    var win = window;
		
    while (win.parent && win.parent != win)
    {
    win = win.parent;
    }
		
    return win;
}

function FixDateTimeFormat(toRadDatePicker_dateInput_Name) {
    var o = window[toRadDatePicker_dateInput_Name];

    o.DateTimeFormatInfo.DateSlots.Day = 0;
    o.DateTimeFormatInfo.DateSlots.Month = 1;
    o.DateTimeFormatInfo.DateSlots.Year = 2;
}

function FixFireFoxOnClick() {
    if (Browser.Name == "Firefox") {
        var inputs = document.getElementsByTagName("input");

        for (var i = 0; i < inputs.length; i++) {
            var input = inputs[i];

            //process all of our image buttons
            if (input.type == "image" && input.id.substr(input.id.length - 9, 9) == "iconImage") {
                var onclick = input.getAttribute("onclick");

                if (onclick != null && onclick != "") {
                    var parts = onclick.split(';');
                    var newOnClick = "";
                    for (var p = 0; p < parts.length; p++) {
                        //trim
                        var part = parts[p].replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/, '$1');

                        if (part.substr(0, 7) == "AjaxNS.") {
                            while (part.indexOf("\"") != -1) {
                                part = part.replace("\"", "@@@");
                            }

                            while (part.indexOf("@@@") != -1) {
                                part = part.replace("@@@", "\\\"");
                            }

                            //Ensure all Ajax requests are called via a setTimeout()
                            newOnClick += "setTimeout(\"" + part + "\", 100);return false;";
                            break;
                        }
                        else if (part.substr(0, 7) == "return ") {
                            //If a return is found, don't bother with what follows
                            newOnClick += part + ";";
                            break;
                        }
                        else {
                            //Add whatever is specified.
                            newOnClick += part + ";";
                        }

                        //clear
                        part = null;

                    }
                    //Assign the new onclick event handler
                    input.onclick = new Function(newOnClick);

                    //clear
                    newOnClick = null;
                    p = null;
                    parts = null;
                }

                //clear				
                onclick = null;
            }

            //release
            input = null;
        }
        //release
        inputs = null;
    }
}

function fix800x600() {
    //Fix for clients using 800 x 600
    if (screen.width == 800) {
        document.body.style.overflow = "auto";
        if (window.parent != window) {
            var applicationContentRow = window.parent.document.getElementById("applicationContentRow");
            var ctl00_contentTD = document.getElementById("ctl00_contentTD");

            if (applicationContentRow && ctl00_contentTD) {
                applicationContentRow.style.height = ctl00_contentTD.offsetHeight + 310;
            }
        }

    }
}

function Firefox3Support(sender) {
    if (sender.onclick.toString().indexOf('AjaxNS') > -1) {
        sender.disabled = true;
        setTimeout("if (document.getElementById('" + sender.id + "') != null) document.getElementById('" + sender.id + "').disabled = false;", 1000);
    }
}

function ResetDialogOnclose(dialog) {
    dialog.OnClientClose = window.parent.RadWindow_OnClose;

    //Call the old onclose event handler
    window.parent.RadWindow_OnClose(dialog);
}

function IsNullOrEmpty(radWindow) {
    if (typeof (radWindow.Argument) == "undefined") {
        return true;
    }
    else {
        return radWindow.Argument == "" || radWindow.Argument == null;
    }
}

function CloseRadWindow(argument) {
    var wnd = window.frameElement.radWindow;

    wnd.Argument = argument;

    wnd.Close();
}

/******************************************************************
* GLOBAL VARIABLES
*****************************************************************/

/// <summary>
/// The server's date.
/// </summary>
ServerDate = "";

/// <summary>
/// The Virtual root of the application.
/// </summary>
VirtualRoot = "";

/******************************************************************
* GLOBAL FUNCTIONS
******************************************************************/
function NavigateTo(url) {
    if (Browser.Name == "Firefox" || Browser.Name == "Safari") {
        window.location = path(url, arguments);
    }
    else {
        window.navigate(path(url, arguments));
    }
}

function SetSiteFontSize() {
    var cookieFontSize = GetCookie("fontSize");
    SetFontSize(cookieFontSize);
}

function ButtonDisabled(buttonPart) {
    return buttonPart.parentNode.parentNode.parentNode.parentNode.disabled;
}

var clickAttempts = 0;
function CheckIfCanPostBack(sender) {
    var __eventValidation = document.getElementById("__EVENTVALIDATION");

    if (__eventValidation == null || __eventValidation.value == "") {
        clickAttempts++;

        if (clickAttempts == 30) {
            clickAttempts = 0;

            return false;
        }
        else {
            setTimeout("document.getElementById('" + sender.id + "').click();", 100);

            return false;
        }
    }
    else {
        return true;
    }

}

function FormatString(s) {
    var w = s;
    for (var i = 1; i < arguments.length; i++) {
        w = w.replace("{" + (i - 1).toString() + "}", arguments[i]);
    }

    return w;
}

function path(x) {
    var w = x;
    for (var i = 1; i < arguments.length; i++) {
        w = w.replace("{" + (i - 1).toString() + "}", arguments[i]);
    }

    return w.replace("~", VirtualRoot);
}

function FillObjectHeight(Print_Container) {
    var heights = 0;
    var widths = 0;
    for (var i = 1; i < arguments.length; i++) {
        heights += arguments[i].offsetHeight;
    }
    heights += 40;
    Print_Container.style.height = document.body.offsetHeight - heights;
    Print_Container.style.width = document.body.offsetWidth - 40;

    Events.AddHandler(window, "resize", new Function("$('" + Print_Container.id + "').style.height = document.body.offsetHeight - " + heights.toString() + "; $('" + Print_Container.id + "').style.width = document.body.offsetWidth - 40;"));
}
function SetCookie(name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date().AddDays(days);

        expires = "; expires=" + date.toGMTString();
    }

    document.cookie = name + "=" + value + expires + "; path=/";
}

function GetCookie(name) {
    var nameEQ = name + "=";

    var ca = document.cookie.split(';');

    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }

        if (c.indexOf(nameEQ) == 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }

    return null;
}

function RemoveCookie(name) {
    Createcookie(name, "", -1);
}

function DocumentOnClickHandlerIE55() {
    var el = null;
    var flag = true;
    el = event.srcElement;

    // Do the While loop to find out if any of the parent elements 
    // are an A HREF.
    // This is necessary because in Internet Explorer 4.x, you can 
    // receive events of any element including the <B> tag.   
    while (flag && el) {
        if (el.tagName == "A") {
            flag = false;

            if (el.protocol == "javascript:") {
                execScript(el.href, "javascript");

                // A window.event.returnValue=false is performed so that the 
                // default action does not happen - which in case of an HREF
                // will be navigating to a link. 
                window.event.returnValue = false;
            }
        }
        else {
            el = el.parentElement;
        }
    }
} // end OnClickHandler()

/// <summary>
///	Shortcut for document.getElementById() 
/// </summary>
function $(element, delimiter) {
    var el;
    if (typeof element == 'string') {
        //First attempt with our prefix.
        if (delimiter == null) {
            el = document.getElementById("ctl00_ContentPlaceHolder1_" + element);
        }
        else {
            el = document.getElementById("ctl00" + delimiter + "ContentPlaceHolder1" + delimiter + element);
        }

        if (el == null) {
            //Otherweise try without the prefix.
            el = document.getElementById(element);
        }

        return el;
    }
    else {
        return element;
    }
}

function InnerText$(elementID, text) {
    if (document.all) {
        $(elementID).innerText = text;
    }
    else {
        $(elementID).textContent = text;
    }
}


function $$(element) {
    if (typeof element == 'string') {
        return document.getElementById(element);
    }
    else {
        return element;
    }
}


var hideResponseTimeout = 0;



// Show/hide the specified element.
function ToggleDisplay(id) {
    ctrl = document.getElementById(id);
    if (ctrl == null) return;

    ctrl.style.display = (ctrl.style.display == "none") ? "" : "none";
}

function EnableAllLinks() {
    var anchors = document.getElementsByTagName("A");

    for (var i = 0; i < anchors.length; i++) {
        if (anchors[i].onclickTmp != null) {
            anchors[i].onclick = anchors[i].onclickTmp; // == null? new Function("return true") : anchors[i].onclickTmp;
        }

        anchors[i].disabled = anchors[i].disabledPrev == null ? false : anchors[i].disabledPrev;

        //Clear the temp attributes
        anchors[i].onclickTmp = null;
        anchors[i].disabledPrev == null;
    }
}

function DisableAllLinks(exceptThisOne) {
    var anchors = document.getElementsByTagName("A");

    for (var i = 0; i < anchors.length; i++) {
        if (anchors[i] != exceptThisOne && anchors[i].onclickTmp == null) {
            anchors[i].onclickTmp = anchors[i].onclick;
            anchors[i].onclick = new Function("return false");
            anchors[i].disabledPrev = anchors[i].disabled;
            anchors[i].disabled = true;
        }
    }
}



/******************************************************************
* EVENT HANDLERS
******************************************************************/
Events = {};
Events.AddHandler = function (element, eventName, handler) {
    if (element.addEventListener) {
        element.addEventListener(eventName, handler, false);
    }
    else if (element.attachEvent) {
        element.attachEvent("on" + eventName, handler);
    }
}

Events.RemoveHandler = function (element, eventName, handler) {
    if (element.removeEventListener) {
        element.removeEventListener(eventName, handler, false);
    }
    else if (element.detachEvent) {
        element.detachEvent("on" + eventName, handler);
    }
}

/******************************************************************
* BROWSER DETECTION
******************************************************************/

Browser = {};
Browser.Name = "";
Browser.Version = 0;

if (navigator.userAgent.indexOf("MSIE") > -1) {
    Browser.Name = "Internet Explorer";
    Browser.Version = parseFloat(navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1]);
}
else if (navigator.userAgent.indexOf("Firefox/") > -1) {
    Browser.Name = "Firefox";
    Browser.Version = parseFloat(navigator.userAgent.match(/ Firefox\/(\d+\.\d+)/)[1]);
}
else if (navigator.userAgent.indexOf("Netscape/") > -1) {
    Browser.Name = "Netscape";
    Browser.Version = parseFloat(navigator.userAgent.match(/ Netscape\/(\d+\.\d+)/)[1]);
}
else if (navigator.userAgent.indexOf("Safari/") > -1) {
    Browser.Name = "Safari";
    Browser.Version = parseFloat(navigator.userAgent.match(/ Safari\/(\d+\.\d+)/)[1]);
}
else if (navigator.userAgent.indexOf("Opera/") > -1) {
    Browser.Name = "Opera";
    Browser.Version = parseFloat(navigator.appVersion)
}

/******************************************************************
* ACCESSIBILITY
******************************************************************/
/// <summary>
/// Makes the font larger
/// </summary>
function IncreaseFontSize() {
    var active = this.GetFontSize();

    switch (active) {
        case 'small':
            SetFontSize('medium');
            break;

        case 'medium':
            SetFontSize('large');
            break;

        case 'large':
            break;

        default:
            SetFontSize('small');
            break;
    }
}

/// <summary>
/// Makes the font smaller
/// </summary>
function DecreaseFontSize() {
    var active = GetFontSize();

    switch (active) {
        case 'large':
            SetFontSize('medium');
            break;

        case 'medium':
            SetFontSize('small');
            break;

        case 'small':
            break;

        default:
            SetFontSize('small');
            break;
    }
}


/// <summary>
/// Returns the current font size.
/// </summary>
function GetFontSize() {
    var i, a;
    for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
        var title = a.getAttribute("title");

        if (a.getAttribute("rel").indexOf("style") != -1 &&
			(title == "small" || title == "medium" || title == "large") &&
			!a.disabled) {
            return a.getAttribute("title");
        }
    }

    return null;
}

/// <summary>
/// Sets the current font size.
/// </summary>
function SetFontSize(title) {
    var i, a, main;

    if (title == null) {
        title = "small";
    }

    for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
        var checkTitle = a.getAttribute("title");

        if (a.getAttribute("rel").indexOf("style") != -1 &&
			(checkTitle == "small" || checkTitle == "medium" || checkTitle == "large")) {
            a.disabled = (a.getAttribute("title") != title);
        }
    }
}


/******************************************************************
* VALIDATIONS
******************************************************************/
// Show message banner.
function ShowMessageBanner(msg) {
    //window.parent.document.getElementById("ResponseBannerType").innerHTML = "Notification";
    ShowMessage("Website Notification", msg, 0, "ResponseBannerInfo", true);
}

// Show an information message.
function ShowInfo(msg, timeoutSecs) {
    if (timeoutSecs == null) {
        timeoutSecs = 20;
    }
    //window.parent.document.getElementById("ResponseBannerType").innerHTML = "Info";
    ShowMessage(msg, "", timeoutSecs, "ResponseBannerInfo", false);
}

// Show an information message.
function ShowInfoMessageBox(msg, timeoutSecs) {
    if (timeoutSecs == null) {
        timeoutSecs = 20;
    }

    ShowMessage(msg, "", timeoutSecs, "ResponseBannerInfo", false);
    alert(msg);
}

// Show a warning message.
function ShowWarning(msg, timeoutSecs) {
    if (timeoutSecs == null) {
        timeoutSecs = 20;
    }

    ShowMessage(msg, "", timeoutSecs, "ResponseBannerWarning", false);
}

// Show the list of validation errors (if any).
function ShowValidationErrors() {
    errorList = ErrorMessages.getValidationErrors();
    errorCount = errorList.count();

    // Added for making the NOTIFICATION MESSAGE BANNER visible
    var responseType = document.getElementById("ResponseBannerText").innerHTML.replace(/^\s+|\s+$/g, '').toLowerCase(); ;// null; //window.parent.document.getElementById("ResponseBannerType").innerHTML;
    
    if (errorCount == 0) {
        if (responseType.indexOf("notification") > -1)
            return;
        HideMessage();
    }
    else {
        ShowErrors(errorList);
    }    
}

// Show the list of error messages.
function ShowErrors(errorList) {
    if (errorCount == 0) {
        errorCount = errorList.length;
    }

    //window.parent.document.getElementById("ResponseBannerType").innerHTML = "Errors";

    // Set the heading depending on the number od errors.
    if (errorCount == 1) {
        heading = "The following error was found:"
    }
    else {
        heading = "The following " + errorCount + " errors were found:"
    }

    try {
        // Get the HTML for the errors.
        content = errorList.toHtml();
        // Call the generic message handler.	    
        ShowMessage(heading, content, 0, "ResponseBannerError", true)
    }
    catch (e) {
        var content = "";
        for (index = 0; index < errorCount; index++) {
            content += "<li>" + errorList[index] + "</li>";
        }
        content += "<br>";
        // Call the generic message handler.	    
        ShowMessage(heading, content, 0, "ResponseBannerError", true)
    }
}

function ShowError(msg, timeoutSecs) {
    if (timeoutSecs == null) {
        timeoutSecs = 20;
    }

    ShowMessage(msg, "", timeoutSecs, "ResponseBannerError", false);
}

// Generic handler to display messages.
function ShowMessage(heading, body, timeoutSecs, className, allowClose) {
    // Get the UI objects.
    var win = window.parent;
        
    if (document.getElementById("ResponseBannerTD")) {
        win = window;
    }

    // Reset the timer.
    win.clearTimeout(win.hideResponseTimeout);

    var responseBannerTD = win.document.getElementById("ResponseBannerTD");
    var responseBannerBox = win.document.getElementById("ResponseBannerBox");
    var responseBannerText = win.document.getElementById("ResponseBannerText");
    var responseBannerClose = win.document.getElementById("ctl00_ResponseBar1_ResponseBannerClose");
    var responseBannerBody = win.document.getElementById("ResponseBannerBody");
    var type = null;// win.document.getElementById("ResponseBannerType").innerHTML;
    var isSiteNotification = (type == "Notification");
    // Set the message class.
    responseBannerBox.className = className;

    //Set the icon
    var ico = win.document.getElementById("ResponseBannerIcon");
    ico.className = "Icon";

    // Set the heading text.
    if (heading == "" || isSiteNotification) {
        responseBannerText.style.display = "none";
    }
    else {
        responseBannerText.innerHTML = heading;
        responseBannerText.style.display = "inline";
    }
    

    // Set the content and display/hide the content area.
    if (body == "") {
        responseBannerBody.innerHTML = "";
        responseBannerBody.style.display = "none";
    }
    else {
        responseBannerBody.innerHTML = body;
        responseBannerBody.style.display = "block";
    }

    // Show/Hide the close button.
    if (allowClose) {
        responseBannerClose.style.display = "";
    }
    else {
        responseBannerClose.style.display = "none";
    }

    // Show the message box.
    responseBannerTD.style.display = "";

    // Set to hide in <timeout> seconds
    if (timeoutSecs > 0) {
        win.hideResponseTimeout = win.setTimeout("hideInfo()", ((timeoutSecs > 10) ? timeoutSecs : 10) * 1000);
    }

    if (Browser.Name == "Firefox" || Browser.Name == "Netscape") {
        PerformLayout();
    }
}

function HideMessage() {
    var responseBanner = document.getElementById("ResponseBannerTD");
    if (responseBanner == null) {
        var responseBanner = window.parent.document.getElementById("ResponseBannerTD");
    }
    responseBanner.style.display = "none";

    if (Browser.Name == "Firefox" || Browser.Name == "Netscape") {
        PerformLayout();
    }
}

/******************************************************************
* STRING BUILDER
*****************************************************************/
// Initialize the string builder.
function StringBuilder(value) {
    this.strings = [];
    this.append(value);
}

// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value) {
    if (value) {
        this.strings.push(value);
    }
}

// Clears the string buffer.
StringBuilder.prototype.clear = function () {
    this.strings = [];
}

// Converts this instance to a string.
StringBuilder.prototype.toString = function () {
    return this.strings.join("");
}

/*** Validation ***/
function ValidatePage(groupName) {
    if (typeof (Page_ClientValidate) == "undefined") {
        isValid = true;
    }
    else {
        isValid = Page_ClientValidate(groupName);
    }

    ShowValidationErrors();

    return isValid;
}

// Helper function to get the value of a control.
function GetControlValue(id) {
    if (id == "") return null;

    var ctrl = $(id);
    if (ctrl == null) return null;

    return ctrl.value;
}

/*** ErrorMessages ***/

// Initialize the error messages.
function ErrorMessages() {
    this.errorList = [];
}

// Add an error with a message and control name.
ErrorMessages.prototype.add = function (message, controlName) {
    var item = {};
    item.message = message;
    item.controlName = controlName;

    this.errorList.push(item);
}

// Clear all the errors.    
ErrorMessages.prototype.clear = function () {
    this.errorList = [];
}

// Get the error at the specified position.    
ErrorMessages.prototype.getItem = function (index) {
    return this.errorList[index];
}

// Count the number of errors.    
ErrorMessages.prototype.count = function () {
    return this.errorList.length;
}

// Convert the errors to HTML (bullet list).
ErrorMessages.prototype.toHtml = function () {
    builder = new StringBuilder();
    builder.append("<ul>");

    for (index in this.errorList) {
        errorItem = this.errorList[index];
        if (errorItem.controlName == "") {
            formatMsg = errorItem.message;
        }
        else {
            formatMsg = "<a href=\"#\" onclick=\"setControlFocus('" + errorItem.controlName + "');\">" + errorItem.message + "</a>";
        }

        builder.append("<li>" + formatMsg + "</li>");
    }

    builder.append("</ul>");
    content = builder.toString();

    return content;
}

// Parse the error string and return an array of errors.
ErrorMessages.parse = function (errorString) {
    errorList = new ErrorMessages();

    itemArray = errorString.split(";");
    for (index in itemArray) {
        valueArray = itemArray[index].split(":");

        errorList.add(valueArray[0], valueArray[1]);
    }

    return errorList;
}

// Return an array of errors from the page validations that have failed.
ErrorMessages.getValidationErrors = function () {
    errors = new ErrorMessages();
    if (typeof (Page_Validators) == "object") {
        for (index in Page_Validators) {
            validator = Page_Validators[index];

            if (!validator.isvalid) {
                controlName = typeof (validator.controltovalidate) == "undefined" ? "" : validator.controltovalidate;
                message = (typeof (validator.errormessage) == "undefined") ? "" : validator.errormessage;
                if (message == "") message = "Unknown Error!";

                errors.add(message, controlName);
            }
        }
    }

    return errors;
}

function OpenWindow(uri, title, width, height, dontShow) {

    var win = GetTopmostWindow();
    var radWindowManager = win.GetRadWindowManager();
    var dialogWindow = radWindowManager.GetWindowByName("DialogWindow");
    var iframe = dialogWindow.GetContentFrame();
    iframe.style.visibility = "hidden";
    if (dontShow == false || dontShow == null) {
        dialogWindow.Show();
    }
    
    
    dialogWindow.SetTitle(title);

    if (width != null) {
        dialogWindow.SetWidth(width);
    }

    if (height != null) {
        //Check for out of range values
        if (height > window.parent.document.body.offsetHeight) {
            height = window.parent.document.body.offsetHeight - 20;
        }

        dialogWindow.SetHeight(height);
    }

    dialogWindow.Center();

    iframe.src = uri;
    iframe.style.visibility = "visible";
    //$(iframe).load = (function () {
    //    iframe.style.visibility = "visible";
    //});
    return dialogWindow;
}

//-------------------------------------------------------------------------------------------//
//--------------------------------SEARCH SCRIPTS---------------------------------------------//
//-------------------------------------------------------------------------------------------//

function ShowWindowForShareSearch() {
    var radWindowManager = window.parent.GetRadWindowManager();

    var dialogWindow = radWindowManager.GetWindowByName("DialogWindow");

    dialogWindow.Show();

    dialogWindow.SetWidth("650px");
    dialogWindow.SetHeight("500px");

    dialogWindow.Center();
}

/// <summary>
/// Will return an instrument code to the user via the function specified in param resultFunction this function is called from the default page
/// </summary>
/// <param name="searchCode">the Code to base the search on</param>
/// <param name="searchFilter">This paramater will filter on specific instrument types options are : Share, Warrant, SSF or All</param>
/// <param name="selectedCallbackFunction">The function to call on the parent page with the result. This function will need to accept the alpha code and instrument type.</param>
/// <returns></returns>
function OpenInstrumentSearchWindow(searchCode, searchFilter, selectedCallbackFunction, autoMatchOnAllTypes) {
    var dialog = OpenWindow(path("~/Instruments/InstrumentSearch.aspx?Code={0}&InstrumentTypes={1}&AutoMatchOnAllTypes={2}", searchCode, searchFilter, autoMatchOnAllTypes ? "1" : "0"),
							"Instrument Loading",
							"650px",
							"500px",
							true);
    dialog.Argument = null;
    dialog.OnClientClose = function (dlg) {
        selectedCallbackFunction(dlg);
        ResetDialogOnclose(dlg);
    };
    return dialog;
}

/// <summary>
/// Will change the iframe page to a specific instrument detail page
/// </summary>
/// <param name="instrumentCode">the instrument alpha code to pass to page</param>
/// <param name="instrumentType">share/warrant/ssf</param>
function navigateToInstrument(instrumentCode, instrumentType) {
    GoToUrl(path("~/Instruments/{0}Details.aspx?Code={1}", instrumentType, instrumentCode, "650px", "500px"));
}

//-------------------------------------------------------------------------------------------//
//--------------------------------HEADER SCRIPTS---------------------------------------------//
//-------------------------------------------------------------------------------------------//
/// <summary>
/// Hides the Info Message Response TD
/// </summary>
function hideInfo() {
    var responseBanner = document.getElementById("ResponseBannerTD");
    responseBanner.style.display = "none";
}

/// <summary>
/// Handles the RadMenuItem click event. 
/// The URL for each menu item is stored in the 
/// value field of the menu item.
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs">Rad Menu EventArgs</param>
function ISLMenu_ItemClick(sender, eventArgs) {
    if (eventArgs.Item.Value != null) {
        if (navigator.userAgent.match(/iPad/i)) {
            NavigateTo("~/" + eventArgs.Item.Value);
        }
        else {
            switch (eventArgs.Item.Text) {
                case "Online Banking":
                case "Asset Management":
                    NavigateTo(eventArgs.Item.Value)
                    break;

                default:
                    document.getElementById("applicationContent").src = eventArgs.Item.Value;
            }
        }
    }
}

function setControlFocus(ctrlName) {
    var ctrl;
    if (window.frames["applicationContent"] != null) {
        ctrl = window.frames["applicationContent"].document.getElementById(ctrlName);
    }
    else {
        ctrl = document.getElementById(ctrlName);
    }

    if (ctrl != null) {
        ctrl.focus();
    }
}

/**********************************
* Generic NEWS Pages and controls
**********************************/
function openLatestNewsWindow(id, code) {
    OpenWindow(path("~/Research/Popups/View.aspx?item={0}&typeCode={1}", id, code), "Latest News", "650px", "500px");
}


/**********************************
* Generic SENS Pages and controls
**********************************/
function openSENSWindow(id) {
    OpenWindow(path("~/SENS/Popups/ViewSENS.aspx?SENSID={0}", id), "SENS Announcement", "650px", "500px");
}

/**********************************
* Generic SENS Pages and controls
**********************************/
function openMKCWindow(id) {
    OpenWindow(path("~/MarketCommentary/Popups/View.aspx?ID={0}", id), "Market Commentary", "650px", "500px");
}

/**********************************
* Print Functionality
**********************************/
function Print_PrintPage() {
    try {
        //The page being printed
        var page = document.getElementById("PageAreaExMargins");

        //The IFRAME element		
        var iframe_el = document.getElementById("Print_PrintIFrame");

        //The IFRAME frame
        var iframe = window.frames["Print_PrintIFrame"];

        //The IFRAME's document object
        var doc = iframe.document;

        //show the IFRAME
        iframe_el.style.visibility = "visible";

        //Set the document's HTML
        doc.body.innerHTML = page.innerHTML;
        iframe.window.document.head = document.head;
        //Ensure the correct length
        var mainDiv = document.getElementById("PageAreaExMargins");
        var mainDiv_print = doc.getElementById("PageAreaExMargins");

        //mainDiv_print.style.width = mainDiv.offsetWidth;

        //Print
        iframe.window.focus();
        iframe.window.print();

        //Hide the IFRAME
        iframe_el.style.visibility = "hidden";

        //Clear
        page = null;
        iframe_el = null;
        iframe = null;
        doc = null;

        CloseRadWindow(null);
        return false;
    }
    catch (ex) {
        return false;
    }
}

function Print_pagePrinter_onload() {
    var doc = window.frames["Print_PrintIFrame"].document;
    //Add all applicable stylesheets
    for (var i = 0; i < document.styleSheets.length; i++) {
        var href = document.styleSheets[i].href;
        if (href != "") {
            if (document.createStyleSheet) {
                doc.createStyleSheet(href);
            }
            else {
                var newSS = document.createElement('link');
                newSS.rel = 'stylesheet';
                newSS.type = 'text/css';
                newSS.href = href;
                doc.getElementsByTagName("head")[0].appendChild(newSS);
            }
        }
    }

    doc.title = document.title;
    
    doc = null;
    
    //document.getElementById("ctl00_printButton_iconImage").focus();
}

function Print_SetPortrait(isPortrait) {
    document.getElementById("page").className = isPortrait ? "Print_Portrait" : "Print_Landscape";
    document.getElementById("ctl00_Print_Container").className = isPortrait ? "Print_Container_Portrait" : "Print_Container_Landscape";
    var maxWidth = isPortrait ? 906 : null;
    SetElementWidths(maxWidth);
}





//v1.7
// Flash Player Version Detection
// Detect Client Browser type
// Copyright 2005-2007 Adobe Systems Incorporated.  All rights reserved.
var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function ControlVersion() {
    var version;
    var axo;
    var e;

    // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry

    try {
        // version will be set for 7.X or greater players
        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
        version = axo.GetVariable("$version");
    } catch (e) {
    }

    if (!version) {
        try {
            // version will be set for 6.X players only
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");

            // installed player is some revision of 6.0
            // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29,
            // so we have to be careful. 

            // default to the first public version
            version = "WIN 6,0,21,0";

            // throws if AllowScripAccess does not exist (introduced in 6.0r47)		
            axo.AllowScriptAccess = "always";

            // safe to call for 6.0r47 or greater
            version = axo.GetVariable("$version");

        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 4.X or 5.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = axo.GetVariable("$version");
        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 3.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3");
            version = "WIN 3,0,18,0";
        } catch (e) {
        }
    }

    if (!version) {
        try {
            // version will be set for 2.X player
            axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            version = "WIN 2,0,0,11";
        } catch (e) {
            version = -1;
        }
    }

    return version;
}

// JavaScript helper required to detect Flash Player PlugIn version information
function GetSwfVer() {
    // NS/Opera version >= 3 check for Flash plugin in plugin array
    var flashVer = -1;

    if (navigator.plugins != null && navigator.plugins.length > 0) {
        if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
            var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
            var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
            var descArray = flashDescription.split(" ");
            var tempArrayMajor = descArray[2].split(".");
            var versionMajor = tempArrayMajor[0];
            var versionMinor = tempArrayMajor[1];
            var versionRevision = descArray[3];
            if (versionRevision == "") {
                versionRevision = descArray[4];
            }
            if (versionRevision[0] == "d") {
                versionRevision = versionRevision.substring(1);
            } else if (versionRevision[0] == "r") {
                versionRevision = versionRevision.substring(1);
                if (versionRevision.indexOf("d") > 0) {
                    versionRevision = versionRevision.substring(0, versionRevision.indexOf("d"));
                }
            }
            var flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
        }
    }
    // MSN/WebTV 2.6 supports Flash 4
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
    // WebTV 2.5 supports Flash 3
    else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
    // older WebTV supports Flash 2
    else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
    else if (isIE && isWin && !isOpera) {
        flashVer = ControlVersion();
    }
    return flashVer;
}

// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) {
    versionStr = GetSwfVer();
    if (versionStr == -1) {
        return false;
    } else if (versionStr != 0) {
        if (isIE && isWin && !isOpera) {
            // Given "WIN 2,0,0,11"
            tempArray = versionStr.split(" "); 	// ["WIN", "2,0,0,11"]
            tempString = tempArray[1]; 		// "2,0,0,11"
            versionArray = tempString.split(","); // ['2', '0', '0', '11']
        } else {
            versionArray = versionStr.split(".");
        }
        var versionMajor = versionArray[0];
        var versionMinor = versionArray[1];
        var versionRevision = versionArray[2];

        // is the major.revision >= requested major.revision AND the minor version >= requested minor
        if (versionMajor > parseFloat(reqMajorVer)) {
            return true;
        } else if (versionMajor == parseFloat(reqMajorVer)) {
            if (versionMinor > parseFloat(reqMinorVer))
                return true;
            else if (versionMinor == parseFloat(reqMinorVer)) {
                if (versionRevision >= parseFloat(reqRevision))
                    return true;
            }
        }
        return false;
    }
}

function AC_AddExtension(src, ext) {
    if (src.indexOf('?') != -1)
        return src.replace(/\?/, ext + '?');
    else
        return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) {
    var str = '';
    if (isIE && isWin && !isOpera) {
        str += '<object ';
        for (var i in objAttrs) {
            str += i + '="' + objAttrs[i] + '" ';
        }
        str += '>';
        for (var i in params) {
            str += '<param name="' + i + '" value="' + params[i] + '" /> ';
        }
        str += '</object>';
    }
    else {
        str += '<embed ';
        for (var i in embedAttrs) {
            str += i + '="' + embedAttrs[i] + '" ';
        }
        str += '> </embed>';
    }

    document.write(str);
}

function AC_FL_RunContent() {
    var ret =
    AC_GetArgs
    (arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
    AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent() {
    var ret =
    AC_GetArgs
    (arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
    AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_GetArgs(args, ext, srcParamName, classid, mimeType) {
    var ret = new Object();
    ret.embedAttrs = new Object();
    ret.params = new Object();
    ret.objAttrs = new Object();
    for (var i = 0; i < args.length; i = i + 2) {
        var currArg = args[i].toLowerCase();

        switch (currArg) {
            case "classid":
                break;
            case "pluginspage":
                ret.embedAttrs[args[i]] = args[i + 1];
                break;
            case "src":
            case "movie":
                args[i + 1] = AC_AddExtension(args[i + 1], ext);
                ret.embedAttrs["src"] = args[i + 1];
                ret.params[srcParamName] = args[i + 1];
                break;
            case "onafterupdate":
            case "onbeforeupdate":
            case "onblur":
            case "oncellchange":
            case "onclick":
            case "ondblClick":
            case "ondrag":
            case "ondragend":
            case "ondragenter":
            case "ondragleave":
            case "ondragover":
            case "ondrop":
            case "onfinish":
            case "onfocus":
            case "onhelp":
            case "onmousedown":
            case "onmouseup":
            case "onmouseover":
            case "onmousemove":
            case "onmouseout":
            case "onkeypress":
            case "onkeydown":
            case "onkeyup":
            case "onload":
            case "onlosecapture":
            case "onpropertychange":
            case "onreadystatechange":
            case "onrowsdelete":
            case "onrowenter":
            case "onrowexit":
            case "onrowsinserted":
            case "onstart":
            case "onscroll":
            case "onbeforeeditfocus":
            case "onactivate":
            case "onbeforedeactivate":
            case "ondeactivate":
            case "type":
            case "codebase":
            case "id":
                ret.objAttrs[args[i]] = args[i + 1];
                break;
            case "width":
            case "height":
            case "align":
            case "vspace":
            case "hspace":
            case "class":
            case "title":
            case "accesskey":
            case "name":
            case "tabindex":
                ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i + 1];
                break;
            default:
                ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i + 1];
        }
    }
    ret.objAttrs["classid"] = classid;
    if (mimeType) ret.embedAttrs["type"] = mimeType;
    return ret;
}
function openNewWindow(URLtoOpen, windowName, windowFeatures) {
    newWindow = window.open(URLtoOpen, windowName, windowFeatures);
}

function AJAX_OnError(sender, e) {
    //    var msg = "There was a problem processing your request. Please try again, or if this problem reoccurs, please " +
    //              "contact the system administrator with the following information:\r\n" +
    //              "Status code: " + e.Status + 
    //              "\r\nResponseText: " + e.ResponseText +
    //              "\r\nResponseHeaders: " + e.ResponseHeaders;
    //    alert(msg);
}

function GoToUrl(url) {

    if (navigator.userAgent.match(/iPad/i)) {
        NavigateTo(url);
    }
    else {
        var win = GetTopmostWindow();

        win.document.getElementById("applicationContent").src = path(url);
    }
}

function ShowDiv(divId, txtObj) {
    if (txtObj.title == "Open") {
        var divEle = document.getElementById('div' + divId);
        var imgHeader = document.getElementById('imgHeader' + divId);
        var lnk = document.getElementById('lnk' + divId);
        divEle.style.visibility = "visible";
        divEle.style.display = "block"
        lnk.innerText = "Close";
        lnk.textContent = "Close";
        imgHeader.src = "../Images/Icons/upArrow.gif";
        imgHeader.alt = "Close";
        txtObj.title = "Close";

    }
    else {
        var divEle = document.getElementById('div' + divId);
        var imgHeader = document.getElementById('imgHeader' + divId);
        var lnk = document.getElementById('lnk' + divId);
        divEle.style.visibility = "hidden";
        divEle.style.display = "none"
        lnk.innerText = "Open";
        lnk.textContent = "Open";
        imgHeader.src = "../Images/Icons/downArrow.gif";
        imgHeader.alt = "Open";
        txtObj.title = "Open";
    }
    return 0;

}
/**********************************
* FastESP
**********************************/
function FilterSearch(searchPage, searchCode) {
    var url = path(searchPage);
    url += getqueryStringPrefix() + "Query=" + searchCode.replace("&", "%26");

    if (Browser.Name == "Firefox" || Browser.Name == "Safari") {
        window.location = url
    }
    else {
        window.navigate(url);
    }
    return false;
}

//Used by AJAX Control Toolkit Autocomplete
function loadCompany(source, eventArgs) {
    var companyAndAlpha = eventArgs.get_text();
    var startAlpha = companyAndAlpha.lastIndexOf("(") + 1;
    var endAlpha = companyAndAlpha.lastIndexOf(")");

    NavigateTo("~/Instruments/SearchResult.aspx" + getqueryStringPrefix() + "Code=" + companyAndAlpha.substring(startAlpha, endAlpha) + "&Type=Share");
    return true;
}

//Investec Daily View
function openInvestecDailyViewWindow(id, code) {
    OpenWindow(path("~/Research/Popups/View.aspx?item={0}&typeCode={1}", id, code), "Investec Daily View", "650px", "500px");
}
$.urlParam = function (name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.search.substring(1));
    if (!results) {
        return 0;
    }
    return results[1] || 0;
}
String.prototype.format = function () {
    var returnValue = this;
    if (arguments != null && arguments.length > 0)
        for (var index = 0; index < arguments.length; index++)
            if (arguments[index] != null)
                returnValue = returnValue.replace('{' + index + '}', arguments[index].toString());
    
    return returnValue;
}
function getqueryStringPrefix() {
    var queryString = window.top.location.search.substring(1);
    var area;
    if (queryString.startsWith("A=C") || queryString.startsWith("a=c")) {
        area = "C";
    }
    else {
        area = "R";
    }

    var prefix = "?";
    if (area != 0)
        prefix = "?A=" + area + "&";

    return prefix;
}
