
/*
Written by Ron Clabo
This file is intended to house common routines that can be used
to improve the UI experience.
*/


$(document).ready(function () {
    timeOutMgr.init();
});


//Used to show or hid a layer
//params: string divId, bit visible (pass 1 or 0 for visible)
function showLayer(divId, visible) {
    var divObj = document.getElementById(divId);
    if (visible) {
        divObj.style.display = 'block';
    } else {
        divObj.style.display = 'none';
    }
}



/*
 FocusMgr restores field focus after update panel partial update.
 Needed because update panel replaces fields with new ones by setting div.innerHTML
*/

var Lib = new Object();

Lib.getPage = function (url) {
    window.location = url;
    return false;
}

Lib.initFocusMgr = function () {
    function focusHandler(e) {
        if (typeof (e.originalTarget) !== "undefined") {
            e.originalTarget.focus = true;              //this approach needed for firefox 3
        }
    }
    function pageLoadingHandler(sender, args) {
        Lib.lastFocusedControlId = "";
        if (typeof (document.activeElement) !== "undefined") {
            Lib.lastFocusedControlId = document.activeElement.id;
        }
    }

    function pageLoadedHandler(sender, args) {
        if (typeof (Lib.lastFocusedControlId) !== "undefined" && Lib.lastFocusedControlId != "") {
            $('#' + Lib.lastFocusedControlId).focus();

            var ctlObj = $get(Lib.lastFocusedControlId);
            if (ctlObj) {
                Lib.moveToEndOfTextField(ctlObj);
            }
        }
    }

    if (typeof (window.addEventListener) !== "undefined") { // !== undefined also checks against null, while === doesn't 
        window.addEventListener("focus", focusHandler, true);
    }
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(pageLoadingHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
}

Lib.lastFocusedControlId = "";

Lib.moveToEndOfTextField = function(ctlObj) {
    if (ctlObj.type != "text") {
        return;
    }

    if (ctlObj.isDisabled == true) {
        return;
    }

    if (ctlObj.createTextRange) {                //for ie
        var range = ctlObj.createTextRange();
        range.moveStart('character', (ctlObj.value.length));
        range.collapse();
        range.select();

    } else if (ctlObj.setSelectionRange) {        //for firefox & safari
        ctlObj.setSelectionRange(ctlObj.value.length, ctlObj.value.length);
    }
}

//---End Focus Handeling code---


Lib.newVisitor = function() {
    function asyncResult(jsonData) {
        return;
    }

    $.post("/ajax.aspx", { reqType: "newVisitor", infoStr: "" }, asyncResult, "text");
    return false;
}

var startMS;
Lib.showWorkingMsg = function() {
    Lib.showWorkingMsg('','');
}
Lib.showWorkingMsg = function(title) {
    Lib.showWorkingMsg(title,'');
}
Lib.showWorkingMsg = function (title, text) {
    var viewPortHeight = $(window).height();
    if (title != '') $('#workingMsg .wmTitle').html(title);
    if (text != '') $('#workingMsg .wmText').html(text);
    Lib.posAndShowDlog('#workingMsg');

    startMS = (new Date()).getTime();               //num millisecs since 1/1/70
}

Lib.hideWorkingMsg = function() {
    var box = $("#workingMsg")
    if (box.css('display') == 'block') {
        var nowMS = (new Date()).getTime();
        if (nowMS - startMS > 500) {
            box.fadeOut(50);
        } else {
            box.delay(500).fadeOut(50);
        }
    }
}

Lib.posAndShowDlog = function (dlogSel) {
    var viewPortHeight = $(window).height();
    $(dlogSel).show();                      //must show before getting cur height, offset & re-offsetting
    var dlogH = $(dlogSel).height();
    var pos = $(dlogSel).offset();          // IE requires both top and left, get existing.
    var scrollTop = $(window).scrollTop();
    pos.top = ((viewPortHeight - dlogH) * .20) + scrollTop;    // set top, use existing left
    $(dlogSel).offset(pos);
}


//handles new and existing query param
Lib.getUrlSetQueryParam = function (name, val) {
    var parts = window.location.toString().split("?");
    var newUrl = parts[0] + '?';
    var sep = "";
    var found = false;

    if (parts[1]) {
        var pieces = parts[1].split("&");
        for (var i in pieces) {
            if (pieces[i].indexOf(name) == 0) {
                newUrl += sep + name + '=' + val;
                found = true;
            } else {
                newUrl += sep + pieces[i];
            }
            sep = "&";
        }
    }
    if (!found) {
        newUrl += sep + name + '=' + val;
    }
    return newUrl;
}


/* Timeout Manager, display dialog before account timeout */
var timeOutMgr = new Object();

timeOutMgr.duration = 1000 * 60 * 15;  // 1 minute = 1000 ms * 60secs * 1min

timeOutMgr.init = function () {
    if ($('#timeoutDlog').length == 0) {    //visitor not logged into account
        return;
    }
    $('#timeoutDlog .ydOk').click(timeOutMgr.keepAlive);
    setTimeout(timeOutMgr.showDlog, timeOutMgr.duration);  
}

timeOutMgr.showDlog = function () {
    Lib.posAndShowDlog('#timeoutDlog');
}

timeOutMgr.keepAlive = function () {
    function asyncResult(resultStr) {

        if (resultStr == 'timedOut') {
            $('#timeoutDlog .ydTitle').html('Re-Login?')
            $('#timeoutDlog .ydText').html("Sorry, your account had already been logged out.<br\>You may log back in via the <a href = '/MyAccount/Home.aspx'>login page</a>.")
            $('#timeoutDlog .ydOk').attr('value', 'Close').css('width', '90px');
            $('#timeoutDlog .ydOk').unbind('click').click(function () { $('#timeoutDlog').hide(); });
        } else {
            $('#timeoutDlog').hide();
            setTimeout(timeOutMgr.showDlog, timeOutMgr.duration);       //setup to do call again
        }
        return;
    }

    $.post("/ajax.aspx", { reqType: "keepAlive", infoStr: "" }, asyncResult, "text");
    return false;
}

/* End Timeout Manager */


