if (!Array.isArray) {
  Array.isArray = function(arg) {
    return Object.prototype.toString.call(arg) === '[object Array]';
  };
}
//  Functions wired to events of page elements.

$(function () {
    $(".inappbrowser").click(function () {
        window.open($(this).data("url"), "_blank", "location=no");
    });

    //if ($(window).width() > 1024) {
    //    $(".slimScroll").slimScroll({
    //        height: "653px"
    //    });
    //}

    //  $.validator.addMethod('RegEx', function (value, element, pattern) {
    //                        var re = new RegExp(pattern);
    //                        return this.optional(element) || re.test(value);
    //                        }, "Please enter a correct number, format xxxx.X");
    //
    //  $.validator.addClassRules("decimal", {
    //                            RegEx: "^\\d+(\\.\\d{1,2})?"
    //                            });

    $("#AppVersion").html(appVersion);

    //Somethings wrong with validate
    //$("#editForm").validate();

    $("#viewsSearchContainer").html("");

    // Add "Active" state to table listings
    $("#TableContainer").on("click", "tbody>tr>td:not(:first-child)", function () {
        $(this).parent().toggleClass("selected");

        var selected = $("#TableContainer tr.selected").length;
        if (selected > 0) {
            $("#MultiEditButton").show();
            if (selectedQueueId == 1 || adminUser) {
                $("#MultiDeleteButton").show();
                $("#MultiStatusButton").show();
            }
            $("#DeselectAllButton").show();
        } else {
            $("#MultiEditButton").hide();
            $("#MultiDeleteButton").hide();
            $("#MultiStatusButton").hide();
            $("#DeselectAllButton").hide();
        }
    });

    $(".collapsible").on("click", "h1", function () {
        $(this).parents(".collapsible").find(".collapsiblePanel").toggle("blind");
    });
    $("#TableContainer").on("click", "tbody>tr>td>a.show-description", ShowDescription);
    // Create dialog boxes
    var wWidth = $(window).width();
    var dWidth = Math.floor(wWidth * 0.95);
    $("#consignor-edit, #creditor-edit").dialog({
        modal: true,
        autoOpen: false,
        position: ['center', 20],
        width: dWidth,
        height: '730',
        resizable: false
    });

    $("#buyer-edit, #update-status").dialog({
        modal: true,
        autoOpen: false,
        position: ['center', 20],
        width: '750',
        height: '730',
        resizable: false
    });

    $("#MultiStatusEquipment").dialog({
        modal: true,
        autoOpen: false,
        position: ['center', 20],
        width: '500',
        resizable: false
    });

    $("#ShareEquipment").dialog({
        modal: true,
        autoOpen: false,
        position: ['center', 20],
        width: '750',
        resizable: false
    });

    $("#DupEquipment").dialog({
        modal: true,
        autoOpen: false,
        position: ['center', 20],
        width: '450',
        resizable: false
    });

    $("#ErrorMessage").dialog({
        modal: true,
        autoOpen: false,
        width: '450',
        resizable: false
    });

    $("#SaveDialog").dialog({
        modal: true,
        autoOpen: false,
        width: '450',
        resizable: false,
        buttons: {
            Cancel: function () {
                $(this).dialog("close");
            },
            OK: function () {
                $(this).dialog("close");
                RefreshQueues(selectedQueueId);
            }
        }
    });
    $("#EquipmentDescriptionDialog").dialog({
        modal: true,
        autoOpen: false,
        width: '450',
        resizable: false,
        buttons: {

            OK: function () {
                $(this).dialog("close");
            }
        }
    });

    $("#ShortcutsDialog").dialog({
        modal: true,
        autoOpen: false,
        width: '450',
        resizable: false,
        buttons: {

            OK: function () {
                $(this).dialog("close");
            }
        }
    });

    $("#DeleteEquipment").dialog({
        modal: true,
        autoOpen: false,
        width: '450',
        resizable: false,
        buttons: {
            Delete: function () {
                DeleteItem();
                $(this).dialog("close");
            },
            Cancel: function () {
                $(this).dialog("close");
            }
        }
    });

    $("#PrintChangeCard").dialog({
        modal: true,
        autoOpen: false,
        position: ['center', 20],
        width: '450',
        resizable: false
    });

    // Dialog click events
    $(".consignor-wrapper .edit-icon").click(function () {
        var consignorId = $("#EquipConsignorNbr").val();
        var contactId = $("#EquipConsignorContact").val();
        SelectConsignor(consignorId, contactId, $("#EquipSale").val(), true);
        ToggleConsignor();
    });

    $("#SaveConsignor").click(function () {
        //SaveConsignor();
        $("#consignorline0").html('Customer/Contact # ' + $("#EquipConsignorNbr").val() + ' / ' + $("#EquipConsignorContact").val());
        $("#consignorline1").html($("#CustomerCompany").val());
        $("#consignorline2").html($("#CustomerFirstName").val() + " " + $("#CustomerLastName").val());
        $("#consignorline3").html($("#CustomerMailingAddress1").val());
        $("#consignorline4").html($("#CustomerMailingCity").val() + ", " + $("#CustomerMailingState").val() + " " + $("#CustomerMailingZipCode").val());
        $("#consignorline5 .main").html(FormatPhone($("#CustomerPhone1").val()));
        $("#consignorline5 .fax").html(FormatPhone($("#CustomerPhone2").val()));
        $("#consignorline5 .other").html(FormatPhone($("#CustomerPhone3").val()));
        $("#EquipCommissionCode").val($("#CustomerCommissionCode").val());
        $("#consignor-edit").dialog("close");
    });

    $(".creditor-wrapper .edit-icon").click(function () {
        var creditorId = $("#EquipCreditorNbr").val();
        var contactId = $("#EquipCreditorContact").val();
        SelectCreditor(creditorId, contactId, true);
        ToggleCreditor();
    });

    $("#SaveCreditor").click(function () {
        //SaveCreditor();
        $("#creditorline0").html('Creditor/Contact # ' + $("#EquipCreditorNbr").val() + ' / ' + $("#EquipCreditorContact").val());
        $("#creditorline1").html($("#CreditorCompany").val());
        $("#creditorline2").html($("#CreditorFirstName").val() + " " + $("#CreditorLastName").val());
        $("#creditorline3").html($("#CreditorMailingAddress1").val());
        $("#creditorline4").html($("#CreditorMailingCity").val() + ", " + $("#CreditorMailingState").val() + " " + $("#CreditorMailingZipCode").val());
        $("#creditorline5").html(FormatPhone($("#CreditorPhone1").val()));

        $("#creditor-edit").dialog("close");
    });

    $(".buyer-wrapper .edit-icon").click(function () {
        $("#buyer-edit").dialog("open");
    });

    $(".status-tab .status-wrapper a.advanced").click(function () {
        $("#update-status").dialog("open");
    });

    $("#SelectAllButton").click(function () {
        //        $("#TableContainer tr:not(.selected)[data-id]")
        //            .not(".filtered").each(function (index, item) {
        //                $(item).addClass("selected");
        //            });
        var grid = $("#grid").data("kendoGrid");

        grid.select(grid.tbody.find(">tr"));


        $("#MultiEditButton").show();
        if (selectedQueueId == 1 || adminUser) {
            $("#MultiDeleteButton").show();
            $("#MultiStatusButton").show();
        }
        $("#DeselectAllButton").show();
        $("#SelectAllButton").hide();
    });

    $("#PrintQueueButton").click(function (evt) {
        var $target = $(evt.target);
        var currentSort = sortFilterState.filter(function (x) {
            return x.queueId == selectedQueueId;
        });
        var sQIDs = "";
        if (Array.isArray(selectedQueueId)) {
            selectedQueueId.forEach(function (id) {
                sQIDs = sQIDs + "&queueId=" + id;
            });
        } else {
            sQIDs = "&queueId=" + selectedQueueId;
        }
        var sortStr = "";
        var filterStr = "";
        var url = rootUrl + "/reports/queuereport?CompanyId=" + companyId
            + sQIDs
            + "&userId=" + userId
            + "&sale=" + currentSale
            + "&allReps=" + viewAllReps;

        //JSON.stringify($("#editForm").serializeObject());
        if (currentSort.length > 0) {
            var currentSortArray = currentSort[0].sort;
            var index = sortFilterState.indexOf(currentSort[0]);
            var tmpSort = new Array();

            $.each($(currentSortArray), function (index, item) {
                if (item[1] == 1)
                    tmpSort.push((item[0] - 1) * -1);
                else
                    tmpSort.push(item[0] - 1);
            });

            sortStr = tmpSort.join("|");
            var currentFilterArray = new Array();
            $.each(currentSort[0].filter, function (index, item) {
                currentFilterArray.push(item);
            });
            currentFilterArray.shift();
            filterStr = currentFilterArray.join("|"); //JSON.stringify($(currentSort[0].filter).serializeObject());
        }

        url = url + "&sort=" + sortStr + "&filter=" + filterStr;
        window.open(url, "_blank", "location=no");

        //        $.ajax({
        //            //url: apiUrl + "/equipment/inforeport/?CompanyId=" + companyId + "&EquipmentId=55665",
        //            url: apiUrl + "/equipment/queuereport?CompanyId=1&queueId=1" + companyId,
        //            cache: false,
        //            //type: "POST",
        //            type: "GET",
        //            //dataType: "json",
        //            contentType: 'application/json; charset=utf-8',
        //            data: {
        //                queueId: 1, //selectedQueueId,
        //                sort: sortStr,
        //                filter: filterStr
        //            },
        //            beforeSend: function (xhr) {
        //                setHeader(xhr);
        //            }
        //        }).complete(function (jqXHR) {
        //            if (jqXHR.statusText === "OK") {
        //                //var myPdf = eval(jqXHR.responseText);
        //                var myPdf = jqXHR;
        //                //window.open('data:application/pdf;' + myPdf, "_blank", "location=no");
        //                //window.open(escape(myPdf), "_blank", "location=no");

        //                // Here, data contains "%PDF-1.4 ..." etc.
        //                var datauri = 'data:application/pdf;' + escape(myPdf);
        //                var win = window.open("", "Your PDF", "width=1024,height=768,resizable=yes,scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=no,copyhistory=no");
        //                win.document.location.href = datauri;
        //            }
        //        });
        //        }).success(function (data) {
        //            var myResponse = eval(data);
        //            window.open('data:application/pdf;base64,' + myResponse.base64EncodedResponse, "_blank", "location=no");
        //        }).fail(function (jqXHR) {
        //            alert("error");
        //        }); 
    });

    $("#DeselectAllButton").click(function () {
        //        $("#TableContainer tr.selected").each(function (index, item) {
        //            $(item).removeClass("selected");
        //        });
        $("#grid").data("kendoGrid").clearSelection();

        $("#SelectAllButton").show();
        $("#MultiEditButton").hide();
        $("#MultiDeleteButton").hide();
        $("#MultiStatusButton").hide();
        $("#DeselectAllButton").hide();

    });


    $("#MultiStatusButton").click(function () {
        $("#MultiStatusEquipment").dialog("open");
    });

    $("#MultiEditButton").click(function () {
        currentPageSize = parseInt($('#grid > div.k-pager-wrap.k-grid-pager.k-widget > span.k-pager-sizes.k-label > span > span > span.k-input').html());
        console.log(unitsToProcess);
        //$("#TableContainer tr.selected[data-id]:not(.filtered)").each(function (index, element) {
        var grid = $("#grid").data("kendoGrid");
        $('#TableContainer tr[aria-selected="true"]').each(function (index, element) {
            var onclick = $(element).find("td:first a").attr("onclick");
            unitsToProcess.push(onclick);
            console.log(onclick);
        });
        eval(unitsToProcess.shift());
    });

    $("#MultiDeleteButton").click(function () {
        var ids = new Array();

        if (confirm('Are you sure you want to delete these units?')) {
            $("#TableContainer tr[aria-selected=true]").each(function (index, element) {
                ids.push($(element).data('id'));
                console.log($(element).data('id'));
            });

            //var json = '{"EquipmentId":"' + $(this).data("id") + '",' +
            //              '"StatusId":"' + statusId + '",' +
            //              '"ActivityDate":"",' +
            //              '"UserName":"' + window.localStorage.getItem("username") + '",' +
            //              '"AssignedTo":"",' +
            //              '"DueDate":"",' +
            //              '"UserLocation":"' + $("#sw_UserLocation").val() + '"}';

            $.ajax({
                type: "POST",
                cache: false,
                url: apiUrl + "/equipment/delete?CompanyId=" + companyId + "&EquipmentIds=" + ids.join(","),
                dataType: "json",
                contentType: 'application/json; charset=utf-8',
                data: '{"EquipmentIds":"' + ids.join(",") + '"}',
                beforeSend: setHeader
            }).done(function (data) {

                RefreshQueues(selectedQueueId);

            })
                                .fail(function (data) {
                                    $("#ErrorMessage #divMessage p").html("There were edit issues when attempting to delete the units.");
                                    var resultJson = jQuery.parseJSON(data.responseText);
                                    if (resultJson.resultType === "EDITSTOPS")
                                        $("#ErrorMessage #divDetails p").html(resultJson.result);
                                    $("#ErrorMessage").dialog("open");
                                    RefreshQueues(selectedQueueId);
                                });
        }
    });


    $("#DeleteButton").click(function () {
        $("#DeleteEquipment").dialog("open");
    });

    $("#ShareButton").click(function () {
        GetContacts();
        $("#ShareEquipment").dialog("open");
    });

    $("#CopyButton").click(function () {
        CopyEquipment();
    });

    $("#DuplicateButton").click(function () {
        $("#DupEquipment").dialog("open");
    });

    $("#ItemList .edit-icon").click(function () {
        $("#InfoTab").show();
        $(".edit-button").show();
    });

    $(".notes").click(function () {
        $("#InfoTab .footer-tab").hide();
        $(".notes-tab").show();
    });

    $(".photo").click(function () {
        $("#InfoTab .footer-tab").hide();
        $(".camera-tab").show();
    });
    $(".info").click(function () {
        $("#InfoTab .footer-tab").hide();
        $(".info-tab").show();
    });
    $(".files").click(function () {
        $("#InfoTab .footer-tab").hide();
        $(".files-tab").show();
        GetPhotos();
    });
    $(".button-history").click(function () {
        $("#InfoTab .footer-tab").hide();
        $(".history-tab").show();
        console.log("clicked history");
    });
    $(".status").click(function (evt) {
        if (!evt.target.hasAttribute("disabled")) {
            $("#InfoTab .footer-tab").hide();
            $(".status-tab").show();
        }
    });

    $(".slide-portrait").click(function () {
        $('.slide-menu-left, .slide-menu-left .footer-left').animate({
            width: '0'
        }, function () {
            $('.slide-menu-left').hide();
        });
        $('.slide-menu-right, .slide-menu-right .footer-right, #TableContainer table.tablesorter, .tablesorter-scroller-table').animate({
            width: '100%'
        }, function () {
            $.each($("#ListingsTable tbody tr:visible:first td"), function (index, item) {
                $(".tablesorter-scroller-header table thead .tablesorter-filter-row td:eq(" + index + ")  input").width($(item).outerWidth() - 8);
            });
            $(".tablesorter-scroller-table").css("width", $("#ListingsTable").outerWidth());

        });


        $('.footer-right li a').animate({
            padding: '0 88px'
        });
        $("#slide-close").attr('id', 'slide-open');

    });

    $("#slide-portrait").click(function () {
        $('.slide-menu-left').show();
        $('.slide-menu-left, .slide-menu-left .footer-left').animate({
            width: '265px'
        });
        $('.slide-menu-right, .slide-menu-right .footer-right, #TableContainer table.tablesorter, .tablesorter-scroller-table').animate({
            width: '100%'
        }, function () {
            $.each($("#ListingsTable tbody tr:visible:first td"), function (index, item) {
                $(".tablesorter-scroller-header table thead .tablesorter-filter-row td:eq(" + index + ")  input").width($(item).outerWidth() - 8);
            });
            $(".tablesorter-scroller-table").css("width", $("#ListingsTable").outerWidth());


        });
        $('.footer-right li a').animate({
            padding: '0 62px'
        });
        $(this).attr('id', 'slide-close');
    });

    $(".ipad-button-save").click(function () {
        SubmitForm();
    });

    $('#accountInfo .save-button').click(function () {
        currentSale = $('#sw_sale').val();
        defaultSale = $('#sw_defaultsale').val();
        viewAllReps = $('#sw_viewallreps').val();
        SetDefaultSale();
        RefreshQueues();
    });

    $(".add-spec").on("click", function () {
        miscSpecCount += 1;
        $("<div class='field-wrapper' style='width:95%;'>"
                      + "<label data-label='Miscellaneous'>Miscellaneous ("
                      + "<input type='textbox' id='po_misc_" + miscSpecCount + "' name='po_misc_" + miscSpecCount + "' value='" + miscPrintOrder + "' />)"
                      + "</label>"
                      + "<textarea class='misc-text' id='misc_" + miscSpecCount + "' name='misc_" + miscSpecCount + "' style='width:100%;'"
                      + " maxlength='200' cols='200' ></textarea>"
                      + "</div>").appendTo($(".specfields"));
        miscPrintOrder += 1;
        $('#po_misc_' + miscSpecCount).focus();
    });

    $("#EditPhotos").click(function () {
        $(".delete-photo").show();
        $("#EditPhotoMenu").show();
        $("#EditPhotos").hide();
        $("#Gallery").sortable();
        $("#Gallery").sortable('enable');
    });

    $("#SavePhotos").click(function () {
        SavePhotos();
    });

    $("#Gallery").on("click", ".delete-photo", function () {
        $(this).parent().remove();
    });

    $("#CancelPhotos").click(function () {
        $("#EditPhotoMenu").hide();
        $(".delete-photo").hide();
        $("#EditPhotos").show();
        $("#Gallery").sortable('disable');
        $("#Gallery").disableSelection();
    });

    $("#EmailAddresses").on("click", ".email", function () {
        $("#sw_shareto").val($("#sw_shareto").val() + $(this).data("email") + ";");
    });

    $("#DuplicateButton").click(function () {
        $("#EquipDupCount").val($("#Duplicate").val());
    });

    $("#RefreshDescription").click(function () {
        RefreshDescription(false);
    });

    $(".StatusOptions").on("click", "a", function () {
        QuickStatus($(this));
    });

    $("#metaFields").on("change", ".checkCascade", function () {
        var id = $(this).attr("id");

        // Get a list of all dependent dropdowns so we can initialize to the "choose..."
        var childrenSpecs = cascadingSpecs.filter(function (x) {
            return (x.TriggerElementId == id);
        });

        var children = [];
        $.each(childrenSpecs, function () {
            if ($.inArray(this.ElementId, children) == -1) {
                children.push(this.ElementId);
            }
        });

        //  Initialize the select elements with default 'choose...'.
        $.each(children, function () {
            $("#" + this).data("id", $("#" + this).val());
            $("#" + this).html("<option value=''>choose...</option>");
        });


        var selectedSpecId = $(this).val();
        //filteredspecs represents all of the possible dropdown values that will go into the equpment specs
        var filteredSpecs = cascadingSpecs.filter(function (x) {
            if ($.inArray(x.ElementId, children) > -1) {
                return (x.ParentSpecId == null || x.ParentSpecId == selectedSpecId);
            }
            else return false;
        });
        /// <reference path="../css/tablesorter.css" />

        //        var filteredSpecs = cascadingSpecs.filter(function (x) {
        //            //return (x.ParentSpecId != null && x.ParentSpecId == selectedSpecId);
        //            return (x.ParentSpecId == null || x.ParentSpecId == selectedSpecId);
        //        });

        //if we have some spec values we need to apply first get them in order
        if (filteredSpecs.length > 0) {

            //    Fourth index is from the ORDERBY column in the SPEC table.
            filteredSpecs.sort(function (a, b) { return (a.ORDERBY < b.ORDERBY ? -1 : (a.ORDERBY > b.ORDERBY ? 1 : 0)); });

            var selects = [];

            //  Get a unique list of select elements that need to be populated.
            $.each(filteredSpecs, function () {
                if ((this.ParentSpecId == selectedSpecId || this.ParentSpecId == null) && $.inArray(this.ElementId, selects) == -1) {
                    selects.push(this.ElementId);
                }
            });

            //  Populate each select element with their cascaded options.
            $.each(filteredSpecs, function () {
                $("#" + this.ElementId).append("<option value='" + this.SPECID + "' data-active='" + this.ACTIVE + "'>" + this.DESCRIPTION + "</option>");
            });

            //  Set the drop down back to the selected value
            $.each(selects, function () {
                $("#" + this).val($("#" + this).data("id"));
            });
        }
    });

    $(".field-wrapper").on("change", "select", function () {
        $(this).next().val("");
        $(this).next().css("background-color", "#FFF");
    });

    $(".field-wrapper").on("change", ".otherSpec", function () {
        $(this).prev().val("");
        $(this).css("background-color", "#FBFCC7");
    });

    $("#metaFields").on("click", ".sequence-number", function () {
        var fieldValue = $(this).html();
        var fieldPosition = $(this).parent().next().next().position();
        $("#edit-sequence-number").css("left", fieldPosition.left);
        $("#edit-sequence-number").css("top", fieldPosition.top);
        $("#edit-sequence-number input").val(fieldValue);
        $("#edit-sequence-number .save").data("id", $(this).data("id"));
        $("#edit-sequence-number").show();
    });

    $("#edit-sequence-number .save").click(function () {
        var id = $(this).data("id");
        $("#po_" + id).val($(this).prev().val());
        $("#" + id).prev().prev().html($("#" + id).prev().prev().data("label") + "(<a class='sequence-number' data-id='" + id + "'>" + $(this).prev().val() + "</a>)");
        $("#edit-sequence-number").hide();
    })

    $("#edit-sequence-number .cancel").click(function () {
        $("#edit-sequence-number").hide();
    });

    $("#AddDup").click(function () {
        $("<tr><td><input type='text' class='serialNumber' /></td><td><input type='text' class='unitNumber' /></td><td><input type='text' class='odometer' /></td><td style='vertical-align:top;'><a class='icon-delete removeDup' style='margin-left:5px;height:26px;width:26px;'></a></td></tr>").appendTo($("#DupEquipment tbody"));
        $("#DupEquipment > table > tbody > tr:last").find("input").first().focus();
    });

    $("#DupEquipment").on("click", ".removeDup", function () {
        $(this).parent().parent().remove();
    });

    $("#OkDuplicate").click(function () {
        var numbers = "";

        $("#DupEquipment > table > tbody > tr").each(function () {
            numbers += $(this).find(".serialNumber").val() + "," + $(this).find(".unitNumber").val() + "," + $(this).find(".odometer").val() + "|";
        });
        $("#DupSerialNumbers").val(numbers);
        $("#DupEquipment").dialog('close');
    });

    $(".phone").on('focus', function () {
        var number = $(this).val();
        number = number.replace(/[^\d]/g, "");
        $(this).val(number);
    });

    $(".phone").on('blur', function () {
        var number = $(this).val();
        number = number.replace(/[^\d]/g, "").replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
        $(this).val(number);
    });

    $("#ConsignorSearchResults").tablesorter({
        theme: 'default',
        widthFixed: true,
        widgets: ["zebra", "filter"],
        headers: { 0: { sorter: false, filter: false} },
        widgetOptions: {
            filter_childRows: false,
            filter_columnFilters: true,
            filter_cssFilter: 'tablesorter-filter',
            filter_functions: null,
            filter_hideFilters: true,
            filter_ignoreCase: true,
            filter_reset: 'button.reset',
            filter_searchDelay: 300,
            filter_startsWith: false,
            filter_useParsedData: false
        }
    });

    $("#CreditorSearchResults").tablesorter({
        theme: 'default',
        widthFixed: true,
        widgets: ["zebra", "filter"],
        headers: { 0: { sorter: false, filter: false} },
        widgetOptions: {
            filter_childRows: false,
            filter_columnFilters: true,
            filter_cssFilter: 'tablesorter-filter',
            filter_functions: null,
            filter_hideFilters: true,
            filter_ignoreCase: true,
            filter_reset: 'button.reset',
            filter_searchDelay: 300,
            filter_startsWith: false,
            filter_useParsedData: false
        }
    });

    $(".pagination").on("click", ".prev", function () {
        if ($(".pagination > .page:visible:first").data("page") > 1) {
            $('.pagination > .page:visible:last').hide();
            $('.pagination > .page:visible:first').prev().show();
        }
    });

    $(".pagination").on("click", ".next", function () {
        if ($(".pagination > .page:visible:last").data("page") < $(this).data("max")) {
            $('.pagination > .page:visible:first').hide();
            $('.pagination > .page:visible:last').next().show();
        }
    });

    $(".pagination").on("click", ".page", function () {
        $(".pagination > .page").removeClass("active");
        $(this).addClass("active");
        ShowList($(".page-header-internal h1").html(), selectedQueueId);
    });
});

