var crudTenantBaseUrl = "Tenant";
var crudProductBaseUrl = "Product";

var GRID_PAGE_SIZE = 10
var AUTO_COMPLETE_PAGE_SIZE = 8

var GRID_MAIN_HEIGHT = 500
var GRID_POPUP_HEIGHT = 130
var POPUP_WIDTH = 520

var ID = {
    GridMain: "gridTenant",
    GridPopup: "gridTenantApps",
    FormMain: "formMain",
    FormPopup: "popupTemplate",
    CommandTemplate: "commandTemplate"
};

var COLUMNS_GRID_MAIN = {
    BillingAccountNumber: { Name: "BillingAccountNumber", Width: 170 },
    CustomerName: { Name: "CustomerName", Width: 150 },
    InvitationEmail: { Name: "InvitationEmail", Width: 200 },
    ProductID: { Name: "ProductID", Width: 50 },
    ProductName: { Name: "ProductName", Width: 170 },
    SageCustomerNumber: { Name: "SageCustomerNumber", Width: 170 },
    TenantID: { Name: "TenantID", Width: 50 },
    TenantName: { Name: "TenantName", Width: 170 }
};

var COLUMNS_GRID_POPUP = {
    BillingSubscriptionNumber: { Name: "BillingSubscriptionNumber", Width: 175 },
    Description: { Name: "Description", Width: 150 },
    IsSuspended: { Name: "IsSuspended", Width: 85 },
    TenantAppID: { Name: "TenantAppID", Width: 50 }
};

var keyFieldDataSource = new kendo.data.DataSource({
    transport: {
        read: {
            url: crudTenantBaseUrl + "/KeyChangeList",
            async: false
        },
        parameterMap: function (data) {
            return { SageCust: $("#" + COLUMNS_GRID_MAIN.SageCustomerNumber.Name).val().rtrim() };
        }
    },
    error: function (e) {
        alert("Unable to get Sage Customer Numbers.");
    }
});

var gridTenantAppsChanged = false;

