﻿//Authentication logic
function LoadLogIn() {
    StartProcessing('Loading logon...');
    $.ajax({ url: "Authentication", dataType: "html", type: "GET", success: ProcessAuthenticationResponse, error: HandleError });
}

function Authenticate() {
    StartProcessing('Processing logon...');
    var form = $("#LogOn");
    $.ajax({ url: "Authentication/LogOn?" + form.serialize(), dataType: "html", type: "POST", success: ProcessAuthenticationResponse, error: HandleError });
}

function ProcessAuthenticationResponse(view) {
    var firstDiv = $(view).first(); //find('div:first');
    var title = firstDiv.attr('title');
    if (title == "Log On")
        OpenDialog(GetDialog(view));
    else if (title == "Validation Errors")
        OpenNewDialogAndCloseOldDialogIfNotError(view, "Log On");
    else if (title == "Administration") {
    ShowAdminSection(view);
    var logondialog = GetFirstDialogWithTitle("Log On");
    if (logondialog != null) CloseDialog(logondialog);
    }
    else {
        OpenNewDialogAndCloseOldDialogIfNotError(view, "Log On");
        ShowAuthenticationStatus(view);
    }
    EndProcessing();
}

function ShowAuthenticationStatus(view) {
    if(view !== null || view !== undefined)
        $("#AuthenticationStatus").html(view);
    else
    $.ajax({ url: "Authentication/Status", dataType: "html", type: "GET", success: function(view) { $("#AuthenticationStatus").html(view); } });
}



//Administration logic
function ShowAdminSection(view) {
    $("#page").html(view);
    LoadCurrentOrders();    
}

function LoadCurrentOrders() {
        var postUrl = "Order/CurrentOrders";
        var columnNames = ["Id","Name", "Time", "Date", "Zip", "Status"];
        var columnModel = [{ name: 'OrderId', index: 'OrderId', hidden: true }, { name: 'ContactName', index: 'ContactName', width: 200, sortable: false }, { name: 'Time', index: 'Time', width: 100, sortable: false }, { name: 'Date', index: 'Date', width: 100, sortable: false }, { name: 'Zip', index: 'Zip', width: 80, sortable: false }, { name: 'Status', index: 'Status', width: 200, sortable: false, editable: true, edittype: "select", editoptions: { value: "0:MissingCusotmerAccount;1:New;2:Delivered;3:Paid"}}];
        var gridExtraOptions = { url: postUrl, colNames: columnNames, colModel: columnModel, gridview: true, sortable: false, gridComplete: ShowLastRefreshDateTime, pager: "CurrentPickupsDivpager", loadtext: "Loading...", height: 300, onSelectRow: function(id) { $("#CurrentPickupsDivgrid").editRow(id, true, OnEditCurrentOrderStatus) } };
        LoadGrid("CurrentPickupsDiv", "Current Orders", gridExtraOptions);
    }

    function OnEditCurrentOrderStatus(gridRowId) {
        var dropdown = $("#" + gridRowId + "_Status");
        if(dropdown.hasEvent('change')) return;
        dropdown.change(function() {
            var rowId = this.id.substring(0, this.id.indexOf("_"));
            var orderId = $("#CurrentPickupsDivgrid").getCell(rowId, "OrderId");
            var statusId = $(this).val();
            $.ajax({ url: "Order/SaveOrderStatus?orderId=" + orderId + "&statusId=" + statusId, dataType: "text", type: "POST", success: RefreshCurrentOrders, error: HandleError });
        });
    }

function RefreshCurrentOrders() {
    var grid = $("#CurrentPickupsDivgrid");
    grid.trigger("reloadGrid");
}

function ShowLastRefreshDateTime() {
    var grid = $("#CurrentPickupsDivgrid");
    grid.setCaption("Current Pickups - Last refreshed at: " + GetCurrentDateTime());
}

function RefreshInvoices() {
    var grid = $("#" + invoicesGridId);
    grid.trigger("reloadGrid");
}

