var commandName = "";
var tableView = null;
var ordersView = null;
var ordersCommandName = "";

function RadGrid1_Command(sender, args) {
    args.set_cancel(true);

    collapseItems(sender);
    
    commandName = args.get_commandName();

    WebService.GetCustomers(tableView.get_currentPageIndex() * tableView.get_pageSize(), tableView.get_pageSize(),
                    tableView.get_sortExpressions().toString(), tableView.get_filterExpressions().toDynamicLinq(),
                        updateGrid);
}

function updateGrid(result) {
    tableView.set_dataSource(result);
    tableView.dataBind();

    var dataItems = tableView.get_dataItems();

    if (commandName == "Filter" || commandName == "Load") {
        WebService.GetCustomersCount(updateVirtualItemCount);
    }
}

function updateVirtualItemCount(result) {
    tableView.set_virtualItemCount(result);
}

function collapseItems(sender) {
    var dataItems = sender.get_masterTableView().get_dataItems();
    for (var i = 0, length = dataItems.length; i < length; i++) {
        var input = dataItems[i].get_element().cells[0].getElementsByTagName("input")[0];
        if (input.className == "rgCollapse") {
            input.click();
        }
    }
}

function RadGrid1_HierarchyExpanding(sender, args) {
    collapseItems(sender);

    var customerID = args.getDataKeyValue("CustomerID");
    var nestedViewItem = args.get_nestedViewItem();

    nestedViewItem.cells[1].appendChild($get("RadGrid2")); 

    ordersView = $find("RadGrid2").get_masterTableView();

    ordersCommandName = "Load";

    WebService.GetOrdersByCustomerID(customerID, ordersView.get_currentPageIndex() * ordersView.get_pageSize(), ordersView.get_pageSize(),
                    ordersView.get_sortExpressions().toString(), ordersView.get_filterExpressions().toDynamicLinq(),
                        updateOrdersGrid);
}

function updateOrdersGrid(result) {
    ordersView.set_dataSource(result);
    ordersView.dataBind();

    if (ordersCommandName == "Filter" || ordersCommandName == "Load") {
        WebService.GetOrdersByCustomerIDCount(updateOrdersVirtualItemCount);
    }
}

function updateOrdersVirtualItemCount(result) {
    ordersView.set_virtualItemCount(result);
}

function RadGrid2_Command(sender, args) {
    ordersView = sender.get_masterTableView();
    var nestedViewItem = sender.get_element().parentNode.parentNode;
    var parentGridDataItem = $find(Telerik.Web.UI.Grid.GetNodePreviousSiblingByTagName(nestedViewItem, "tr").id);
    var customerID = parentGridDataItem.getDataKeyValue("CustomerID");

    args.set_cancel(true);

    ordersCommandName = args.get_commandName();

    WebService.GetOrdersByCustomerID(customerID, ordersView.get_currentPageIndex() * ordersView.get_pageSize(), ordersView.get_pageSize(),
                    ordersView.get_sortExpressions().toString(), ordersView.get_filterExpressions().toDynamicLinq(),
                        updateOrdersGrid);
}