﻿var GDprevBackColor;
var GDprevBorderColor;
var TheSplashScreen;
var TheSplashMessage;
var TheSplashMask;
var messageElem;
var messageElemErrorStyle = "ErrorMessage";
var messageElemStyle = "Message";
var _POSTBACKCOUNTER = 0;
var __oldDoPostBack;
var TheProgressTime = 1; //3 seconds
var TheTimeOut = 0;
var GDBodyObj;
var GDDIVSCROLLPOSOBJ;
var GDSCROLLDIV;
var intSCROLLPOS = 0;
var wnd_event = false;

// Hook up Application event handlers.
if (typeof (Sys) !== 'undefined') {
    var app = Sys.Application;
    app.add_load(ApplicationLoad);
    app.add_init(ApplicationInit);
    app.add_unload(ApplicationUnload);
}

function ApplicationInit(sender) {

    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if (!prm.get_isInAsyncPostBack()) {
        prm.add_beginRequest(beginRequestHandler);
        prm.add_endRequest(endRequestHandler);
        prm.add_initializeRequest(CheckStatus);
    }
}

function ApplicationLoad(sender, args) {
    TheSplashScreen = getObjectById('splashScreen');
    TheSplashMessage = getObjectById('splashMessage');
    TheSplashMask = getObjectById("splashMask");
    messageElem = getObjectById(masterPrefix + "lblMessage");

    _POSTBACKCOUNTER = 0;
    attachClassEvents();
    if (typeof (TheSplashScreen) != "undefined") changeObjectVisibility('splashScreen', 'hidden');
}

function ApplicationUnload(sender) {
    with (Sys.WebForms.PageRequestManager.getInstance()) {
        remove_beginRequest(beginRequestHandler);
        remove_endRequest(endRequestHandler);
    }
}

function CheckStatus(sender, args) {
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    if (prm.get_isInAsyncPostBack()) args.set_cancel(true);  //prm.abortPostBack();
    //else if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) args.set_cancel(true);
}

function beginRequestHandler(sender, args) {
    if (typeof (TheSplashScreen) != "undefined") changeObjectVisibility('splashScreen', 'hidden');
    StartProgressTimer();
    _POSTBACKCOUNTER = 0;
}

function endRequestHandler(sender, args) {
    StopProgressTimer();
    if (typeof (TheSplashScreen) != "undefined") {
        changeObjectVisibility('splashScreen', 'hidden');
        changeObjectVisibility('splashMask', 'hidden');
    }
    if ((args.get_error() != undefined)) {
        if (typeof (messageElem) != "undefined") {
            var errorMessage;
            if (args.get_response().get_statusCode() == '200')
            { errorMessage = args.get_error().message; }
            else // Error occurred somewhere other than the server page.
            { errorMessage = 'An unspecified error occurred. '; }

            args.set_errorHandled(true);
            messageElem.className = messageElemErrorStyle;
            messageElem.innerHTML = errorMessage;
            alert(errorMessage);
        }
    } else {
        var dataItems = args.get_dataItems();
        messageElem.className = messageElemStyle;
        if (dataItems[messageElem.id] == undefined) messageElem.innerHTML = ""; else messageElem.innerHTML = dataItems[messageElem.id];
    }
}

function StopProgressTimer()
{ window.clearTimeout(TheTimeOut); TheTimeOut = 0; }

function StartProgressTimer() {
    if (TheTimeOut == 0) TheTimeOut = setTimeout(WakeUpProgress, (TheProgressTime * 1000)); //sleep for time determined by user role (3 or 30 seconds)
}

function WakeUpProgress() {
    StopProgressTimer();
    if (typeof (TheSplashScreen) != "undefined") changeObjectVisibility('splashScreen', 'visible');
}

function BeforeSubmit() {   //if (typeof(ValidatorOnSubmit) == "function" && ValidatorOnSubmit() == false) return;
    ++_POSTBACKCOUNTER; // record already posted
    if (_POSTBACKCOUNTER == 1) //ignore other request
    { hideIssues(); if (typeof (TheSplashScreen) != "undefined") changeObjectVisibility('splashScreen', 'visible'); }
    else
    { if (typeof (TheSplashMessage) != "undefined") TheSplashMessage.innerText = "Submit is in progress. " + _POSTBACKCOUNTER.toString(); }
    return (_POSTBACKCOUNTER == 1);
}