function ToggleConsignor(title) {
    $(".add-consignor").toggle();
    if (typeof title !== 'undefined') {
        $("#consignor-edit").dialog('option', 'title', title);
    }
}

function ToggleCreditor() {
    $(".add-creditor").toggle();
}

function GetContacts() {
    $("#EmailAddresses").html("");

    try {
        var options = new ContactFindOptions();
        options.multiple = true;
        var fields = ["name", "emails"];
        navigator.contacts.find(fields, onContactSuccess, onContactError, options);
    } catch (err) { }
}

function onContactSuccess(contacts) {
    contacts = contacts.sort(cSort);

    for (var i = 0; i < contacts.length; i++) {
        if (contacts[i].emails) {
            for (m = 0; m < contacts[i].emails.length; m++) {
                //addToMyContacts(contacts[n].name.formatted, contacts[n].emails[m].value);
                //console.log("Display Name = " + contacts[i].name.formatted + " " + contacts[i].emails[m].value + " (" + contacts[i].emails[m].type + ")");
                $("<li class='email' data-email='" + contacts[i].emails[m].value + "' style='height:30px'><p style='font-weight:bold;'>" + contacts[i].name.formatted + "</p><p>" + contacts[i].emails[m].value + "</p></li>").appendTo("#EmailAddresses");
            }
        }
    }
}