var invoicesGridId = "";
function ViewInvoices() {
    var postUrl = "Invoice/Search";
    var columnNames = ["OrderId", "Invoice Number", "Company Name", "Contact Name", "Time", "Date", "Status"];
    var columnModel = [{ name: 'OrderId', index: 'OrderId', hidden: true, search: false }, { name: 'InvoiceId', index: 'InvoiceId', search: false }, { name: 'CompanyName', index: 'CompanyName', width: 200 }, { name: 'ContactName', index: 'ContactName', width: 200, search: false }, { name: 'Time', index: 'Time', width: 100, search: false }, { name: 'Date', index: 'Date', width: 100, search: false }, { name: 'InvoiceStatus', index: 'InvoiceStatus', width: 200, search: false, editable: true, edittype: "select", editoptions: { value: "0:MissingCusotmerAccount;1:Processing;2:OutForDelivery;3:PendingPayment;4:Paid"}}];
    var gridExtraOptions = { url: postUrl, colNames: columnNames, colModel: columnModel, rowNum: 10, search: {odata:['equals']}, searchoptions: { attr: { title: "Search by Company or Contact Name"} }, sortname: "Name", sortorder: "asc", pager: "pager", onCellSelect: OnEditInvoiceStatus, ondblClickRow: ShowInvoice };
    var invoiceSearchDialog = GetGridDialog("Invoice Search", gridExtraOptions);
    invoicesGridId = invoiceSearchDialog.attr("id") + "datagrid";
    OpenDialog(invoiceSearchDialog);
}

function ShowInvoice(rowId, rowIndex, columnIndex, evt) {
    var grid = $("#" + invoicesGridId);
    var invoiceId = grid.getCell(rowId, "InvoiceId");
    $.ajax({ url: "Invoice/ShowInvoice?invoiceId=" + invoiceId, dataType: "html", success: function(view) { OpenDialog(GetDialog(view)); }, error: HandleError });
}

function OnEditInvoiceStatus(rowid, iCol, cellcontent, e) {
    if (iCol != 6) return;
    $("#" + invoicesGridId).editRow(rowid, true);
    var dropdown = $("#" + rowid + "_InvoiceStatus");
    if (dropdown.hasEvent('change')) return;
    dropdown.change(function() {
        var rowId = this.id.substring(0, this.id.indexOf("_"));
        var orderId = $("#" + invoicesGridId).getCell(rowId, "OrderId");
        var statusId = $(this).val();
        $.ajax({ url: "Order/SaveOrderStatus?orderId=" + orderId + "&statusId=" + statusId, dataType: "text", type: "POST", success: RefreshInvoices, error: HandleError });
    });
}

var customerSearchGrid = "";
function ModifyCustomers() {
    var postUrl = "Customer/Search";
    var columnNames = ["Id", "Customer Name", "Contact Name"];
    var columnModel = [{ name: 'Id', index: 'Id', hidden: true, search: false }, { name: 'CustomerName', index: 'CustomerName', width: 200 }, { name: 'ContactName', index: 'ContactName', width: 200, search: false }];
    var gridExtraOptions = { url: postUrl, colNames: columnNames, colModel: columnModel, rowNum: 10, search: { odata: ['equals'] }, searchoptions: { attr: { title: "Search by Company or Contact Name"} }, sortname: "Name", sortorder: "asc", pager: "pager", ondblClickRow: ShowUpdateCustomer };
    var customerSearchDialog = GetGridDialog("Customer Search", gridExtraOptions);
    customerSearchGrid = customerSearchDialog.attr("id") + "datagrid";
    OpenDialog(customerSearchDialog);
}

function ShowUpdateCustomer(rowId, rowIndex, columnIndex, evt) {
    var grid = $("#" + customerSearchGrid);
    var customerId = grid.getCell(rowId, "Id");
    $.ajax({ url: "Customer/Edit/" + customerId, dataType: "html", success: function(view) { OpenDialog(GetDialog(view)); }, error: HandleError });
}

function UpdateCustomer() {
    var form = $("#UpdateCustomerForm");
    StartProcessing('Processing customer data...');
    $.ajax({ url: "Customer/Edit?" + form.serialize(), dataType: "html", type: "POST", success: function(view) { OpenNewDialogAndCloseOldDialogIfNotError(view, "Update Customer"); EndProcessing(); ShowMessage("Successfully updated customer") }, error: HandleError });
}

