// Auto session refresh to prevent timeouts.
var to;
var sto;
try {
    sto = intSessionRefreshInterval;
}
catch (e) {
    sto = 12000;
}

$().ready(function() {
    to = setTimeout("TimedOut()", sto);

    refreshCountDown = sto;
    refreshTimesCount = 0;

    // Uncomment this line to add a countdown timer to the page for debugging the session refresh.
    //initCountDownDiv();
    
    
    try{
        switch(DatabaseEnvironment){
            case "UAT":
                showEnvironmentMessage("UAT");
                break;
            
            case "DEV":
                showEnvironmentMessage("DEV");
                break;
        }
    }
    catch(e){}
});

function TimedOut() {
    $.post("refresh_session.aspx", null, function(data) {
        if (data == "success") {
            if (refreshCountDown != sto) {
                $("#cnv").before("<div id='sessionmessage' style='width:50%;top:60px;min-height:30px;line-height:30px;position:absolute;background-color:#FFC;color:#666;'>Session refreshed</div>").fadeIn(1200, function() {
                    $("#sessionmessage").delay(1000).fadeOut(2000, function() {
                        $("#sessionmessage").remove();
                    });
                });
                refreshTimesCount++;
            }

            to = setTimeout("TimedOut()", sto);
            refreshCountDown = sto;
        }
    });
}

function countdown() {
    strRefreshMessage = "Session refresh in<br />" + refreshCountDown / 1000 + "<br />seconds";
    if (refreshTimesCount > 0) {
        strRefreshMessage += "<hr>Refresh count: " + refreshTimesCount;
    }

    document.getElementById("divCountDown").innerHTML = strRefreshMessage;

    refreshCountDown -= 1000;
    tmrRS = setTimeout("countdown()", 1000);
}

function initCountDownDiv() {
    $("#cnv").before("<div id='divCountDown' style='width:100px;text-align:center;min-height:30px;font-size:9px;position:absolute;background-color:#999;color:#333;z-index:500;'></div>");
    tmrRS = setTimeout("countdown()", 1000);
}

function showDebugMessage(strMessageHTML, intDelayMilliseconds) {
    if (null == intDelayMilliseconds) {
        intDelayMilliseconds = 1000;
    }
    if ($("#tempMessagePopup").length < 1) {
        // There is no message currently in place so show a new one.
        strHTML = "<div id='tempMessagePopup'>" + strMessageHTML + "</div";
        $("body").prepend(strHTML);
        $("#tempMessagePopup").click(function() { removeDebugMessage() });
        dto = setTimeout("removeDebugMessage()", intDelayMilliseconds);
    } else {
        // There is already a message on screen so append the new one.
        dto = null;
        strHTML = $("#tempMessagePopup").html() + "<hr>" + strMessageHTML;
        $("#tempMessagePopup").html(strHTML);
        // Reset the timeout.
        dto = setTimeout("removeDebugMessage()", intDelayMilliseconds);
    }
}

function removeDebugMessage() {
    if ($("#tempMessagePopup").length > 0)
        $("#tempMessagePopup").remove();
}

function showFinanceOverlay(financeProductKey) {
    $("#SummaryContainer").load('FinanceOverlay.aspx?SelectedProduct=' + financeProductKey, function() {
        $("#summaryFrame").hide();
        $("#SummaryContainer").dialog('open');
    });
}

function closeOverlay(id) {
    $("#" + id).dialog('close');
}

function closeBlockUI() {
    $.unblockUI();

    $.blockUI.defaults.overlayCSS = { backgroundColor: '#e9e9e9', opacity: 0.6 };
    $.blockUI.defaults.css = { width: '60px',
        border: 'none',
        backgroundColor: 'transparent'
    };
}

// Function to reference embeded flash movies for Javascript.
function flashMovie(movieName) {
    // IE and Netscape refer to the movie object differently.
    // This function returns the appropriate syntax depending on the browser.
    if (navigator.appName.indexOf("Microsoft") != -1)
        return window.document[movieName];
    else
        return document[movieName];
}

function showPageLoading() {
    $('#pageLoading').block({ message: "<img src='images/TFS_Loading_animation_3.gif' alt='Loading' />" });
}

function hidePageLoading() {
    $('#pageLoading').unblock();
}

function formatAPR(label, value) {
    $("[id$=APRLab]").html(label + "" + value);
    $("[id$=APRVal]").html("");
}

// Create an XML element from a string
function prepareXMLDoc(xml) {
    var xmlDoc = null;

    if (window.DOMParser) {
        // Good Browsers
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(xml, "text/xml");
    }
    else {
        // Internet Explorer
        xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xml);
    }

    return xmlDoc;
}

// Convert an input to an integer, but always ensure an int is 
// returned even for non-numeric values.
// REG - 2011-11-11
function makeInt(val)
{
	var o=parseInt(val);	
	if(isNaN(o))
	 o=0;	
	return o;
}

function stringToBoolean(string)
{         
    switch(string.toLowerCase())
    {                 
        case "true": 
        case "yes": 
        case "1": 
        return true;                 

        case "false": 
        case "no": 
        case "0": 
        case null: 
        return false;                 

        default: 
        return Boolean(string);         
    } 
}


// Eco Label functions.
function loadEcoLabel()
{
    $("#EcoLabelContainer").load("EcoLabel.aspx?id=" + Math.floor(Math.random() * Math.pow(10,20)));
}


// Environment message
function showEnvironmentMessage(strDBEnv)
{
    // If we're on prod, then we don't want to see any message.
    if (strDBEnv == "PROD")
        return;

    var envMsg = "<div id='environmentmessage' style='position:fixed;top:0;left:0;z-index:1000'><img src='images/DBIndicator-" + strDBEnv + ".png' alt=''></div>";
    $("#cnv").before(envMsg);
}
