﻿// This file contains the scripts used in the Operator Portal


/* TODO: Check if there is a better alternative for this workaround
* 
*  When deploying the website, it is possibe that it is not deployed in IIS as root
*  In that case the baselocation will hold the subdirectory path which in turn will
*  be used in the replaceContent function.
*
*  This is set in the onload function of the masterpage by constructing a serverside url
*
*  This is a workaround for IIS 5.1
*  Deploying on IIS 7 should work without this extra step.
*/
var baselocation = "";
function setBaseLocation(location) {
    if (location != "/") {
        baselocation = location;
    }
}

function redirectToControllerURL(actionName, controllerName, id) {
    window.location = baselocation + "/" + encodeURIComponent(controllerName) + "/" + encodeURIComponent(actionName) + "/" + encodeURIComponent(id);
}

// replaces the content of the domElement with the result from the controller action
function replaceContent(actionName, controllerName, id, domElement) {
    replaceContent(actionName, controllerName, id, domElement, true);
}

// replaces the content of the domElement with the result from the controller action
function replaceContent(actionName, controllerName, id, domElement, useEncodeURIComponent) {
    var url;

    if (useEncodeURIComponent) {
        url = baselocation + "/" + encodeURIComponent(controllerName) + "/" + encodeURIComponent(actionName) + "/" + encodeURIComponent(id);
    }
    else {
        url = baselocation + "/" + controllerName + "/" + actionName + "/" + id;
    }

    Sys.Mvc.MvcHelpers._asyncRequest(url, 'get', '', null, { insertionMode: Sys.Mvc.InsertionMode.replace,
        // since new html content is generated, we need to bind the jQuery functions again
        onSuccess: Function.createDelegate(this, bindJQueryFunctions),
        updateTargetId: domElement
    });    
}

// do not add functions directly to document ready.
// Ajax calls will not trigger a document ready
// However by using an onSuccess = "bindJQueryFunctions" Ajax option all functions can be bound again
$(document).ready(function() {
    bindJQueryFunctions();
});


function ShowLoading() {
    document.getElementById('mainContent').style.display = 'none';      // Hide main content
    document.getElementById('loadingContent').style.display = '';       // Show loading gif
}
function HideLoading() {
    document.getElementById('mainContent').style.display = '';          // Show main content
    document.getElementById('loadingContent').style.display = 'none';   // Hide loading gif
}

function bindJQueryFunctions() {

    // apply highligting functions to all elements of the highlight class
    $('.highlightOnMouseOver').each(function() {
        $(this).mouseover(function() {
            $(this).addClass('highlight');
        })
        $(this).mouseout(function() {
            $(this).removeClass('highlight');
        })
    });

    // for each table that is of the class filtarable
    $('table.filterable').each(function() {

        var $table = $(this);

        /*
        * active filters will hold the current filters for the whole table
        *
        * [dropdownName][keyword]
        */
        var activeFilters = {};
        var $selectTable = $('<table></table>');
        var $selectTableHeader = $('<tr></tr>');
        var $selectTableDropDownRow = $('<tr></tr>');

        //for each table heading
        $table.find('th').each(function(column) {


            if (!$(this).is('.filter-column')) {
                // if the table heading is not a filtarable column only add a header
                var $selectTableHeaderColumn = $('<th>' + $(this).text() + '</th>');
                $selectTableHeaderColumn.appendTo($selectTableHeader);

                var $selectTableDropDownColumn = $('<td>&nbsp;</td>');
                $selectTableDropDownColumn.appendTo($selectTableDropDownRow);

            }
            else {
                // if the table heading is a filtarable column
                // try adding it to a dropdown list
                var $selectTableHeaderColumn = $('<th>' + $(this).text() + '</th>');
                $selectTableHeaderColumn.appendTo($selectTableHeader);

                var $dropdownList = $('<select id="dropDown' + $(this).text() + '"></select>');
                $dropdownList.append('<option value="All" >All</option>');
                $dropdownList.change(function(event) {

                    var selected = this.value;
                    activeFilters[column] = selected;

                    // go over each row
                    $table.find('tbody tr').each(function() {

                        var unhide = true;
                        var index = 0;

                        // check for each column if a filter applies
                        $('td', this).each(function() {

                            if (this.innerText != activeFilters[index] &&
                                 activeFilters[index] != "All" &&
                                  activeFilters[index] != undefined) {

                                unhide = false;
                            }
                            index++;
                        });

                        // if all conditions pass, show
                        if (unhide == true) {
                            $(this).show().removeClass('filtered');
                        }

                        //$('th', this).length ???
                        if (!unhide && $('th', this).length == 0) {

                            $(this).hide().addClass('filtered');
                        }

                    });
                })

                var $selectTableDropDownColumn = $('<td></td>');
                $dropdownList.appendTo($selectTableDropDownColumn);
                $selectTableDropDownColumn.appendTo($selectTableDropDownRow);

                // will hold all the available options
                var keywords = {};

                // create an array for all the text that occurs in the column
                $table.find('tbody tr td').filter(':nth-child(' + (column + 1) + ')').each(function() {
                    // use the text itself as the index so multiple occurances are listed once
                    keywords[$(this).text()] = $(this).text();
                });

                // add each keyword found to the dropdownlist
                $.each(keywords, function(index, keyword) {
                    $dropdownList.append('<option value="' + keyword + '" >' + keyword + '</option>');
                });
            }

        });
        $selectTableHeader.appendTo($selectTable);
        $selectTableDropDownRow.appendTo($selectTable);
        $selectTable.insertBefore($table);
        $('</br>').insertBefore($table);

    });

    HideLoading();
}