function cancelClick() {
    StopProgressTimer();
    _POSTBACKCOUNTER = 0;
    if (typeof (TheSplashScreen) != "undefined") {
        changeObjectVisibility('splashScreen', 'hidden');
        changeObjectVisibility('splashMask', 'hidden');
    }
}

function hideIssues() {
    changeObjectVisibility('splashMask', 'visible');
    /*
    if (!IE7Up()) {
    //ie always shows SELECT boxes with a z-order higer than all other objects. Period.
    for(var i = 0; i < document.forms.length; i++) {
    for(var e = 0; e < document.forms[i].length; e++){
    if(document.forms[i].elements[e].tagName == "SELECT") {
    document.forms[i].elements[e].style.visibility="hidden";
    }
    }
    }
    }
    */
}

function tb_Focus(mEvent) {
    var evt = mEvent || window.event; // event object
    var el = evt.target || window.event.srcElement; // event target
    if (typeof (el) != "undefined") {
        if (!el.readOnly) {
            GDprevBackColor = el.style.color;
            GDprevBorderColor = el.style.borderColor;
            el.style.backgroundColor = "#c4ffae";
            el.style.borderColor = "#228b22";
        }
    }
}

function tb_Blur(mEvent) {
    var evt = mEvent || window.event; // event object
    var el = evt.target || window.event.srcElement; // event target
    if (typeof (GDprevBackColor) != "undefined" && typeof (el) != "undefined") {
        if (!el.readOnly) {
            el.style.backgroundColor = GDprevBackColor;
            el.style.borderColor = GDprevBorderColor;
        }
    }
}

function On_Focus(obj)
{ tb_Focus(); }

function On_Blur(obj)
{ tb_Blur(); }

function attachClassEvents() {
    var arrElements = new Array();
    var arrClasses = new Array();
    var arrElements;
    arrClasses = ["TextBoxRequired", "TextBox", "ListBox", "ListBoxRequired"];
    for (var j = 0; j < arrClasses.length; j++) {
        arrElements = getElementsByClassName(document, "*", arrClasses[j]);
        for (var i = 0; i < arrElements.length; i++) {
            oElement = arrElements[i];
            //old items may have On_Focus(this);On_Blur(this)
            addEvent(arrElements[i], "focus", tb_Focus);
            addEvent(arrElements[i], "blur", tb_Blur);
        }
    }
}
/*
Written by Jonathan Snook, http://www.snook.ca/jonathan
Add-ons by Robert Nyman, http://www.robertnyman.com
*/

function getElementsByClassName(oElm, strTagName, strClassName) {
    var arrElements = (strTagName == "*" && oElm.all) ? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/-/g, "\-");
    var oRegExp = new RegExp("(^|\s)" + strClassName + "(\s|$)");
    var oElement;
    for (var i = 0; i < arrElements.length; i++) {
        oElement = arrElements[i];
        if (oRegExp.test(oElement.className)) {
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}

function getObjectById(objectId) {
    // cross-browser function to get an object's style object given its id
    if (document.getElementById && document.getElementById(objectId)) {
        // W3C DOM
        return document.getElementById(objectId);
    } else if (document.all && document.all(objectId)) {
        // MSIE 4 DOM
        return document.all(objectId);
    } else {
        return false;
    }
} // getStyleObject

function getStyleObject(objectId) {
    // cross-browser function to get an object's style object given its id
    if (document.getElementById && document.getElementById(objectId)) {
        // W3C DOM
        return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
        // MSIE 4 DOM
        return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
        // NN 4 DOM.. note: this won't find nested layers
        return document.layers[objectId];
    } else {
        return false;
    }
} // getStyleObject

function changeObjectVisibility(objectId, newVisibility) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if (styleObject) {
        styleObject.visibility = newVisibility;
        if (newVisibility == "visible") styleObject.display = "block"; else styleObject.display = "none";
        return true;
    } else {
        // we couldn't find the object, so we can't change its visibility
        return false;
    }
} // changeObjectVisibility

function toggleObjectVisibilityInline(objectId) {
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if (styleObject) {
        if (styleObject.visibility == "visible" || styleObject.visibility == "") {
            styleObject.visibility = "hidden"; styleObject.display = "none"; styleObject.position = "absolute";
        } else { styleObject.visibility = "visible"; styleObject.display = "inline"; styleObject.position = "relative"; }
        return true;
    } else {
        // we couldn't find the object, so we can't change its visibility
        return false;
    }
} // toggleObjectVisibilityInline

