﻿function addLoadEvent(func) 
{
    var oldonload = window.onload;
    if (typeof window.onload != 'function') 
    {
        window.onload = func;
    }
    else 
    {
        window.onload = function() 
        {
            if (oldonload) 
            {
                oldonload();
            }
            func();              
        }
    }          
}

function addResizeEvent(func) 
{
    var oldonresize = window.onresize;
    if (typeof window.onresize != 'function') 
    {
        window.onresize = func;
    }
    else 
    {
        window.onresize = function() 
        {
            if (oldonresize) 
            {
                oldonresize();
            }
            func();        
        }
    }          
}

function getElement(id) 
{    
    if (document.getElementById) {return document.getElementById(id);}
    if (document.all) {return document.all[id];}
    if (document.layers) {return document.layers[id];}
    return window[id];
}

function getInnerText(node) {
    return (node.textContent || node.innerText || node.text);
}

// toggles the visibility of an element
function showHideElement(id)
{
    var s = getElement(id);

    if (s) 
    {
        s.style.visibility = s.style.visibility!='visible'?'visible':'hidden';
    }
}

// hides an element
function hideElement(id)
{
    var s = getElement(id);

    if (s) 
    {
        s.style.visibility = 'hidden';
    }
}

function showElement(id)
{
    var s = getElement(id);

    if (s) 
    {
        s.style.visibility = 'visible';
    }
}

function showHideElementWithAnimation(id, animationTitle, numMilliseconds, callbackFunction, elementToUpdateId, hideText, showText) 
{
    var animatedElementSelector = "#" + id;
    var elementToUpdateSelector = "#" + elementToUpdateId;

    if ($(animatedElementSelector).css("display") == "block") 
    {
        $(animatedElementSelector).hide(animationTitle, {}, numMilliseconds, callbackFunction);

        if ($(elementToUpdateSelector))
            $(elementToUpdateSelector).html(hideText);
    }
    else 
    {
        $(animatedElementSelector).show(animationTitle, {}, numMilliseconds, callbackFunction);

        if ($(elementToUpdateSelector))
            $(elementToUpdateSelector).html(showText);
    }
}

function ResizeTree() {
    var DocumentBodyHeight = $(window).height();
    var DocTreeIFrame = getElement('FullBrowseTree');

    if (typeof (DocTreeIFrame) === 'undefined' || DocTreeIFrame == null)
        return; 

    var diff = OldBodyHeight - DocumentBodyHeight;
    if (diff > 5 || diff < -5)
    {        
        if (DocumentBodyHeight > 500)
            DocTreeIFrame.style.height = (DocumentBodyHeight - 150) + 'px';
        else
            DocTreeIFrame.style.height = '350px';
            
        //ReloadTree();
                        
        OldBodyHeight = DocumentBodyHeight;
    }
}

function ReloadTree(url)
{            
    // Set the url for the iframe to get it to reload    
    if (url != null && url != undefined)
    {
        frames['treeHolder'].location.href = url;
    }
}

function ShowTree(url)
{
    showElement("FullBrowseTree");
    showElement("treeHolder");
    CloseDocumentPane();
    //menuUnderlayShow(null, null);
    ReloadTree(url);
}

function getParameter(parameterName) 
{
    var queryString = window.location.search.substring(1).toLowerCase();
    var parameters = new Array();
    parameters = queryString.split('&');

    for (var i = 0; i < parameters.length; i++) 
    {
        if (parameters[i].indexOf(parameterName.toLowerCase()) >= 0) 
        {
            var parameterValue = new Array();
            parameterValue = parameters[i].split('=');
            return parameterValue[1];
        }
    }
    return "null";
}

function SessionTimedOut(expUrl) 
{
    document.URL = expUrl;
}

function toggleSet(rad) 
{             
    setCookie("SearchType", rad.value);
}

function setCookie(name, value)
{
    var cookie_string = name + "=" + escape ( value ) + "; path=/";
    document.cookie = cookie_string;
}

function getCookie(cookieName)
{
    var results = document.cookie.match ( '(^|;) ?' + cookieName + '=([^;]*)(;|$)' );

    if (results)
        return (unescape(results[2]));
    else
        return null;
}