function onContactError(contactError) {
    alert(contactError.code);
}

var cSort = function (a, b) {
    aName = a.name.formatted;
    bName = b.name.formatted;
    return aName < bName ? -1 : (aName == bName ? 0 : 1);
}


//Keyboard shortcuts section

Mousetrap.bind('space', function () {
    document.activeElement.click();
    console.log("space");
    return false;
});

Mousetrap.bindGlobal('ctrl+s', function () {
    if ($(".ipad-button-save").is(":visible")) {
        SubmitForm();
        console.log("saved");
    } else {
        console.log("not saved");
    }
    return false;
});

Mousetrap.bind('ctrl+a', function () {
    console.log("ctrl+a");
    var grid = $("#grid").data("kendoGrid");

    grid.select(grid.tbody.find(">tr"));

    $("#MultiEditButton").show();
    if (selectedQueueId == 1 || adminUser) {
        $("#MultiDeleteButton").show();
        $("#MultiStatusButton").show();
    }
    $("#DeselectAllButton").show();
    $("#SelectAllButton").hide();
    return false;
});


Mousetrap.bind('ctrl+d', function () {
    console.log("ctrl+d");
    $("#grid").data("kendoGrid").clearSelection();

    $("#SelectAllButton").show();
    $("#MultiEditButton").hide();
    $("#MultiDeleteButton").hide();
    $("#MultiStatusButton").hide();
    $("#DeselectAllButton").hide();
    return false;
});