$(document).ready(function () {
    //add kendo validator to page
    window.validator = $("#" + ID.FormMain).kendoValidator().data(KENDO_DATA.Validator);

    var gridDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: crudTenantBaseUrl + "/TenantList",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                type: "post"
            },
            update: {
                url: crudTenantBaseUrl + "/Update",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                type: "post"
            },
            destroy: {
                url: crudTenantBaseUrl + "/Delete",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                type: "post"
            },
            create: {
                url: crudTenantBaseUrl + "/Add",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                type: "post"
            },

            parameterMap: function (options, operation) {
                options.__RequestVerificationToken = $("input[name=__RequestVerificationToken]").val();
                return options;
                //if (operation !== "read" && options.models) {
                //    return JSON.stringify(options);
                //}
            }
        },
        batch: true,
        pageSize: GRID_PAGE_SIZE,
        schema: {
            model: {
                id: COLUMNS_GRID_MAIN.TenantID.Name,
                fields: {
                    TenantID: { type: "guid", editable: false, nullable: true },
                    SageCustomerNumber: {
                        type: "string",
                        editable: true,
                    },
                    CustomerName: { type: "string", editable: true },
                    InvitationEmail: { type: "string", editable: true },
                    ProductName: { type: "string", editable: true },
                    BillingAccountNumber: { type: "string", editable: true }
                }
            }
        },
        error: function (e) {
            alert("error");
        }
    });

    $("#" + ID.GridMain).kendoGrid({
        dataSource: gridDataSource,
        height: GRID_MAIN_HEIGHT,
        pageable: true,
        toolbar: [{ name: "create", text: "Add Tenant" } ],
        columns: [
            //{ field: COLUMNS_GRID_MAIN.TenantID.Name, title: "TenantID", width: COLUMNS_GRID_MAIN.TenantID.Width, hidden: true, menu: false },
            //{ field: COLUMNS_GRID_MAIN.ProductID.Name, title: "Product", width: COLUMNS_GRID_MAIN.ProductID.Width, hidden: true, menu: false },
            { field: COLUMNS_GRID_MAIN.SageCustomerNumber.Name, title: "Sage Customer Number", width: COLUMNS_GRID_MAIN.SageCustomerNumber.Width, attributes: { style: "white-space: nowrap" } },
            { field: COLUMNS_GRID_MAIN.CustomerName.Name, title: "Customer", width: COLUMNS_GRID_MAIN.CustomerName.Width, attributes: { style: "white-space: nowrap" } },
            { field: COLUMNS_GRID_MAIN.InvitationEmail.Name, title: "Email", width: COLUMNS_GRID_MAIN.InvitationEmail.Width, template: "<a href=\"mailto:#=InvitationEmail#\">#=InvitationEmail#</a>", attributes: { style: "white-space: nowrap" }},
            { field: COLUMNS_GRID_MAIN.ProductName.Name, title: "Product", width: COLUMNS_GRID_MAIN.ProductName.Width, attributes: { style: "white-space: nowrap" }},
            { field: COLUMNS_GRID_MAIN.BillingAccountNumber.Name, title: "Billing Account Number", width: COLUMNS_GRID_MAIN.BillingAccountNumber.Width, attributes: { style: "white-space: nowrap" } },
            { template: kendo.template($("#" + ID.CommandTemplate).html()), title: "&nbsp;", width: 280 }
            //{ command: ["edit", "destroy", { text: "Invite", click: sendEMailWithSendGrid }], title: "&nbsp;", width: 280 }
        ],
        editable: {
            mode: "popup",
            template: $("#" + ID.FormPopup).html(),
            confirmation: "Are you sure you want to remove this tenant?"
        },
        edit: function (e) { return PopupSetup(e); },
        save: function (e) { return PopupSave(e); },
        filterable: true,
        sortable: true,
        selectable: "row single",
        scrollable: true,
        columnMenu: true,
        resizable: true
    });

    GridColumnHeaderSetup($("#" + ID.GridMain));
    GridAddSetup($("#" + ID.GridMain));

    $("#" + ID.GridMain).on("click", ".k-grid-invite", function (e) {
        return sendEMailWithSendGrid(e);
    });
})

function GridColumnHeaderSetup(grid) {
    //Loop through column headers and remove href
    var headers = grid.find(".k-grid-header-wrap th");
    headers.each(function () {
        var $th = $(this);
        if ($th.find(".k-link").attr("href") != null)
            $th.find(".k-link").removeAttr("href");
    });
}

function GridAddSetup(grid) {
    //Align Add button to the right
    grid.find(".k-grid-add").css("float", "right");
    //Remove href
    if (grid.find(".k-grid-add").attr("href") != null)
        grid.find(".k-grid-add").removeAttr("href")
}

// Event Handler for popup Edit event
function PopupSetup(e) {
    //Reference to popup container
    var editor = e.container;
    //Determine if Add or Edit
    var isEdit = ((e.model.TenantID != null) && (e.model.TenantID.length != 0));

    PopupSetTitle(editor, isEdit);
    PopupSetFieldKey(editor, isEdit);
    PopupSetFieldProduct(editor, isEdit);
    if (isEdit) {
        PopupSetFieldSubscriptions(editor, e.model.Apps);
    }
    //Hide or Show edit fields
    PopupSetFieldEditItems(isEdit);

    //Set activite event handler
    PopupBindEvent(editor, "activate", function (e) { return PopupActivate(e, isEdit) });
    //Size popup
    PopupSize(editor, isEdit);
    //Place buttons in correct order
    PopupSetButtons(editor, isEdit);
    //Center popup window
    PopupCenter(editor);
}

