var requests;

function pageReadyIe()
{
    if (previousDocumentReady != null && previousDocumentReady != '')
    {
        previousDocumentReady();
    }

    if (document.readyState == 'complete')
    {
        if(spKpiAllCommands != null && spKpiAllCommands != '')
        {
            eval(spKpiAllCommands);
        }
    }
}

function pageReadyMoz()
{
    eval(spKpiAllCommands);
}

function kpiRequestStateChange(index, elementUniqueIdSuffix, showOnlyProblems)
{
    if(requests[index].readyState == 4)
    {
        PopulateValueAndIcon(requests[index].responseText, elementUniqueIdSuffix, showOnlyProblems);                       
    }
}

function PopulateValueAndIconWithDetails(result, elementUniqueIdSuffix)
{
    PopulateValueAndIcon(result, elementUniqueIdSuffix, 'False')
}

function PopulateValueAndIconOnlyProblems(result, elementUniqueIdSuffix)
{
    PopulateValueAndIcon(result, elementUniqueIdSuffix, 'True')
}

function PopulateValueAndIcon(result, elementUniqueIdSuffix, showOnlyProblems) 
{
    if(elementUniqueIdSuffix == null || elementUniqueIdSuffix == '' ||
        result == null || result == '')
    {
        return;
    }

    var errIndex = result.indexOf('<Error>')
    if(errIndex != -1)
    {
        var dom=loadXml(result);
        var childNode = dom.getElementsByTagName('Error')[0];
        var errorText = childNode.text;

        var row = document.getElementById('kpirow_' + elementUniqueIdSuffix);

        var numOfCells = row.cells.length - 2;
        for(i = 0; i< numOfCells; i++)
        {
            row.deleteCell();
        }

        var newErrorCell = row.insertCell();
        newErrorCell.className = 'ms-vb2 ms-error';
        newErrorCell.id ='kpiErrorCell_' + elementUniqueIdSuffix;
        newErrorCell.colSpan = numOfCells;        

        newErrorCell.innerHTML = '<font color=red>' + errorText + '</font>';
    }
    else if(showOnlyProblems == 'True' && result.indexOf('No') == 19)
    {
        document.getElementById('kpirow_' + elementUniqueIdSuffix).style.display = 'none';
    }
    else
    {
        var dom=loadXml(result);
        var childNode = dom.documentElement.childNodes.item(0);

        var filtered = false;
        childNode = childNode.nextSibling;
        if(getNodeText(childNode) == 'Yes')
        {
            ShowFilterColumn();
            document.getElementById('kpiExpandCollaspeCell_' + elementUniqueIdSuffix).innerHTML += '<img id=FilteredImagekpiExpandCollaspe_' + elementUniqueIdSuffix + ' alt="" src="/_layouts/images/filter.gif" width="12px" height="10px">';
        } 

        var i=0;
        var kpiNode;
        while(childNode.nextSibling != null && childNode.nextSibling.nodeName == 'KpiData')
        {
          childNode = childNode.nextSibling;

          kpiNode = childNode.childNodes.item(0);
          var includeGoal = false;
          var includeValue = false;
          var includeStatus = false;
          var includeTrend = false;

          var goaldiv = document.getElementById('kpigoaldiv' + i + '_' + elementUniqueIdSuffix);
          if(goaldiv != null)
          {
                goaldiv.innerHTML = "<nobr>" + getNodeText(kpiNode) + "</nobr>";
                includeGoal = true;
          }

          kpiNode = kpiNode.nextSibling;
          var valuediv = document.getElementById('kpivaluediv' + i + '_' + elementUniqueIdSuffix);
          if(valuediv != null)
          {
                valuediv.innerHTML = "<nobr>" + getNodeText(kpiNode) + "</nobr>";
                includeValue = true;
          }

          kpiNode = kpiNode.nextSibling;     
          var statusdiv = document.getElementById('kpiimagediv' + i + '_' + elementUniqueIdSuffix);
          if(statusdiv != null)
          {
                statusdiv.innerHTML = getNodeText(kpiNode);
                includeStatus = true;
          }

          kpiNode = kpiNode.nextSibling;
          if(statusdiv != null)
          {
                statusdiv.innerHTML += getNodeText(kpiNode);
                includeTrend = true;
          }

          i++;
        }

        childNode = childNode.nextSibling;
        if(childNode != null && childNode.tagName == 'ChildKpis')
        {
            var row = document.getElementById('kpirow_' + elementUniqueIdSuffix);
            var tableIdSuffix = elementUniqueIdSuffix.substring(0,elementUniqueIdSuffix.lastIndexOf('_'));
            var table = document.getElementById('kpitable_' + tableIdSuffix);
            ShowFilterColumn();
            document.getElementById('kpiExpandCollaspeCell_' + elementUniqueIdSuffix).innerHTML += '<img id=ExpandImagekpiExpandCollaspe_' + elementUniqueIdSuffix + ' expandmode="collapsed" onclick=toggleKpiExpandCollaspe() alt="" src="/_layouts/images/collapseplus.gif" width="16px" height="16px">';

            renderChildKpis(childNode, row.rowIndex + 1, table, showOnlyProblems, row.id, includeGoal, includeValue, includeStatus, includeTrend, 1);
        }
    }
}