function OpenModal(url, caption) {
    var ht; var wd;
    var a = getObjectById("ipageframe");
    if ((a != null) && (typeof (a.tagName) != "undefined") && (a.tagName.toUpperCase() == "IFRAME")) {
        a.src = url; //if this iframe exist, open in it
        return;
    }
    if (arguments.length == 2) {//Max size default
        ht = getViewportHeight() - 80;
        wd = getViewportWidth() - 40;
    }
    else { ht = arguments[3]; wd = arguments[4]; }
    if (ht > 500) ht = 500;
    if (wd > 850) wd = 850;
    if ((typeof (showPopWin) == 'function')) //if modal showPopWin function is available use it
        showPopWin(url, wd, ht, null, caption);
    else {
        var winProp = CenterPopup(wd, ht);
        var hWnd = window.open(url, caption, winProp + ",menubar=no,resizable=yes,titlebar=yes,scrollbars=yes,status=yes,toolbar=no,location=no");

        if ((document.window != null) && (!hWnd.opener))
            hWnd.opener = document.window;

        hWnd.focus();
    }
}

/**
* Code below taken from - http://www.evolt.org/article/document_body_doctype_switching_and_more/17/30655/
*
* Modified 4/22/04 to work with Opera/Moz (by webmaster at subimage dot com)
*
* Gets the full width/height because it's different for most browsers.
*/
function getViewportHeight() {
    if (window.innerHeight != window.undefined) return window.innerHeight;
    if (document.compatMode == 'CSS1Compat') return document.documentElement.clientHeight;
    if (document.body) return document.body.clientHeight;
    return window.undefined;
}
function getViewportWidth() {
    if (window.innerWidth != window.undefined) return window.innerWidth;
    if (document.compatMode == 'CSS1Compat') return document.documentElement.clientWidth;
    if (document.body) return document.body.clientWidth;
    return window.undefined;
}
function CenterPopup(popW, popH) {
    var winLeft = (screen.width - popW) / 2;
    var winTop = (screen.height - popH) / 2;
    winProp = 'width=' + popW + ',height=' + popH + ',left=' + winLeft + ',top=' + winTop;
    return winProp;
}
function CloseIframe() {//if the parent contains this function, then we are using modal iframe
    if (window.parent.hidePopWin) window.parent.hidePopWin(null); else self.close();
}

function IsIE() {
    return window.navigator.userAgent.toLowerCase().indexOf('msie') > -1;
}

function IE6Up() {
    var agt = navigator.userAgent.toLowerCase();
    var major = parseInt(navigator.appVersion);
    var ie4 = ((major == 4) && (agt.indexOf("msie 4") != -1));
    var ie5 = ((major == 4) && (agt.indexOf("msie 5") != -1));
    return IE6Up = (!ie4 && !ie5 && major >= 4);
}

function IE7Up() {
    var agt = navigator.userAgent.toLowerCase();
    var major = parseInt(navigator.appVersion);
    var ie4 = ((major == 4) && (agt.indexOf("msie 4") != -1));
    var ie5 = ((major == 4) && (agt.indexOf("msie 5") != -1));
    var ie6 = ((major == 4) && (agt.indexOf("msie 6") != -1));
    return IE6Up = (!ie4 && !ie5 && !ie6 && major >= 4);
}

function divSettings() {
    GDSCROLLDIV.style.width = "100%";
    GDSCROLLDIV.style.overflow = "auto"

    if (GDDIVSCROLLPOSOBJ != null) intSCROLLPOS = (GDDIVSCROLLPOSOBJ.value == "") ? 0 : parseInt(GDDIVSCROLLPOSOBJ.value); else intSCROLLPOS = 0;
    wnd_event = false;
    divResize();
    addEvent(window, 'resize', divResize);
    addEvent(GDSCROLLDIV, 'scroll', divScroll);
}

function divScroll() {
    if (wnd_event == true) {
        if (GDDIVSCROLLPOSOBJ != null)
            GDDIVSCROLLPOSOBJ.value = GDSCROLLDIV.scrollTop;
        else intSCROLLPOS = GDSCROLLDIV.scrollTop;
    }
}