// Event Handler for popup activation
function PopupActivate(e, isEdit) {
    //Reference to popup container
    var editor = $("div.k-widget.k-window").last();
    if (isEdit) {
        //Place focus on Tenant Name field
        editor.find("#" +COLUMNS_GRID_MAIN.TenantName.Name).select();
    }
    else {
        //Place focus on Sage Customer Number field
        editor.find("#" + COLUMNS_GRID_MAIN.SageCustomerNumber.Name).select();
        //Default to first product
        var productList = editor.find("#" + COLUMNS_GRID_MAIN.ProductID.Name).data(KENDO_DATA.DropDownList);
        productList.select(0);
    }
}

// Event Handler for popup Save event
function PopupSave(e) {
    //Reference to popup container
    var editor = e.container;
    //Determine if Add or Edit popup
    var isEdit = ((e.model.TenantID != null) && (e.model.TenantID.length != 0));
    if (isEdit) {
        if (gridTenantAppsChanged)
            e.model.dirty = true;
        //var CELL_TENANTAPPID    = 0,
        //    CELL_DESCRIPTION    = 1,
        //    CELL_SUSPENDED      = 2,
        //    CELL_SUBSCRIPTION   = 3;
        ////Edit popup, need to save subscription numbers
        //var tenantApps = editor.find("#" + ID.GridPopup).data(KENDO_DATA.Grid);
        //var table = tenantApps.table[0];
        //for (var row = 0; row < table.rows.length; row++) {
        //    var tenantAppID = table.rows[row].cells[CELL_TENANTAPPID].textContent
        //    var isSuspended = table.rows[row].cells[CELL_SUSPENDED].firstChild.checked
        //    var billSubscriptionNumber = table.rows[row].cells[CELL_SUBSCRIPTION].textContent
        //    for (var app = 0; app < e.model.Apps.length; app++) {
        //        if (tenantAppID == e.model.Apps[app].TenantAppID) {
        //            if (e.model.Apps[app].BillingSubscriptionNumber.toUpperCase() != billSubscriptionNumber.toUpperCase()) {
        //                e.model.Apps[app].BillingSubscriptionNumber = billSubscriptionNumber;
        //                e.model.dirty = true;
        //            }
        //            if (e.model.Apps[app].IsSuspended != isSuspended) {
        //                e.model.Apps[app].IsSuspended = isSuspended;
        //                e.model.dirty = true;
        //            }
        //            break;
        //        }
        //    }
        //}
    }
    else {
        //Add popup, need to save ProductID, NULL if user didn't change field
        var productList = editor.find("#" + COLUMNS_GRID_MAIN.ProductID.Name).data(KENDO_DATA.DropDownList);
        if (e.model.ProductID != productList.value()) {
            e.model.ProductID = productList.value();
            e.model.ProductName = productList.text();
            e.model.dirty = true;
        }
    }
    return true;
}

//Key field changed, must check if it already exists
var onKeyFieldChange = function (e) {
    keyFieldDataSource.read();
    var editor = $("div.k-widget.k-window").last();
    var editRow = $("#" + ID.GridMain).data().kendoGrid.dataSource.data()[0];
    var sageCustomerNumber = editRow.SageCustomerNumber.rtrim().toUpperCase();
    for (var cust = 0; cust < keyFieldDataSource.view().length; cust++) {
        if (keyFieldDataSource.view()[cust].SageCustomerNumber.toUpperCase() == sageCustomerNumber) {
            editor.find("#" + COLUMNS_GRID_MAIN.CustomerName.Name)[0].value = keyFieldDataSource.view()[cust].CustomerName;
            editRow.set(COLUMNS_GRID_MAIN.CustomerName.Name, keyFieldDataSource.view()[cust].CustomerName);
            editor.find("#" + COLUMNS_GRID_MAIN.BillingAccountNumber.Name)[0].value = keyFieldDataSource.view()[cust].BillingAccountNumber;
            editRow.set(COLUMNS_GRID_MAIN.BillingAccountNumber.Name, keyFieldDataSource.view()[cust].BillingAccountNumber);
            break;
        }
    }
};

function PopupSetTitle(editor, isEdit) {
    //Set appropriate popup title
    if (isEdit)
        editor.kendoWindow("title", "Edit Tenant");
    else
        editor.kendoWindow("title", "Add Tenant");
}