var invalidTextFieldId = null;

function validateTextField(tb, ff, minValue, maxValue) 
{
    if (tb.value == "" || (invalidTextFieldId != null && tb.id != invalidTextFieldId)) 
    {
        invalidTextFieldId = null;
        return;
    }

    var errorText = "";

    if (ff == ffDecimal) 
    {
        if (isNaN(tb.value)) 
        {
            errorText = ffDecimalError;
        }
        else
        {
            var dec = parseFloat(tb.value);

            if (minValue != "null" && dec < minValue)
                errorText = minValueError + minValue + ".";
                
            if (maxValue != "null" && dec > maxValue)
                errorText = maxValueError + maxValue + ".";
        }
    }
    else if (ff == ffEmailAddress) 
    {
        var regexp = /^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/;

        if (!regexp.test(tb.value)) 
        {
            errorText = ffEmailAddressError;
        }
    }
    else if (ff == ffHTMLCode) 
    {
        var regexp = /([\<])([^\>]{1,})*([\>])/i;
        if (!regexp.test(tb.value)) 
        {
            errorText = ffHTMLCodeError;
        }        
    }
    else if (ff == ffInteger) 
    {
        if (isNaN(tb.value) || tb.value.indexOf(".") != -1) 
        {
            errorText = ffIntegerError;
        }
        else 
        {
            var dec = parseInt(tb.value);

            if (minValue != "null" && dec < minValue)
                errorText = minValueError + minValue + ".";

            if (maxValue != "null" && dec > maxValue)
                errorText = maxValueError + maxValue + ".";
        }
    }
    else if (ff == ffWebLink) 
    {
        var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/i;

        if (!regexp.test(tb.value)) 
        {
            errorText = ffWebLinkError;
        }
    }

    if (errorText != "") 
    {
        // Set the id of the text field we are looking for here so that when a different field
        // tries to call ValidateTextField, it will not trigger the validation since we know we will
        // be back in the original field that failed validation due to the focus() call down below.
        invalidTextFieldId = tb.id;
        alert(errorText);
        setTimeout("focusTextField('" + tb.id + "');", 1);
        return false;
    }
    else 
    {
        invalidTextFieldId = null;
        return true;
    }
}

function focusTextField(tbId) 
{
    getElement(tbId).focus();
    getElement(tbId).select();
}

// This function is used set to a check box to checked or not checked
// based on whether or not a text box has content.
function txtBox_OnChange(txt, cbId, event) 
{
    var cb = getElement(cbId);

    if (cb && txt) 
    {
        if (txt.value != null && txt.value != '') 
        {
            cb.checked = true;
        }
        else 
        {
            cb.checked = false;
        }
    }
}

// This function is used set to a check box to checked 
// when a drop down list is changed.
function ddl_OnChange(ddl, cbId, event)
{
    var cb = getElement(cbId);

    if(ddl && cb)
    {
        cb.checked = true;
    }
}

// This function is used set to a check box to checked or not checked
// when a list box is changed.
function lb_OnChange(lb, cbId, event)
{
    var anyChecked = false;
    if(lb)
    {  
        for(var i = 0; i < lb.options.length; i++)
        {
            if(lb.options[i].selected)
            {  
                anyChecked = true;
                break;
            }
        }
        var cb = getElement(cbId);
        cb.checked = anyChecked;
    }
}

function qtDate_OnChange(txt, cbId, event) 
{
    var cb = getElement(cbId);
    if(cb && txt)
    {
        cb.checked = (txt.value != '') ? true : false;
    }
}

