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

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

    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 RadGrid1_HierarchyExpanding(sender, args) {
//collapse the rest of the grid items here
    var customerID = args.getDataKeyValue("CustomerID");
    var nestedViewItem = args.get_nestedViewItem();

    $get("RadGrid2").style.display = "";
    nestedViewItem.cells[1].appendChild($get("RadGrid2"));
    ordersView = $telerik.findControl(nestedViewItem, "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);
}