function PopupSetButtons(editor, isEdit) {
    //Remove Cancel button
    editor.find(".k-grid-cancel").remove();
    //Change 'Update' button text to 'Save'
    editor.find("a.k-button.k-button-icontext.k-grid-update").html('<span class="k-icon k-update"></span>Save');
    //Align Save button on the right edge
    if (isEdit)
        editor.find(".k-grid-update").css("position", "relative").css("left", "110%");
    else
        editor.find(".k-grid-update").css("float", "right");
    //Remove href from Save button
    if (editor.find(".k-grid-update").attr("href") != null)
        editor.find(".k-grid-update").removeAttr("href")
}

//Set up Key field for adding a tenant
function PopupSetFieldKey(editor, isEdit) {
    if (isEdit)
        editor.find("#" + COLUMNS_GRID_MAIN.SageCustomerNumber.Name).attr("disabled", true);
    else {
        editor.find("#" + COLUMNS_GRID_MAIN.SageCustomerNumber.Name).attr("disabled", false);
        editor.find("#" + COLUMNS_GRID_MAIN.SageCustomerNumber.Name).on('change', function (e) {
            onKeyFieldChange(e);
        });
    }
}

//Set up Product list for adding a tenant
function PopupSetFieldProduct(editor, isEdit) {
    var fieldValueID = COLUMNS_GRID_MAIN.ProductID.Name;
    var fieldTextID = COLUMNS_GRID_MAIN.ProductName.Name;
    var dropdownDataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: crudProductBaseUrl + "/ProductList",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                type: "post"
            }
        },
        schema: {
            model: {
                id: COLUMNS_GRID_MAIN.ProductID.Name,
                fields: {
                    ProductID: { type: "guid", editable: false, nullable: true },
                    ProductName: { type: "string", editable: false }
                }
            }
        },
        error: function (e) {
            alert("Unable to get Sage Product List.");
        }
    });

    var dropDownList = editor.find("#" + fieldValueID).kendoDropDownList({
        //optionLabel: "Select product...",
        dataTextField: fieldTextID,
        dataValueField: fieldValueID,
        dataSource: dropdownDataSource
    }).data(KENDO_DATA.DropDownList);

    if (isEdit)
        dropDownList.enable(false);
    else
        dropDownList.enable(true);
}