//to check if newNode is direct child of newNode
function IsChild (currentNode, newNode)
{
    if(newNode.parent().parent().parent()[0].id == currentNode.parent()[0].id)
    {
        return true;
    }
    return false;        
}
//to check if the node is a root node
function IsRootNode(currentNode)
{
    var str = currentNode.parent()[0].id;
    if(str.match('root')== 'root')
    {
        return true;
    }
    else
    {
        return false;
    }
}

//to check if newNode is direct child of newNode
function IsParent (newNode, currentNode)
{
    if(IsRootNode(currentNode))
    {
        return false;
    }
    if(currentNode.parent().parent().parent()[0].id == newNode.parent()[0].id)
    {
        return true;
    }
    else
    {
        return IsParent( newNode, currentNode.parent().parent()) 
    }
}


//to check if two nodes are siblings
function IsSibling (currentNode, newNode)
{
    var siblings = newNode.parent().siblings();
    
    for (var index=0; index < siblings.length; index++)
    {
        if (currentNode.parent()[0].id == siblings[index].id)
        {   
            return true;
        }
    }
    return false;        
}
//to check is the two nodes are the same
function IsSameNode (currentNode, newNode)
{
    if(currentNode.parent()[0].id == newNode.parent()[0].id)
    {   
        return true;
    }
    else
    {
        return false;        
    }
}

//recursive function to close expanded menu
function SlideUp (currentNode, newNode)
{
    
    //alert('currentNode '+ currentNode.parent()[0].id);
    //alert('newNode '+ newNode.parent()[0].id);
        

    if(IsSameNode(currentNode, newNode))
    {
        //do nothing; return the recursive function
    }
    else if (IsChild(currentNode, newNode))
    {
        //do nothing; return the recursive function
    }
    else if (IsParent(newNode, currentNode)) //new node is parent of current
    {
        if(currentNode[0].nodeName == 'UL')
        {
            currentNode.slideUp('normal');
        }
        else
        {
            currentNode.next().slideUp('normal');
        }
        SlideUp(currentNode.parent().parent(),newNode);
    }
    else if (IsSibling(currentNode, newNode))
    {
        if(currentNode[0].nodeName == 'UL')
        {
            currentNode.slideUp('normal');
        }
        else
        {
            currentNode.next().slideUp('normal');
        }
    }
    else if (IsRootNode(currentNode))
    {
        currentNode.next().slideUp('normal');
    }
    else 
    {
        if(currentNode[0].nodeName !='UL')
        {
            if(currentNode.next().children().length !=0) //there is menu expanded
            {
                currentNode.next().slideUp('normal'); //close the menu
                //resursive call stepping back to the parent
                SlideUp(currentNode.parent().parent(),newNode);
            }
            else // there is no menu expande; in other words this is the last menu
            {
                //resursive call stepping back to the parent
                SlideUp(currentNode.parent().parent(),newNode);
            }
        }
        else //== 'UL'
        {
            //resursive call stepping back to the parent
            currentNode.slideUp('normal');
            SlideUp(currentNode.parent().parent(),newNode);
        }
    }   
}

function getWindowheight() 
{ 
    var windowheight = 0; 
    if (typeof(window.innerheight) == 'number') 
    { 
        windowheight = window.innerHeight; 
    } 
    else 
    { 
        if (document.documentElement && document.documentElement.clientHeight) 
        { 
            windowheight = document.documentElement.clientHeight; 
        } 
        else 
        { 
            if (document.body && document.body.clientHeight) 
            { 
                windowheight = document.body.clientHeight; 
            } 
         } 
     } 
     return windowheight; 
} 

function setGround() 
{ 
    var groundElement = document.getElementById('mainContent');
    var leftmenu = document.getElementById('leftMenu');
    if ((groundElement) && (leftmenu))
    { 
        var groundheight = getWindowheight() - 160 - 25; //160 see css file from top and factor 25 title from top
        var menuheight = groundheight+2; //top 2 pixel extra
        if (groundheight > 0) 
        { 
            groundElement.style.height = groundheight + 'px'; 
            leftmenu.style.height = menuheight + 'px';        
        }         
     }          
 } 