function trim(str, chars)
{
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars)
{
    if (str.length == 0)
        return "";
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars)
{
    if (str.length == 0)
        return "";
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

// Charting client side functions for hovering
function onDpHover(who, what) 
{
    //draw the div that displays the pop-up menu if it hasn't been created
    var chart = what.get_dataPoint().get_parentSeries().get_parentChart();
    var chartImage = getElement(chart.get_id());

    if (!window.menuDiv) 
    {
        window.menuDiv = document.createElement('div');
        window.menuDiv.style.position = 'absolute';
        window.menuDiv.style.height = '48px';
        window.menuDiv.style.width = '230px';
        window.menuDiv.style.zIndex = '100000';
        window.menuDiv.style.backgroundImage = "url(" + siteRoot + "App_Themes/QTNextGen/Images/charting/ChartPopupBackground.jpg)";
        window.menuDiv.style.textAlign = 'center';
        window.menuDiv.style.verticalAlign = 'top';
        window.menuDiv.style.visibility = 'hidden';
        window.menuDiv.style.top = (chart.get_absoluteY() + 25) + 'px';
        window.menuDiv.style.left = (chart.get_absoluteX() + 275) + 'px';
        window.document.body.insertBefore(window.menuDiv, document.body.firstChild);
    }
    else 
    {
        window.menuDiv.style.top = (chart.get_absoluteY() + 25) + 'px';
        window.menuDiv.style.left = (chart.get_absoluteX() + 275) + 'px';
    }

    //create the HTML for the pop-up 
    var xValue = what.get_dataPoint().get_x();

    var popupHTML = "<table style=\"font-size: 7pt; height: 100%; width: 100%;\"><tr><td>" + xValue + ": ";
    popupHTML += "<b>" + what.get_dataPoint().get_y() + "</b></td></tr></table>";

    window.menuDiv.innerHTML = popupHTML;
    window.menuDiv.style.visibility = 'visible';
}

function onDpExit(who, what) 
{
    if (window.menuDiv) 
    {
        window.menuDiv.style.visibility = 'hidden';
    }
}

function checkUncheckAllTreeNodes(tv) 
{
    if (areAllTreeNodesChecked(tv.get_nodes().getNode(0)))
    {
        tv.unCheckAll();
    }
    else 
    {
        tv.checkAll();
    }
}

function areAllTreeNodesChecked(node) 
{
    var i = 0;
    var j = 0;
    var nodes = node.get_nodes(); // Get the nodes under the parent node
    var allChecked = true;
    var nodesLength = nodes.get_length();

    // Loop through each node and see if the nodes are not checked
    for (i = 0; i < nodesLength; i++) 
    {
        var curNode = nodes.getNode(i);

        if (curNode.get_nodes().get_length() > 0)
            allChecked = allChecked && areAllTreeNodesChecked(curNode);

        if (curNode.get_showCheckBox()) 
        {
            var isChecked = curNode.get_checked();

            if (isChecked != undefined) 
            {
                allChecked = allChecked && curNode.get_checked();
            }
            else 
            {
                allChecked = false;
            }
        }

        if (!allChecked) 
        {
            break;
        }
    }   

    return allChecked;
}

function applyCheckedStatusToTree(sender, eventArgs)
{
    var node = eventArgs.get_node();
    var isChecked = node.get_checked();

    setCheckedOnSubNodes(node, isChecked);

    // Don't uncheck the parent nodes.
    if(isChecked)
        setCheckedOnParentNode(node, isChecked);
}

function setCheckedOnSubNodes(node, isChecked) 
{
    var i = 0;
    var j = 0;
    var nodes = node.get_nodes(); // Get the nodes under the parent node
    var nodesLength = nodes.get_length();

    for (i = 0; i < nodesLength; i++) 
    {
        var curNode = nodes.getNode(i);

        if (curNode.get_nodes().get_length() > 0)
            setCheckedOnSubNodes(curNode, isChecked);

        curNode.set_checked(isChecked);
    }
}

function setCheckedOnParentNode(node, isChecked)
{
    var parentNode = node.get_parentNode();

    if (parentNode) 
    {
        parentNode.set_checked(isChecked);
        setCheckedOnParentNode(parentNode, isChecked);
    }
}

function findWidestElement(selector) 
{
    var normalizedWidth = 0;

    $(selector).each(function (i, element) 
    {
        var elementWidth = $(this).width();

        if (elementWidth > normalizedWidth) 
        {
            normalizedWidth = elementWidth;
        }
    });

    return normalizedWidth;
}

function setElementWidth(selector, width) 
{
    $(selector).width(width);
}

function menuUnderlayShow(sender, eventArgs) 
{
    $("#dynamicMenuHolder").css("visibility", "visible");
}

function menuUnderlayHide(sender, eventArgs)
{
    $("#dynamicMenuHolder").css("visibility", "hidden");
}