function PopupSetFieldSubscriptions(editor, model) {
    var gridDataSource = new kendo.data.DataSource({
        autoSync: true,
        transport: {
            read: {
                url: crudTenantBaseUrl + "/AppList",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                type: "post"
            },
            update: {
                url: crudTenantBaseUrl + "/AppListUpdate",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                type: "post"
            },
            parameterMap: function (options, operation) {
                if (operation === "read") {
                    return { ProductID: $("#" + COLUMNS_GRID_MAIN.ProductID.Name).val() };
                }
                //parameterMap: function (options, operation) {
                //if (operation !== "read" && options.models) {
                //    return JSON.stringify(options);
                //}
            }
        },
        schema: {
            model: {
                id: COLUMNS_GRID_POPUP.TenantAppID.Name,
                fields: {
                    TennantAppID: { type: "guid", editable: false, nullable: false },
                    Description: { type: "string", editable: false, nullable: false },
                    IsSuspended: { type: "boolean", editable: true, nullable: false },
                    BillingSubscriptionNumber: { type: "string", editable: true, nullable: true }
                }
            }
        },
        error: function (e) {
            alert("Error in grid data source");
        }
    });
    editor.find("#" + ID.GridPopup).kendoGrid({
        dataSource: gridDataSource,
        pageSize: GRID_POPUP_HEIGHT,
        pageable: false,
        columns: [
            { field: COLUMNS_GRID_POPUP.TenantAppID.Name, title: "TennantApp", hidden: true },
            { field: COLUMNS_GRID_POPUP.Description.Name, title: "App", width: COLUMNS_GRID_POPUP.Description.Width, attributes: { style: "white-space: nowrap" } },
            { field: COLUMNS_GRID_POPUP.IsSuspended.Name, title: "Suspended", width: COLUMNS_GRID_POPUP.IsSuspended.Width, attributes: { style: "white-space: nowrap; text-align: center;" }, template: '<input class="check_row" data-bind="value:IsSuspended" type="checkbox" #= (IsSuspended == true) ? checked="checked" : "" #/>' },
            { field: COLUMNS_GRID_POPUP.BillingSubscriptionNumber.Name, title: "Subscription", width: COLUMNS_GRID_POPUP.BillingSubscriptionNumber.Width, attributes: { style: "white-space: nowrap" } }
        ],
        selectable: "cell",
        editable: true,
        navigatable: true
    });
    //editor.find("#" + ID.GridPopup).kendoGrid({
    //    dataSource: {
    //        data: model,
    //        autoSync: true,
    //        schema: {
    //            model: {
    //                id: COLUMNS_GRID_POPUP.TenantAppID.Name,
    //                fields: {
    //                    TennantAppID: { type: "guid", editable: false, nullable: false },
    //                    Description: { type: "string", editable: false, nullable: false },
    //                    IsSuspended: { type: "boolean", editable: true, nullable: false },
    //                    BillingSubscriptionNumber: { type: "string", editable: true, nullable: true }
    //                }
    //            }
    //        }
    //    },
    //    height: GRID_POPUP_HEIGHT,
    //    pageable: false,
    //    columns: [
    //        { field: COLUMNS_GRID_POPUP.TenantAppID.Name, title: "TennantApp", hidden: true },
    //        { field: COLUMNS_GRID_POPUP.Description.Name, title: "App", width: COLUMNS_GRID_POPUP.Description.Width, attributes: { style: "white-space: nowrap" } },
    //        { field: COLUMNS_GRID_POPUP.IsSuspended.Name, title: "Suspended", width: COLUMNS_GRID_POPUP.IsSuspended.Width, attributes: { style: "white-space: nowrap; text-align: center;" }, template: '<input class="check_row" data-bind="value:IsSuspended" type="checkbox" #= (IsSuspended == true) ? checked="checked" : "" #/>' },
    //        { field: COLUMNS_GRID_POPUP.BillingSubscriptionNumber.Name, title: "Subscription", width: COLUMNS_GRID_POPUP.BillingSubscriptionNumber.Width, attributes: { style: "white-space: nowrap" } }
    //    ],
    //    selectable: "cell",
    //    editable: true,
    //    navigatable: true
    //    //dataBound: rowDataBound
    //});

    gridTenantAppsChanged = false;

    editor.find("#" + ID.GridPopup).data(KENDO_DATA.Grid).dataSource.bind("change", function (e) {
        gridTenantAppsChanged = true;
    });
}

//function rowDataBound (e) {
//    //Go Through Each visible row and add a data property with the unique ID from the dataset
//    $(".k-grid-content tbody tr").last().each(function () {
//        var $tr = $(this);
//        var uid = $tr.attr("data-uid");
//        var data_entry = _.find(e.sender.dataSource._data, function (data_source) {
//            return data_source.uid === uid;
//        });
//        $tr.addClass('kendo-data-row').attr('id', data_entry.uid);
//    });
//}

//$('.check_row').live('change', function (e) {
//var grid = $("#" + ID.GridPopup).data(KENDO_DATA.Grid);
    //var cell = grid.select();
    //grid.editCell(cell);

    //var $cb = $(this);
    //var $row = $cb.parents('.kendo-data-row').first();
    //if ($cb.is(':checked')) {
    //    //$row.addClass('k-state-selected');
    //    $cb[0].setAttribute("checked", "checked");
    //} else {
    //    //$row.removeClass('k-state-selected');
    //    $cb[0].removeAttribute("checked");
    //}

