///<reference name="Microsoft.Ajax.js"/>
///<reference path="DataService.js"/>

var currentSort = "";
var currentFilter = [];
var sortCell = null;
var clearSortImage = false;
var startGetData;
var startUpdateGrid;
var pageCount;

function pageLoad()
{
    $find(gridId)._getFilterMenu().add_itemClicking(onFilterCommand);       
}

function doQuery(query, onSuccsessHandler, onFailureHandler, context)
{    
    var northwindService = new Sys.Data.DataService("NorthwindDataService.svc");

    northwindService.query(query, onSuccsessHandler, onFailureHandler, context);
}

function onFilterCommand(sender, args)
{
    args.set_cancel(true);
    
    var filterCommand = args.get_item().get_value();
    var columnName = args.get_item()._filterMenu_column_uniqueName;
    var filterRow = $find(gridId).get_masterTableView()._getTableFilterRow()
    var index = $find(gridId).get_masterTableView()._getCellIndexByColumnUniqueNameFromTableRowElement(filterRow, columnName);
    
    var filterInput = filterRow.cells[index].getElementsByTagName("input")[0];
    var filterValue = filterInput.value;
    
    if(filterInput.type == "checkbox")
    {
        filterValue = filterInput.checked;
    }
    
    if(filterCommand == "NoFilter")
    {
        if(filterInput.type == "checkbox")
        {
            filterInput.checked = false;
        }
        else
        {
            filterInput.value = "";
        }
    }
    else
    {
        if(filterValue == "" && 
           filterInput.type != "checkbox" &&
            (filterCommand != "IsEmpty" && 
            filterCommand != "NotIsEmpty" &&
            filterCommand != "IsNull" &&
            filterCommand != "NotIsNull"))
        {
            alert("No filter value!");
            return;
        }
    }

    sender.hide();
    
    var found = false;
    for(var i=0,length = currentFilter.length; i < length; i++)
    {
        if (currentFilter[i].first == columnName)
        {
            if (filterCommand == "NoFilter")
            {
                Array.remove(currentFilter,currentFilter[i]);
            }
            else{
                currentFilter[i].second = String.format("{0}:{1}:{2}", columnName, filterCommand, filterValue);
            }
            found = true;
            break;
        }
    }
    
    if (!found)
    {
        var tempFilter = new Object();
        tempFilter.first = columnName;
        tempFilter.second = String.format("{0}:{1}:{2}", columnName, filterCommand, filterValue);
        Array.add(currentFilter, tempFilter);
    }
    
    startGetData = new Date();
    
    createQuery(currentPage, pageSize, currentSort, currentFilter, true);
    //WebService.GetData(currentPage, pageSize, currentSort, currentFilter, false, onSuccess);
    
    currentPage = 0;
}

function onSortCommand(sender, argument)
{
    sortCell = sender;

    if(currentSort == argument)
    {
        argument = String.format("{0} desc", argument);
        clearSortImage = false;
    }
    else
    {
        clearSortImage = true;
    }

    if (currentSort.indexOf("desc") != -1)
    {
        argument = "";
        clearSortImage = true;
        sortCell = null;
    }

    currentSort = argument;

    $get("loading").style.visibility = "visible";

    startGetData = new Date();

    $get("timeData").innerHTML = $get("timeGrid").innerHTML = "";

    //WebService.GetData(currentPage, pageSize, argument, currentFilter, false, onSuccess);
    createQuery(currentPage, pageSize, currentSort, currentFilter, true);
}

function onPageCommand(argument)
{
    if(currentPage == 0 && argument != "next") return;
    if(currentPage == pageCount && argument == "next") return;

    if(argument == "next")
    {
        currentPage += pageSize;
    }
    else
    {
        currentPage -= pageSize;
    }

    $get("loading").style.visibility = "visible";
    
    startGetData = new Date();

    $get("timeData").innerHTML = $get("timeGrid").innerHTML = "";

    createQuery(currentPage, pageSize, currentSort, currentFilter, true);
    //WebService.GetData(currentPage, pageSize, currentSort, currentFilter, false, onSuccess);
}
function createQuery(currentPage, pageSize, sortExpression, filteringExpression, enablePaging)
{    
    var sb = new Sys.StringBuilder();
    sb.append("Customers?");    
    if (sortExpression)
    {
        sb.append(String.format("&$orderby={0}", sortExpression));
    }

    if (filteringExpression && filteringExpression.length)
    {
        sb.append("&$filter=");
        for (var i = 0, length = filteringExpression.length; i < length; i++)
        {
            if (i > 0)
            {
                sb.append(" and ");
            }
            
            if (filteringExpression[i].second)
            {
                var exp = filteringExpression[i].second.split(":");
                var propertyName = exp[0];
                var filterFunction = exp[1];
                var value = exp[2];

                if (filterFunction == "Contains")
                {
                    sb.append(String.format(" contains({0},'{1}') ", propertyName, value));
                }
                else if (filterFunction == "DoesNotContain")
                {
                    sb.append(String.format(" not contains({0},'{1}') ", propertyName, value));
                }
                else if (filterFunction == "StartsWith")
                {
                    sb.append(String.format(" startswith({0},'{1}') ", propertyName, value));
                }
                else if (filterFunction == "EndsWith")
                {
                    sb.append(String.format(" endswith({0},'{1}') ", propertyName, value));
                }                
                else if (filterFunction == "EqualTo")
                {
                    sb.append(String.format(" {0} eq '{1}' ", propertyName, value));
                }
                else if (filterFunction == "NotEqualTo")
                {
                    sb.append(String.format(" {0} ne '{1}' ", propertyName, value));
                }
                else if (filterFunction == "GreaterThanOrEqualTo")
                {
                    sb.append(String.format(" {0} gteq '{1}' ", propertyName, value));
                }
                else if (filterFunction == "LessThanOrEqualTo")
                {
                    sb.append(String.format(" {0} lteq '{1}' ", propertyName, value));
                }
                else if (filterFunction == "GreaterThan")
                {
                    sb.append(String.format(" {0} gt '{1}' ", propertyName, value));
                }
                else if (filterFunction == "LessThan")
                {
                    sb.append(String.format(" {0} lt '{1}' ", propertyName, value));
                }
                else if (filterFunction == "IsEmpty")
                {
                    sb.append(String.format(" {0} eq '') ", propertyName));
                }
                else if (filterFunction == "IsNotEmpty")
                {
                    sb.append(String.format(" {0} ne '') ", propertyName));
                }
                else if (filterFunction == "IsNull")
                {
                    sb.append(String.format(" {0} eq null) ", propertyName));
                }
                else if (filterFunction == "IsNotNull")
                {
                    sb.append(String.format(" {0} ne null) ", propertyName));
                }
                else if (filterFunction == "Between")
                {
                    sb.append(String.format(" ({0} gteq '{1}' and {0} lteq '{2}') ", propertyName, value.split(' ')[0], value.split(' ')[1]));
                }
                else if (filterFunction == "NotBetween")
                {
                    sb.append(String.format(" ({0} lteq '{1}' or {0} gteq '{2}') ", propertyName, value.split(' ')[0], value.split(' ')[1]));
                }
            }            
        }
    }
    
    var contextQuery = sb.toString();
    if (enablePaging)
    {
        sb.append(String.format("&$top={0}&$skip={1}", pageSize, currentPage));
    }
    doQuery(sb.toString(), onSuccess, null, contextQuery);
}
 