function divResize() {
    var windowHeight = getViewportHeight();

    if (GDBodyObj) { //only proceed if passed	
        if (windowHeight - GDSCROLLDIV.offsetTop < 150) {
            GDSCROLLDIV.style.height = 150 + "px";
            GDBodyObj.scroll = "yes";
        }
        else {
            GDSCROLLDIV.style.height = (windowHeight - GDSCROLLDIV.offsetTop) + "px";
            GDBodyObj.scroll = "no";
        }
        if (GDDIVSCROLLPOSOBJ != null)
            GDDIVSCROLLPOSOBJ.scrollTop = (GDDIVSCROLLPOSOBJ.value == "") ? 0 : parseInt(GDDIVSCROLLPOSOBJ.value);
        wnd_event = true;
    }
}

/**
* X-browser event handler attachment and detachment
*
* @argument obj - the object to attach event to
* @argument evType - name of the event - DONT ADD "on", pass only "mouseover", etc
* @argument fn - function to call
*/
function addEvent(obj, evType, fn) {
    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, true);
        return true;
    } else if (obj.attachEvent) {
        var r = obj.attachEvent("on" + evType, fn);
        return r;
    } else {
        return false;
    }
}
function removeEvent(obj, evType, fn, useCapture) {
    if (obj.removeEventListener) {
        obj.removeEventListener(evType, fn, useCapture);
        return true;
    } else if (obj.detachEvent) {
        var r = obj.detachEvent("on" + evType, fn);
        return r;
    } else {
        alert("Handler could not be removed");
    }
}

function getPopupCaller() {
    if (window.parent.hidePopWin) return window.parent;
    else if (window.opener) return window.opener;
    return window.parent;
}
// End of IFrame Popup Routines

// String Functions
function CurrentPageName() {   //returns the current page filename only 
    //(ex. if current page is http://localhost/forms/inv_upd.aspx?FID=497 then this function will return inv_upd.aspx)

    var URL = unescape(location.href); //unescape to get rid of strange characters
    var start = URL.lastIndexOf("/") + 1;
    var end = URL.indexOf("?"); //do not include querystring params
    if (end == -1) end = URL.length;
    var retValue = URL.substring(start, end);
    return retValue;
}

function righttrim(str, Char) { //Remove leading white spaces + requested character
    var i = str.length;
    var aChar;

    while (i > 0) {
        aChar = str.charAt(i - 1);
        if ((aChar == Char) || (aChar == " ") || (aChar == "\t") || (aChar == "\r") || (aChar == "\n")) i--;
        else break;
    }
    return (str.substr(0, i));
}

function lefttrim(str, Char) { //Remove trailing white spaces + requested character
    var i = 1;
    var aChar;

    while (str.length >= i) {
        aChar = str.charAt(i - 1);
        if ((aChar == Char) || (aChar == " ") || (aChar == "\t") || (aChar == "\r") || (aChar == "\n")) i++;
        else break;
    }
    return (str.substr(i - 1));
}

function trimall(str, Char)
{ return (lefttrim(righttrim(str, Char), Char)); }

function SStrip(InStr, StripStr) {
    var NewStr = new String(InStr);
    var repLen = StripStr.length;

    while (NewStr.indexOf(StripStr) != -1)
        NewStr = NewStr.substr(0, NewStr.indexOf(StripStr)) + NewStr.substr(NewStr.indexOf(StripStr) + repLen);

    return (NewStr);
}
//Trim white space
function trimws(str) { return (str.replace(/^\s+|\s+$/g, '')); }