Mousetrap.bind('ctrl+p', function () {
    console.log("ctrl+p");
    //Print current queue
    if ($("#PrintQueueButton").is(":visible")) {
        $("#PrintQueueButton").click();
    } else { }
    return false;
});


Mousetrap.bind('ctrl+m', function () {
    console.log("ctrl+m");
    //Add new unit
    if ($("#AddItemButton").is(":visible")) {
        ShowClasses();
    } else if ($(".add-spec").is(":visible")) {
        $(".add-spec").click();
    }
    else { }
    return false;
});

Mousetrap.bind('?', function () {
    console.log("?");
    // Show popup with keyboard shotcuts here
    $("#ShortcutsDialog").dialog("open");
    return false;
});

$(".info").click(function () {

});


//Show info on edit screen

Mousetrap.bind('ctrl+i', function () {
    if ($(".info").is(":visible")) {
        console.log("ctrl+i");
        $("#InfoTab .footer-tab").hide();
        $(".info-tab").show();
    } else {
        console.log("not info");
    }
    return false;
});

Mousetrap.bind('ctrl+o', function () {
    if ($(".photo").is(":visible")) {
        console.log("ctrl+");
        $("#InfoTab .footer-tab").hide();
        $(".camera-tab").show();
    } else {
        console.log("not phOtos");
    }
    return false;
});