//Quote logic
function GetQuote() {
    StartProcessing('Processing quote...');
    var form = $('#Quote');
    var fromZip = form.find("#FromZip").val();
    var toZip = form.find("#ToZip").val();
    GoogleMapsGetDistance(fromZip, toZip, OnGetDistanceMilesSendQuoteRequest);

}

function OnGetDistanceMilesSendQuoteRequest(miles) {
    var form = $('#Quote');
    $.ajax({ url: "Quote/GetQuote?" + form.serialize() + "&Miles=" + miles, dataType: "html", type: "POST", success: function(view) { OpenDialog(GetDialog(view)); EndProcessing(); }, error: HandleError });
}

function Ship() {
    StartProcessing('Processing order...');
    var quoteId = $('#QuoteId').val();
    $.ajax({ url: "Quote/Ship?quoteId=" + quoteId, dataType: "html", type: "POST", success: function(view) { OpenNewDialogAndCloseOldDialogIfNotError(view, "Quote Estimate"); EndProcessing(); }, error: HandleError });
}

//Views logic
$(document).ready(function() {
    LoadHome();
    EnableList("PackageTypeId", "Quote/GetPackageTypes");
});

function LoadHome() {
    $("#AjaxLoader").fadeOut();
    $("body").attr("id", "page1");
    $.ajax({ url: "Home/Home", dataType: "html", success: function(view) { $('#AjaxLoader').html(view); $("#AjaxLoader").fadeIn(); EndProcessing(); }, error: HandleError, beforeSend: StartProcessing });

}

function LoadServices() {
    $("#AjaxLoader").fadeOut();
    $.ajax({ url: "Home/Services", dataType: "html", success: function(view) { $('#AjaxLoader').html(view); $("#AjaxLoader").fadeIn(); EndProcessing(); }, error: HandleError, beforeSend: StartProcessing });


}

function LoadContacts() {
    $("#AjaxLoader").fadeOut();
    $.ajax({ url: "Home/Contacts", dataType: "html", success: function(view) { $('#AjaxLoader').html(view); $("#AjaxLoader").fadeIn(); EndProcessing(); }, error: HandleError, beforeSend: StartProcessing });


}

function SendContactForm() {
    StartProcessing('Sending contact information.');
    var form = $("#contactform");
    $.ajax({ url: "Home/SendContactForm?" + form.serialize(), dataType: "text", type: "POST", success: function(view) { ShowMessage("Message sent."); EndProcessing(); }, error: HandleError });
    
 }

function LoadMissionStatement() {
    $("#AjaxLoader").fadeOut();
    $.ajax({ url: "Home/MissionStatement", dataType: "html", success: function(view) { $('#AjaxLoader').html(view); $("#AjaxLoader").fadeIn(); EndProcessing(); }, error: HandleError, beforeSend: StartProcessing });


}

function LoadTestimonial(client) {
    if(client == null)
    {
        $("#AjaxLoader").fadeOut();
        $.ajax({ url: "Testimonials", dataType: "html", success: function(view) { $('#AjaxLoader').html(view); $("#AjaxLoader").fadeIn(); EndProcessing(); }, error: HandleError, beforeSend: StartProcessing });

    }

    if (client == "zimmer") { 
        $("#ClientNameDiv").html("zimmer");
        $("#ClientMessageDiv").html("In the course of the past few months we have used On My Way Couriers, Inc. for all of our errands and we are pleased to say that we are ecstatic with their service. They are very efficient, have flexible rates, and are always on time at anytime of the day. We will continue to use O.M.W. and the excellent service they provide. ");
        $("#ClientCardImage").attr("src", "../../Content/images/ZimmerClient.gif");
        return;
    }
    
    if (client == "delaresma") { 
        $("#ClientNameDiv").html("De La Resma Insurance Group");
        $("#ClientMessageDiv").html("Every time we need important documents brought to us, we trust On My Way to get the job done. I highly recommend On My Way and their friendly staff for any delivery service you may need. Thanks OMW for all your help. ");
        $("#ClientCardImage").attr("src", "../../Content/images/DeLaResmaInsuranceClient.gif");
        return;
    }
    
    if (client == "thierry") { 
        $("#ClientNameDiv").html("Thierry's Catering and Event Design");
        $("#ClientMessageDiv").html("I manage a food catering business and when my customers place an order they want it fresh and on time. Thierry’s provides our customers with same day delivery with the help of On My Way Couriers and their Flat Rate Express service. We are glad to have OMW as part of our team.");
        $("#ClientCardImage").attr("src", "../../Content/images/ThierrysClient.gif");
    }
    
}