//    $cb[0].setAttribute("class", "k-dirty");
//    grid.closeCell(cell);
//    //$row.find('.check_row').addClass("k-dirty");
//    //var grid = $("#" + ID.GridPopup).data(KENDO_DATA.Grid);
//    //var cell = $row.find('.check_row')[0];
//    //grid.editCell($row.find('.check_row')[0]);

//});

//var specialKeys = [kendo.keys.UP, kendo.keys.DOWN];
//function edit(e) {
//    var ddl = e.container.find(".k-dropdown").focus();
//    ddl.keydown(function (e) {

//        if ($.inArray(e.keyCode, specialKeys) > 0) {
//            e.stopImmediatePropagation();
//        }
//    });
//}

//function rowDataBound(e) {
//    var grid = $("#" + ID.GridPopup).data(KENDO_DATA.Grid);
//    var checkBoxCell = $("td:has(input[type='checkbox'])", e.row);
//    $(checkBoxCell).mouseenter(function () {
//        $(grid.element).find(".t-grid-edit-cell").each(function () {
//            grid.closeCell($(this));
//        })
//        grid.editCell($(this));
//    });
//    $(checkBoxCell).mouseleave(function () {
//        $(grid.element).find(".t-grid-edit-cell").each(function () {
//            grid.closeCell($(this));
//        })
//    });
//    //$(checkBoxCell).click(function (e) {
//    //    var grid = $("#" + ID.GridPopup).data(KENDO_DATA.Grid);
//    //    var cell = grid.select();
//    //    grid.editCell(cell);
//    //    //checkBoxCell
//    //    grid.closeCell();
//    //});
//}

function PopupSetFieldEditItems(isEdit) {
    //Use to hide edit fields when Add Tenant popup displayed and show edit fields when Edit popup displayed
    if (!isEdit) {
        $("tr.edit").hide();
        $("fieldset.edit").hide();
    }
    else {
        $("tr.edit").show();
        $("fieldset.edit").show();
    }
}

function PopupBindEvent(editor, eventName, func) {
    //Need to set focus when popup activated
    editor.data(KENDO_DATA.Window).bind(eventName, func);
}

function PopupSize(editor, isEdit) {
    if (isEdit) {
        $(".k-edit-form-container").parent().width(POPUP_WIDTH)
    }
}

function PopupCenter(editor) {
    editor.data(KENDO_DATA.Window).center();
}

//Hide column in grid
function HideGridColumn(GridID, ColumnName) {
    $("#" + GridID).data(KENDO_DATA.Grid).hideColumn(ColumnName);
}

function sendEMailWithSendGrid(e) {
    e.preventDefault();
    //Get selected row in grid
    var grid = $("#" + ID.GridMain).data(KENDO_DATA.Grid);
    var selectedrow = $("#" + ID.GridMain).find("tbody tr.k-state-selected");

    //Get data from selected row in grid to send invitation email
    var tenant = grid.dataItem(selectedrow);
    var tenantID = tenant.TenantID;
    var email = tenant.InvitationEmail;
    var custName = tenant.CustomerName;

    //Use AJAX to send invitation email
    $.ajax({
        url: crudTenantBaseUrl + "/SendActivationCode",
        cache: false,
        type: 'POST',
        //SendActivationCode
        data: { 'ToEMail': email, 'CustomerName': custName, 'TenantID': tenantID },
        success: function (msg) {
            //Return message format: "ActivationCode; TenantStatus; TenantStatusText; EmailMessage"
            var msg = msg.split(";");
            tenant.ActivationCode = msg[0];
            tenant.TenantStatusText = msg[2];
            selectedrow.find("a.k-button.k-grid-invite").html("<span class=\"k-grid-invite\"></span>Re-invite")
            alert(msg[3]);
        }
    })
};

String.prototype.trim = function () {
    return this.replace(/^\s+|\s+$/g, "");
}
String.prototype.ltrim = function () {
    return this.replace(/^\s+/, "");
}
String.prototype.rtrim = function () {
    return this.replace(/\s+$/, "");
}