Mousetrap.bind('ctrl+f', function () {
    if ($(".files").is(":visible")) {
        console.log("ctrl+f");
        $("#InfoTab .footer-tab").hide();
        $(".files-tab").show();
        GetPhotos();
    } else {
        console.log("not Files");
    }
    return false;
});

Mousetrap.bind('ctrl+k', function () {
    if ($(".notes").is(":visible")) {
        console.log("ctrl+k");
        $("#InfoTab .footer-tab").hide();
        $(".notes-tab").show();
    } else {
        console.log("not notes");
    }
    return false;
});

Mousetrap.bind('ctrl+u', function () {
    if ($(".status").is(":visible")) {
        console.log("ctrl+u");
        //if (!evt.target.hasAttribute("disabled")) {
        $("#InfoTab .footer-tab").hide();
        $(".status-tab").show();
        //}
    } else {
        console.log("not statUs");
    }
    return false;
});


Mousetrap.bind('ctrl+q', function () {
    if ($('#slide-open').is(":visible")) {
        console.log("ctrl+q");
        $('#slide-open').click();
    } else {
        $('#slide-close').click();
    }
    return false;
});


Mousetrap.bind('ctrl+g', function () {
    if ($('.button-queues').is(":visible")) {
        console.log("ctrl+g");
        $('.button-queues').click();
    } else {
        console.log("not refresh queueus");
    }
    return false;
});