function renderChildKpis(currentNode, currentIndex, table, showOnlyProblems, parentRowId, includeGoal, includeValue, includeStatus, includeTrend, depth)
{
    currentNode = currentNode.childNodes.item(0);
    while(currentNode != null && currentNode.tagName == 'Kpi')
    {
        var dataNode = currentNode.childNodes.item(0);

        if(showOnlyProblems == 'True' && getNodeText(dataNode) == 'No')
        {
            currentNode = currentNode.nextSibling;
            continue;
        }

        var newRow = table.insertRow(currentIndex);
        currentIndex++;

        newRow.setAttribute('parentRowId', parentRowId);
        newRow.id = parentRowId + '_' + currentIndex;
        newRow.style.display = 'none';
        newRow.className = newRow.previousSibling.className;
        newRow.pixelHeight = '25px';

        var newExpandCollaspeCell = newRow.insertCell();
        newExpandCollaspeCell.className = "ms-vb2";        
        newExpandCollaspeCell.innerHTML = " ";

        dataNode = dataNode.nextSibling;
        var newTitleCell = newRow.insertCell();
        newTitleCell.className = "ms-vb2";
        newTitleCell.innerHTML = '<div style="padding-left:' + depth*10 + 'px">' + getNodeText(dataNode) + '</div>';

        var kpiNode;
        while(dataNode.nextSibling != null && dataNode.nextSibling.nodeName == 'KpiData')
        {
            dataNode = dataNode.nextSibling;
            kpiNode = dataNode.childNodes.item(0);

            if(includeGoal)
            {
                var newGoalCell = newRow.insertCell();
                newGoalCell.className = "ms-vb2";
                newGoalCell.innerHTML = getNodeText(kpiNode);
            }

            kpiNode  = kpiNode.nextSibling;

            if(includeValue)
            {
                var newValueCell = newRow.insertCell();
                newValueCell.className = "ms-vb2";
                newValueCell.innerHTML = getNodeText(kpiNode);
            }

            if (includeStatus || includeTrend)
            {
                var newStatusCell = newRow.insertCell();
                newStatusCell.className = "ms-vb2";

                kpiNode = kpiNode.nextSibling;
                var StatusImage = getNodeText(kpiNode);
                if(includeStatus)
                {
                    newStatusCell.innerHTML = StatusImage;
                }

                kpiNode = kpiNode.nextSibling;
                var TrendImage = getNodeText(kpiNode);
                if(includeTrend)
                {
                    newStatusCell.innerHTML += TrendImage;
                }
            }

        }
        dataNode = dataNode.nextSibling;
        if(dataNode != null && dataNode.tagName == 'ChildKpis')
        {
            newTitleCell.innerHTML = '<img id=kpiExpandCollaspe_' + newRow.id + ' expandmode="collapsed" onclick=toggleKpiExpandCollaspe() src="/_layouts/images/collapseplus.gif" width="16px" height="16px" /><div style="padding-left:' + depth*10 + 'px">' + newTitleCell.innerHTML + '</div>';
            var index = renderChildKpis(dataNode, currentIndex, table, showOnlyProblems, newRow.id, includeGoal, includeValue, includeStatus, includeTrend, depth+1);
            currentIndex = index;
        }
        currentNode = currentNode.nextSibling;
    }
    return currentIndex;
}