function onSuccess(result, context)
{     
   $get("timeData").innerHTML = String.format("Time to get data: {0} ms", new Date() - startGetData);
   
   startUpdateGrid = new Date();

   updateGrid(result);


   updatePager(result.length, context);

   $get("loading").style.visibility = "hidden";

   updateSortImage();
   
   $get("timeGrid").innerHTML = String.format("Time to update grid: {0} ms", new Date() - startUpdateGrid);
}

function updateGrid(result)
{
   var tableView = $find(gridId).get_masterTableView();
   var dataItems = tableView.get_dataItems();
   var columns = tableView.get_columns();

   var itemDisplay = (result.length == 0)? "none" : "";
   for(var i = 0, l1 = dataItems.length; i < l1; i++)
   {       
       var row = $get(dataItems[i].get_id());
       
       row.style.display = itemDisplay;
       
       if(result.length == 0) continue;

       if(i >= result.length)
       {
            row.style.display = "none";
            continue
       }
       
       for(var j = 0, l2 = columns.length; j < l2; j++)
       {
           var uniqueName = columns[j].get_uniqueName();
           var cell = tableView.getCellByColumnUniqueName(dataItems[i], uniqueName);
           var value = result[i][uniqueName]; 
           cell.innerHTML = result[i][uniqueName];
       }
   }
}

function updatePager(totalItemsOnPage, currentQuery)
{
   $get("currentPageLabel").innerHTML = currentPage / pageSize + 1;
   $get("startIndexLabel").innerHTML = currentPage + 1;
   $get("endIndexLabel").innerHTML = (totalItemsOnPage < pageSize) ? Math.min(currentPage + pageSize, totalItemsOnPage) : currentPage + pageSize;

   doQuery(currentQuery, onTotalRowsCountSuccess, null, null);
//   WebService.TotalRowsCount(onTotalRowsCountSuccess);
}

function onTotalRowsCountSuccess(result)
{
    var recordsCount = result.length;
    $get("totalItemsLabel").innerHTML = recordsCount;
    var totalPages = pageCount = Math.round(recordsCount / pageSize);
    $get("totalPagesLabel").innerHTML = (totalPages == 0) ? 1 : totalPages;
}

function updateSortImage()
{
    var sortAscImage = String.format("<img id='sortAscImage' src='{0}'/>", sortAscUrl);
    var sortDescImage = String.format("<img id='sortDescImage' src='{0}'/>", sortDescUrl);

    if(clearSortImage)
    {
        if($get("sortAscImage")){$get("sortAscImage").parentNode.removeChild($get("sortAscImage"))}
        if($get("sortDescImage")){$get("sortDescImage").parentNode.removeChild($get("sortDescImage"))}
    }

    if(sortCell != null)
    {
        if(sortCell.parentNode.innerHTML.indexOf(sortAscUrl) != -1)
        {
            sortCell.parentNode.innerHTML = sortCell.parentNode.innerHTML.replace(sortAscUrl, sortDescUrl);
        }
        else if(sortCell.parentNode.innerHTML.indexOf(sortDescImage) != -1)
        {
            sortCell.parentNode.innerHTML = sortCell.parentNode.innerHTML.replace(sortDescUrl, sortAscUrl);
        }
        else
        {
            var images = sortCell.parentNode.getElementsByTagName("img");
            if(images.length > 0)
            {
                sortCell.parentNode.removeChild(images[0]);
            }
            sortCell.parentNode.innerHTML = String.format("{0}&nbsp;{1}", sortCell.parentNode.innerHTML, sortAscImage);
        }
        sortCell = null;
    }
}