function emailCheck(emailStr) {
    var checkTLD = 1;
    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
    var emailPat = /^(.+)@(.+)$/;
    var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    var validChars = "\[^\\s" + specialChars + "\]";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom = validChars + '+';
    var word = "(" + atom + "|" + quotedUser + ")";
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$");
    var matchArray = emailStr.match(emailPat);

    if (matchArray == null) {
        alert("Email address seems incorrect (check @ and .'s)");
        return false;
    }
    var user = matchArray[1];
    var domain = matchArray[2];

    for (i = 0; i < user.length; i++) {
        if (user.charCodeAt(i) > 127) {
            alert("Ths username contains invalid characters.");
            return false;
        }
    }
    for (i = 0; i < domain.length; i++) {
        if (domain.charCodeAt(i) > 127) {
            alert("Ths domain name contains invalid characters.");
            return false;
        }
    }

    if (user.match(userPat) == null) {
        alert("The username doesn't seem to be valid.");
        return false;
    }

    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {

        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                alert("Destination IP address is invalid!");
                return false;
            }
        }
        return true;
    }

    var atomPat = new RegExp("^" + atom + "$");
    var domArr = domain.split(".");
    var len = domArr.length;
    for (i = 0; i < len; i++) {
        if (domArr[i].search(atomPat) == -1) {
            alert("The domain name does not seem to be valid.");
            return false;
        }
    }

    if (checkTLD && domArr[domArr.length - 1].length != 2 &&
                domArr[domArr.length - 1].search(knownDomsPat) == -1) {
        alert("The address must end in a well-known domain or two letter " + "country.");
        return false;
    }

    if (len < 2) {
        alert("This address is missing a hostname!");
        return false;
    }

    return true;
}

// End String Functions

//Start SpellCheck
function onCheckSpelling(PAGEBASE, objID) {
    //objName is the name of the text object to get the text from and check it.
    //If the modal routines exist the use them, otherwise popup up.
    var hWnd;
    if (window.parent.hidePopWin) {
        hWnd = objID.document.parentWindow.frames["popupFrame"];
        showPopWin('', 540, 250, null, "Spellex");
    }
    else {
        var winProp = CenterPopup(540, 250);
        hWnd = window.open('', 'Spellex', winProp + ',toolbar=no,directories=no,status=no,menubar=no,resizable=no');
        //if the spellex window is open, close it and start over.
        if (hWnd.document.forms["SpellingForm"]) { hWnd.close(); hWnd = window.open('', 'Spellex', winProp + ',toolbar=no,directories=no,status=no,menubar=no,resizable=no'); }
    }

    hWnd.document.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">');
    hWnd.document.write('<head><title>Spellex<\/title><\/head><body style="overflow:hidden" bgcolor="#eeeeee">');
    hWnd.document.write('<form method="post" runat="server" name="BegSpell" id="BegSpell" action="' + PAGEBASE + '/WSS/SpellingForm.aspx?obj=' + objID.name + '" language="javascript">')
    hWnd.document.write('<INPUT id="narrid" type="hidden" value="" name="narrid">');
    hWnd.document.write('<\/form><\/body><\/html>');
    hWnd.document.BegSpell.narrid.value = objID.value;
    hWnd.document.forms["BegSpell"].submit();
    hWnd.focus();
}
//END SPELLCHECK

// Reports
function ViewReport(PAGEBASE, PKEY, RPTID, ShowMsg, Default, FN, ExitURL, Confirm) {
    if (Confirm == 1) {
        var ConfirmMsg = "Unsaved data will be lost!";
        if (!confirm(ConfirmMsg)) return;
    }

    if (ShowMsg == 1) {
        var URL = PAGEBASE + "/Forms/POP_RptMsg.aspx?RPTID=" + RPTID + "&PKEY=" + PKEY + "&DEF=" + Default + "&FN=" + FN + "&X=" + escape(ExitURL);
        window.location = URL;
    }
    else {
        var URL = PAGEBASE + "/Forms/RPT_Body.aspx?RPTID=" + RPTID + "&PKEY=" + PKEY + "&JUV=0";
        window.location = URL;
    }
}

//Flash Stuff
function MM_swapImgRestore() { //v3.0
    var i, x, a = document.MM_sr; for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}
function MM_preloadImages() { //v3.0
    var d = document; if (d.images) {
        if (!d.MM_p) d.MM_p = new Array();
        var i, j = d.MM_p.length, a = MM_preloadImages.arguments; for (i = 0; i < a.length; i++)
            if (a[i].indexOf("#") != 0) { d.MM_p[j] = new Image; d.MM_p[j++].src = a[i]; } 
    }
}

function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
    var i, j = 0, x, a = MM_swapImage.arguments; document.MM_sr = new Array; for (i = 0; i < (a.length - 2); i += 3)
        if ((x = MM_findObj(a[i])) != null) { document.MM_sr[j++] = x; if (!x.oSrc) x.oSrc = x.src; x.src = a[i + 2]; }
}

//END REPORTS
// Notify ScriptManager that this is the end of the script.
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();