//Customer logic
function SaveCustomer() {
    var form = $("#SaveCustomerForm");
    StartProcessing('Processing customer creation...');
    $.ajax({ url: "Customer/Create?" + form.serialize(), dataType: "html", type: "POST", success: function(view) { OpenNewDialogAndCloseOldDialogIfNotError(view, "Create an account with us to qualify for the 15% discount"); ShowAuthenticationStatus(view); EndProcessing(); }, error: HandleError });
 }

 //Order logic
 function ShowOtherPackageTextAreaDisplay() {
     var row = $("#OtherPackageTypeDescriptionRow");
     row.fadeIn();
 }

  function HideOtherPackageTextAreaDisplay() {
     var row = $("#OtherPackageTypeDescriptionRow");
     row.fadeOut();
 }

 function OnPackageTypeChange(dropdown) {
     var index = dropdown.selectedIndex;
     var value = dropdown.options[index].value;

     if (value == "4") ShowOtherPackageTextAreaDisplay();
     else HideOtherPackageTextAreaDisplay();
     UpdatePrice();
 }

 function UpdatePrice() {
     var form = $("#InsertOrder");
     var packageTypeId = form.find("#OrderPackagetypeid").val();
     var fromAddressLine1 = form.find("#Pickupaddressline1").val();
     if (fromAddressLine1.length < 4) return;
     var fromZip = form.find("#Pickupzip").val();
     if (fromZip.length < 5) return;
     var fromAddress = fromAddressLine1 + ", " + fromZip;
     var toAddressLine1 = form.find("#Shiptoaddressline1").val();
     if (toAddressLine1.length < 4) return;
     var toZip = form.find("#Shiptozip").val();
     if (toZip.length < 5) return;
     var toAddress = toAddressLine1 + ", " + toZip;
     if (IsValidNumber(packageTypeId) === false) return;
     GoogleMapsGetDistance(fromAddress, toAddress, OnGetDistanceMilesForOrder);

 }

 function OnGetDistanceMilesForOrder(miles) {
     $("#OrderMiles").html(miles);
     var packageTypeId = $("#OrderPackagetypeid").val();
     var pieces = $("#OrderPieces").val();
     $.ajax({ url: "Order/GetUpdatedPrice?packageTypeId=" + packageTypeId + "&miles=" + miles + "&pieces=" + pieces, dataType: "text", type: "POST", success: function(text) { $("#OrderPrice").html(text); } });
 }

 function PlaceOrder() {
     var form = $("#InsertOrder");
     StartProcessing('Processing order...');
     var fromAddressLine1 = form.find("#Pickupaddressline1").val();
     var fromZip = form.find("#Pickupzip").val();
     var fromAddress = fromAddressLine1 + ", " + fromZip;
     var toAddressLine1 = form.find("#Shiptoaddressline1").val();
     var toZip = form.find("#Shiptozip").val();
     var toAddress = toAddressLine1 + ", " + toZip;
     GoogleMapsGetDistance(fromAddress, toAddress, OnGetDistanceMilesForPlaceOrder);

 }

 function OnGetDistanceMilesForPlaceOrder(miles) {
     var form = $("#InsertOrder");
     $.ajax({ url: "Order/Create?" + form.serialize() + "&miles=" + miles, dataType: "html", type: "POST", success: function(view) { OpenNewDialogAndCloseOldDialogIfNotError(view, "Place Order"); EndProcessing(); }, error: HandleError });
  }


  //Invoice logic

  function PrintInvoice() {
      $('#OrderInvoice').printElement({ pageTitle: 'OMW Couriers Invoice' });
  }