function toggleKpiExpandCollaspe()
{                
    var displayMode;
    var displayIcon;
    var displayAttribute;
    var displayAlt;

    if(event.srcElement.getAttribute('expandmode') == 'collapsed')
    {
        displayMode = 'inline';
        displayIcon = '/_layouts/images/collapseminus.gif';
        displayAttribute = 'expanded';
        displayAlt = '';

    }
    else
    {
        displayMode = 'none';
        displayIcon = '/_layouts/images/collapseplus.gif';
        displayAttribute = 'collapsed';
        displayAlt = '';
    }

    var parentRow = event.srcElement.parentElement.parentElement;
    event.srcElement.src = displayIcon;
    event.srcElement.alt = displayAlt;
    event.srcElement.setAttribute('expandmode',displayAttribute);

    var potentialChildRow = parentRow.nextSibling;
    while(potentialChildRow != null)
    {
        var parentRowId = potentialChildRow.getAttribute('parentRowId');

        if(parentRowId == null)
        {
                return;
        }

        if(parentRowId == parentRow.id)
        {
                potentialChildRow.style.display = displayMode;
        }
        else if(parentRowId.indexOf(parentRow.id) != -1)
        {
                if(displayMode == 'none')
                {
                        potentialChildRow.style.display = displayMode;                
                }
                else
                {
                        var parent = document.getElementById(parentRowId);
                        if(parent == null)
                        {
                                potentialChildRow.style.display = displayMode;                                        
                        }
                        else
                        {
                                var image = getImageFromRow(parent);
                                if(image == null)
                                {
                                        potentialChildRow.style.display = displayMode;        
                                }
                                else
                                {
                                        if(image.getAttribute('expandmode') == 'expanded')
                                        {
                                                potentialChildRow.style.display = displayMode;                                                        
                                        }
                                }
                        }
                }
        }        
        potentialChildRow = potentialChildRow.nextSibling;
    }
}

function getImageFromRow(rowElement)
{
        var titleCell = rowElement.firstChild.nextSibling;
        if(titleCell.firstChild.tagName != 'IMG')
        {
                return null;
        }
        return titleCell.firstChild;
}

function loadXml(xml)
{
    var xmlHttp=null;
    try
    {
         xmlHttp = new ActiveXObject("Microsoft.XMLDOM");
    }
    catch (e)
    {
        xmlHttp = null;
    }

    if (xmlHttp != null)
    {
        xmlHttp.async="false";
        xmlHttp.loadXML(xml);
    }
    else
    {
        try
        {
            var domParser = new DOMParser();
            xmlHttp = domParser.parseFromString(xml, "text/xml");
        }
        catch (e)
        {
            alert(e.message);
            xmlHttp = null;
        }
    }

    return xmlHttp;
}

function getNodeText(node)
{
    var childNodes = node.childNodes
    return (childNodes==null || childNodes.length==0) ? '' : childNodes[0].nodeValue;
}

var filterColumnVisible = false;

function ShowFilterColumn()
{
    if (!filterColumnVisible)
    {
        var filterCells = getElementsByClassName(document, "ms-kpifiltercolumn");
        for (var i = 0; i < filterCells.length; i++)
        {
            filterCells[i].style.display = "";
        }
    }
}

function getElementsByClassName(node, classname)
{
    var a = [];
    var re = new RegExp('\\b' + classname + '\\b');
    var els = node.getElementsByTagName("*");
    for (var i=0, j=els.length; i<j; i++)
    {
        if(re.test(els[i].className))
        {
            a.push(els[i]);
        }
    }

    return a;
}