Mousetrap.bind('ctrl+e', function () {
    if ($('#MultiEditButton').is(":visible")) {
        console.log("ctrl+g");
        $('#MultiEditButton').click();
    } else {
        console.log("not refresh queueus");
    }
    return false;
});


Mousetrap.bind('ctrl+x', function () {
    if ($("#editForm .collapsible .collapsiblePanel").is(":visible")) {
        $("#editForm .collapsible .collapsiblePanel").hide();
        $("#specForm .collapsible .collapsiblePanel").hide();
        $("#Notes .collapsiblePanel").hide();
        $("#ProductDescription .collapsiblePanel").hide();
        $("#AdditionalInformation .collapsiblePanel").hide();
    } else {
        $("#editForm .collapsible .collapsiblePanel").show();
        $("#specForm .collapsible .collapsiblePanel").show();
        $("#Notes .collapsiblePanel").show();
        $("#ProductDescription .collapsiblePanel").show();
        //TODO check to make sure current unit is in checkin or greater status before showing
        $("#AdditionalInformation .collapsiblePanel").show();
    }

return false;
});


//Change Card Functions

$("#PrintChangeCardButton").click(function () {
    $("#PrintChangeCard").dialog("open");
    $("#PrintAllChangeCards").focus();
});



$("#PrintAllChangeCards").click(function () {
    $("#ChangeCardError").hide();
    var saleNumber = $("#saleNumberAll").val();
    console.log(saleNumber);
    url = apiUrl + "/ChangeCard/ChangeCardReport?saleNumber=" + saleNumber + "&CompanyId=" + companyId;
    //console.log(url);
    window.open(url, "_blank");
})


$("#PrintSelectedChangeCards").click(function () {
    $("#ChangeCardError").hide();
    var saleNumber = $("#saleNumber").val();
    var url = $("#ChangeCardSelection").serialize();
    //var check = apiUrl + "/ChangeCard/ChangeCardReportCheck?saleNumber=" + saleNumber + "&CompanyId=" + companyId + "&" + url;
    //$.get(check, function (data) {
        url = apiUrl + "/ChangeCard/ChangeCardReport?saleNumber=" + saleNumber + "&CompanyId=" + companyId + "&" + url;
        window.open(url, "_blank");
    //}).fail(function () {
    //    $("#ChangeCardError").html("No equipment found in range.");
    //    $("#ChangeCardError").show();
    //})

})

$("#typeStart").change(function () {
    $("#typeEnd").val($("#typeStart").val());
})


//function GetSales() {
//    console.log("getSales");
//    return $.ajax({
//        url: apiUrl + "/sales/getall/?callback=?",
//        cache: false,
//        type: "GET",
//        data: {
//            companyId: companyId
//        },
//        beforeSend: setHeader
//    });

//}

$("#sw_sale").change(function () {
    $("#saleNumberAll").val($("#sw_sale").val());
    $("#saleNumber").val($("#sw_sale").val());
})