var companyId = 3;
//  1 = TMBN, 2 = Live, 3 = Test
var appVersion = "Version 1.7.20";
var defaultBusinessId = companyId; 
var debug = false;
var testing = false;
var rootUrl = "https://especs.taylorandmartin.com";
switch (companyId) {
    case 2:
        rootUrl = "https://especs10.taylorandmartin.com";
        break;
    case 3:
        rootUrl = "https://especs10test.taylorandmartin.com";
        //rootUrl = "http://localhost:49574";
        debug = false;
        break;
    case 1:
        rootUrl = "http://localhost:49574";
        debug = true;
}
var apiUrl = rootUrl + "/api";

var columns = 0;
var pictureSource;   // picture source
var destinationType; // sets the format of returned value
var geoField;
var userId = window.localStorage.getItem("userid");
var adminUser = false;
var currentSale = 0;
var defaultSale = 0;
var viewAllReps = false;
var myPhotoSwipe;
var miscSpecCount = 0;
var miscPrintOrder = 1000;
var cascadingSpecs = [];
var makeSpecId;
var modelSpecId;
var defaultDivision = "TM   ";
var defaultCommission = "";
var selectedQueueId = -1;
var selectedUnits = [];
var unitsToProcess = [];
var searchViewPaths = [];
var sortFilterState = new Array();
var photoQuality = 0;
var photoHeight = 0;
var photoWidth = 0;
var ids = [];
var currentPage = 1;
var currentPageSize = 25;
var editedUnits = [];


searchViewPaths.push(new Array('Make', 'root', 'Class', 'TRMAKE'));
searchViewPaths.push(new Array('Make', 'Class', 'Model', 'TRCLAS'));
searchViewPaths.push(new Array('Make', 'Model', 'Year', 'TRMODL'));
searchViewPaths.push(new Array('Make', 'Year', 'Results', 'TRYEAR'));
searchViewPaths.push(new Array('Type', 'root', 'Class', 'TYDESC'));
searchViewPaths.push(new Array('Type', 'Class', 'Make', 'TRCLAS'));
searchViewPaths.push(new Array('Type', 'Make', 'Model', 'TRMAKE'));
searchViewPaths.push(new Array('Type', 'Model', 'SaleDate', 'TRMODL'));
searchViewPaths.push(new Array('Type', 'SaleDate', 'Results', 'TRSLDT'));
searchViewPaths.push(new Array('Year', 'root', 'Class', 'TRYEAR'));
searchViewPaths.push(new Array('Year', 'Class', 'Make', 'TRCLAS'));
searchViewPaths.push(new Array('Year', 'Make', 'Model', 'TRMAKE'));
searchViewPaths.push(new Array('Year', 'Model', 'Results', 'TRMODL'));
searchViewPaths.push(new Array('SaleDate', 'root', 'Class', 'TRSLDT'));
searchViewPaths.push(new Array('SaleDate', 'Class', 'Make', 'TRCLAS'));
searchViewPaths.push(new Array('SaleDate', 'Make', 'Model', 'TRMAKE'));
searchViewPaths.push(new Array('SaleDate', 'Model', 'Results', 'TRMODL'));
searchViewPaths.push(new Array('Location', 'root', 'SaleDate', 'SALELOCATION'));
searchViewPaths.push(new Array('Location', 'SaleDate', 'Class', 'TRSLDT'));
searchViewPaths.push(new Array('Location', 'Class', 'Make', 'TRCLAS'));
searchViewPaths.push(new Array('Location', 'Make', 'Model', 'TRMAKE'));
searchViewPaths.push(new Array('Location', 'Model', 'Results', 'TRMODL'));

function GetUser() {
    $.ajax({
        url: apiUrl + "/users/get/?callback=?",
        data: {
            id: userId,
            companyId: companyId
        },
        cache: false,
        type: "GET",
        beforeSend: setHeader
    }).always(
                     function (data) {
                         $("#sw_defaultsale").val(data.DEFAULTSALE);
                         $("#saleNumberAll").val(data.DEFAULTSALE);
                         $("#saleNumber").val(data.DEFAULTSALE);

                         defaultSale = data.DEFAULTSALE;

                         if (data.DEFAULTSALE && currentSale == 0) {
                             $("#sw_sale").val(data.DEFAULTSALE);
                             currentSale = data.DEFAULTSALE;
                         }

                         if (data.ROLE.DESCRIPTION != "Sales") {
                             viewAllReps = true;
                             $("#sw_viewallreps").val(true);
                             $("#sw_viewallreps").prev().attr("class", "checkbox-true");
                         } else {
                             viewAllReps = false;
                             $("#sw_viewallreps").val(false);
                             $("#sw_viewallreps").prev().attr("class", "checkbox-false");
                         }

                         RefreshQueues(data.ROLE.DEFAULTQUEUEID);
                     });
}

function RefreshQueues(queueId) {
//    console.log("refresh queues");
    $("#queueList").html("");
    $("#queueList").hide();
    $("#accountInfo").hide();
    $(".queues-list").show();
    $(".leftLoading").show();
    $(".footer-left .active").removeClass("active");
    $(".button-queues").parent().addClass("active");
    $(".list-button").hide();
    $("#AddItemButton").show();

    if (currentSale == 0) {
        $("#QueueHeader").html("All Sales");
    } else {
        $("#QueueHeader").html("Sale #" + currentSale);
    }

    $.ajax({
        url: apiUrl + "/equipmentqueues/getall/?callback=?",
        data: {
            companyId: companyId,
            sale: currentSale,
            allReps: viewAllReps
        },
        cache: false,
        type: "GET",
        beforeSend: setHeader
    }).always(
                     function (queueData) {
                         $.each(queueData, function () {
                             $("<li class='cf'><div class='multiQueueContainer'><label class='multiQueue'><input type='checkbox' name=" + this.QUEUEID + " class='multiQueue' onclick='showMultiQueue()' data-id=" + this.QUEUEID + "><span  tabindex='0'></span></input></label><a id='queue_" + this.QUEUEID + "' onclick='ShowList(\"" + this.QUEUE + "\", " + this.QUEUEID + ", " + this.ORDERBY + ")'><span>" + this.EQUIPMENTCOUNT + "</span>" + this.QUEUE + "</a></div></li>").appendTo("#queueList");
                             //$("<li><label class='multiQueue' tabindex='0'><input type='checkbox' name=" + this.QUEUEID + " class='multiQueue' onclick='showMultiQueue()' data-id=" + this.QUEUEID + "><span></span></input><a id='queue_" + this.QUEUEID + "' onclick='ShowList(\"" + this.QUEUE + "\", " + this.QUEUEID + ", " + this.ORDERBY + ")'><span>" + this.EQUIPMENTCOUNT + "</span>" + this.QUEUE + "</a></li>").appendTo("#queueList");
                         });

                         $(".leftLoading").hide();
                         $("#queueList").show();

                         if (selectedQueueId instanceof Array) {
                             $.each(selectedQueueId, function (index, value) {
                                 $('input[name=' + value + ']').attr('checked', true);
                             });
                             console.log("showing selected array");
                             ShowList("Selected queues", ids, null);
                         } else if (queueId != undefined) {
                             console.log("showing single queue");
                             $("#queue_" + queueId).trigger("click");
                         } else if (ids[0] != null) {
                             console.log("showing selected");
                             ShowList("Selected queues", ids, null);
                         } else {
                             console.log("Nothing selected");
                         }

                     });
}

function ShowList(title, queueId, orderBy) {

    selectedQueueId = queueId;
    var sortInit = new Array();
    var filterInit = new Array();
    var fieldSorts = new Array();
    $(".window-right").hide();
    $(".edit-button").hide();
    $(".rightLoading").show();
    $(".page-header-internal h1").html(title);
    $("#ListingsTable").trigger("saveSortReset");

    $("#ListingsTable").remove();
    $("#TableContainer").html("<table class='tablesorter tablesorter-default' id='ListingsTable' style='width:100%;'><thead></thead><tbody></tbody></table>");
    $("#TableContainer").html("<div id='grid' style='float:none;height:100%'></div>");
    console.log("COMPANYID: " + companyId);
    $.ajax({
        url: apiUrl + "/equipmentfields/forlistmulti/?callback=?",
        cache: false,
        type: "GET",
        data: {
            id: 0,
            queueId: queueId,
            companyId: companyId
        },
        beforeSend: setHeader
    }).always(
                     function (fieldData) {
                         //console.log("fielddata");
                         //console.log(fieldData);
                         var fields = [];
                         $.each(fieldData, function (index) {
                             fields.push({ "field": this.EQUIPMENTFIELD.replace("#", "_"), "title": this.LISTCAPTION });
                         });


                         $.ajax({
                             url: apiUrl + "/equipment/getforqueuemulti/?callback=?",
                             cache: false,
                             type: "GET",
                             data: {
                                 queueId: queueId,
                                 companyId: companyId,
                                 sale: currentSale,
                                 allReps: viewAllReps
                             },
                             beforeSend: setHeader
                         }).always(

                                      function (workData) {
                                          //console.log(workData);

                                          retrocycle(workData);
                                          var trClass = "";
                                          $.each(workData, function () {
                                              if (this.TREDFLG == "Y") {
                                                  trClass = "error";
                                              } else if (this.TRSTAT == "A" || this.TRSTAT == "S") {
                                                  trClass = "scratch";
                                              } else {
                                                  if (trClass == "odd") { trClass = ""; } else { trClass = "odd"; }
                                              }
                                              var i = this;
                                              var tr = "<a data-id=" + this.EQUIPMENTID + " onclick='EditItem(" +
                                             this.TYPEID + ", " +
                                             this.CLASSID + ", " +
                                             "\"" + this.CLDESC + "\", " +
                                             this.EQUIPMENTID + ", " +
                                             this.SASAL_ + ", " +
                                             this.TRCSGN + ", " +
                                             this.TRCNTC + ", " +
                                             this.TRCRDN + ", " +
                                             this.TRCRDC + ", " +
                                             this.TRBYR_ + ", " +
                                             this.TRBCNT + ")' " + ((this.PHOTOS > 0) ? "class='edit-icon-photo' tabindex='' " : "class='edit-icon' ") + "data-id='" + this.EQUIPMENTID + "'>edit "
                                             + (this.PHOTOS > 0 ? "<span class='photos-count'>" + this.PHOTOS + "</span>" : "")
                                             + "</a>";

                                              //console.log("serial: " + this.TRSERL);
                                              var thisVIN = this.TRSERL.toUpperCase().replace("#", "_");
                                              if (TrimValue(this.TRSERL.toUpperCase().replace("#", "_")).length == 0)
                                                  thisVIN = " Not Entered";
                                              this.TRSERL = "<a href='#' class='show-description' data-id='" + this.EQUIPMENTID + "'>" + thisVIN + "</a>";


                                              //console.log(this);
                                              this.edit = tr;
                                              this.class = trClass;
                                          });
                                          createGrid(fields, workData);

                                          var grid = $("#grid").data("kendoGrid")
                                          console.log(parseInt(currentPage));
                                          $("#grid").data("kendoGrid").dataSource.page(parseInt(currentPage));

                                          if (editedUnits.length > 0) {

                                              var row;
                                              var row1 = $('a[data-id="' + editedUnits[0] + '"').parent().parent();
                                              $.each(editedUnits, function (index, value) {
                                                  row = $('a[data-id="' + value + '"').parent().parent();
                                                  row.addClass("edited");
                                              });
                                              setTimeout(function () {
                                                  //grid.select(row);
                                                  //grid.offset().top
                                                  //console.log(row.offset().top);
                                                  //console.log(grid.content.offset().top);

                                                  grid.content.scrollTop(row1.offset().top - grid.content.offset().top);

                                              }, 1000);
                                          }
                                          editedUnits = [];

                                          if (orderBy != undefined) {
                                              GetStatuses(orderBy, "queue");
                                          } else {
                                              GetStatuses(-1);
                                          }


                                          $(".rightLoading").hide();
                                          $("#ItemList").show();
                                          $(".edit-button").hide();
                                          $(".list-button").show();
                                          $("#MultiEditButton").hide();
                                          $("#MultiDeleteButton").hide();
                                          $("#MultiStatusButton").hide();
                                          $("#DeselectAllButton").hide();

                                      });

                     });
}

function ShowDescription(evt) {
    var $target = $(evt.target);
    //var equipId = $target.closest("tr").attr("data-id");
    var equipId = $target.attr("data-id");
    $.ajax({
        url: apiUrl + "/equipment/getdescription/?callback=?",
        cache: false,
        type: "GET",
        data: {
            CompanyId: companyId,
            EquipmentId: equipId,
            IncludeQuotes: true
        },
        beforeSend: setHeader
    }).success(
                      function (data) {
                          $("#EquipmentDescriptionDialog p").html(data);
                          $("#EquipmentDescriptionDialog").dialog("open");
                      });


    evt.stopImmediatePropagation();
}

function ShowClasses() {
    $(".window-right").hide();
    $(".edit-button").hide();
    $(".add-button").hide();
    $(".list-button").hide();
    $(".rightLoading").show();
    $(".page-header-internal h1").html("Select Class of Equipment");
    $(".classes-table tbody").html("");

    $.ajax({
        url: apiUrl + "/classes/getall/?callback=?",
        cache: false,
        type: "GET",
        data: {
            companyId: companyId,
            typeId: null
        },
        beforeSend: setHeader
    }).done(function (classData) {
        retrocycle(classData);
        var trClass = "";
        $.each(classData, function (i, item) {
            if (trClass == "odd") { trClass = ""; } else { trClass = "odd"; }

            var tr = "<tr class='" + trClass + "'><td style='width:35px;'><a tabindex='1' onclick='AddItem(" + item.CLTYPE + ", " + item.CLASSID + ", \"" + item.CLDESC + "\")' class='select-icon'>select</a></td>" +
                "<td>" + item.EQPTYPE.TYDESC + "</td><td>" + item.CLDESC + "</td></tr>";

            $(tr).appendTo(".classes-table tbody");
        });

        $(".rightLoading").hide();
        $("#ClassList").show();

        $(".classes-table tbody tr td:first a").focus();
    }).error(
                           function () {
                               $(".rightLoading").hide();
                               $("#ClassList").show();
                               console.log("error");
                           });
}


/*==============================================================================================*
*                                                                                              *
*  Equipment Functions                                                                         *
*                                                                                              *
*==============================================================================================*/

function AddItem(typeId, classId, description) {
    ApplySecurity(true);
    $("#slide-close").trigger("click");
    $("#EditItem").hide();
    $("#ClassList").hide();
    $(".footer-right").hide();
    $(".rightLoading").show();
    $("#EditIssues").hide();


    if (classId == undefined) {
        //TODO: Do something here.
        //defId = $("#work-definition-dropdown").data("definitionid");
    }

    $("#EquipClassID").val(classId);
    $("#EquipTypeCode").val(typeId);
    $("#EquipmentID").val("0");
    $("#EquipStatus").val("");


    $("#metaFields").html("");
    $("#Gallery").html("");
    $("#historyList").html("");
    $("#sw_statusstep").html("<option value=''>choose...</option>");
    $("#sw_statusassign").html("<option value=''>choose...</option>");

    GetBuyer(0, 0);
    GetHeader(0, TrimValue(description));
    $(".page-header-internal h1").html("Add " + TrimValue(description));
    $("#ProductDescription").hide();
    BuildFields(classId, description);
    $("#EquipCommissionCode").val($("#CustomerCommissionCode").val());

    $("#InfoTab .footer").hide();
    $(".edit-button").hide();
    $(".list-button").hide();
    $(".add-button").show();
    $("#DuplicateButton").hide();
    $('.info-tab').show();
    $('.footer li').removeClass('active');
    $('.footer li:first').addClass('active');

    getGeolocation("sw_UserLocation");
    $("#AddItemButton").hide();
    setTimeout(function () {
        $("#editForm .collapsible .collapsiblePanel").show();
        $("#specForm .collapsible .collapsiblePanel").show();
        $("#Notes .collapsiblePanel").show();
        $(".consignor-wrapper div a").focus();
        //TODO check to make sure current unit is in checkin or greater status before showing
        $("#AdditionalInformation").hide();
        //console.log("show the things");
    }, 500);
}

function EditItem(typeId, classId, classDesc, equipmentId, sale, consignorId, consignorIndex, creditorId, creditorIndex, buyerId, buyerIndex) {
    var StatusOrderBy = 1;
    editedUnits.push(equipmentId);
    currentPageSize = parseInt($('#grid > div.k-pager-wrap.k-grid-pager.k-widget > span.k-pager-sizes.k-label > span > span > span.k-input').html());

    $("#AddItemButton").hide();
    $("#ItemList").hide();
    $("#AdvSearch").hide();
    $("#ViewSearchDetails").dialog("close");
    $("#viewsSearch").hide();
    $(".page-header-internal h1").html("");
    $(".rightLoading").show();
    $("#EditIssues").hide();
    $("#EquipmentID").val(equipmentId);
    $("#EquipClassID").val(classId);
    $("#EquipTypeCode").val(typeId);
    $("#EquipStatus").val("");
    $("#metaFields").html("");
    $("#Gallery").html("");
    $("#historyList").html("");
    $("#sw_statusstep").html("<option value=''>choose...</option>");
    $("#sw_statusassign").html("<option value=''>choose...</option>");

    $(".add-button").hide();
    $(".list-button").hide();
    $(".edit-button").show();

    try {
        pictureSource = navigator.camera.PictureSourceType;
        destinationType = navigator.camera.DestinationType;
    } catch (err) { }

    GetConsignor(consignorId, consignorIndex, sale);
    //SelectConsignor(consignorId, consignorIndex, sale);
    GetBuyer(buyerId, buyerIndex);
    GetCreditor(creditorId, creditorIndex, false);
    SelectCreditor(creditorId, creditorIndex, false);

    GetHeader(equipmentId, classDesc.trim());
    $("#EquipmentInfoReport").data("url", apiUrl + "/equipment/inforeport/?CompanyId=" + companyId + "&EquipmentId=" + equipmentId);

    $("#ProductDescription").show();
    BuildFields(classId, classDesc.trim(), equipmentId);

    $("#InfoTab .footer").show();
    $('.info-tab').show();
    $('.footer li').removeClass('active');
    $('.footer li:first').addClass('active');

    $.ajax({
        url: apiUrl + "/equipment/statushistory/?callback=?",
        cache: false,
        type: "GET",
        data: {
            companyId: companyId,
            id: equipmentId
        },
        beforeSend: setHeader
    }).always(
                     function (data) {
                         var i = 0;
                         $.each(data, function () {
                             console.log(this);
                             if (i == 0) {
                                 $("#LastStatusId").html(this.STATUSID);
                                 StatusOrderBy = this.ORDERBY;
                             }
                             i++;

                             $("<li><a class='history-edit'>" + this.STATUS + "<br/><span>Date:</span> " + FormatDateTime(this.ACTIVITYDATE) +
                              " | <span>User:</span> " + this.ENTEREDBYUSER + "</a></li>").appendTo("#historyList");
                         });
                         GetStatuses(StatusOrderBy);

                     });

}

function collapsePanels() {
    $("#editForm .collapsible .collapsiblePanel").show();
    $("#specForm .collapsible .collapsiblePanel").show();
    $("#Notes .collapsiblePanel").show();
    $(".consignor-wrapper div a").focus();

    console.log(StatusOrderBy);
    if (StatusOrderBy >= 30) {//markiting or above status

        $(".consignor-wrapper .collapsiblePanel").hide();

    }
    if (StatusOrderBy >= 50) {//checked in status?
        $("#AdditionalInformation").show();
        $("#AdditionalInformation .collapsiblePanel").show();
    } else {
        $("#AdditionalInformation").hide();
    }

    if (StatusOrderBy == 50 || StatusOrderBy == 65 || StatusOrderBy == 60) {
        $("#EquipmentHeader .collapsiblePanel").hide();
    }
}


function DeleteItem() {
    $("#EquipStatus").val("D");
    SubmitForm();
    $("#ItemList").hide();
    $("#AdvSearch").hide();
    $("#EditItem").hide();
    $("#ClassList").hide();
    RefreshQueues(selectedQueueId);
}

function GetStatuses(OrderBy, type) {
    $.ajax({
        url: apiUrl + "/statuses/getall?callback=?",
        cache: false,
        type: "GET",
        data: {
            companyId: companyId
        },
        beforeSend: setHeader
    }).always(
                     function (data) {
                         retrocycle(data);
                         var i = 0;
                         $(".StatusOptions").html("");
                         $(".sw_statusstep").html("<option value=''>choose...</option>");
                         $.each(data, function () {
                             if (type == "queue") {
                                 if (this.QUEUE.ORDERBY > OrderBy && i < 1) {
                                     $("<a data-id='" + this.STATUSID + "'>" + this.DESCRIPTION + "</a>").appendTo(".StatusOptions");
                                     i++;
                                 }
                             }
                             else if (this.ORDERBY > OrderBy && i < 1) {
                                 $("<a data-id='" + this.STATUSID + "'>" + this.DESCRIPTION + "</a>").appendTo(".StatusOptions");
                                 i++;
                             }

                             $("<option value='" + this.STATUSID + "'>" + this.DESCRIPTION + "</option>").appendTo(".sw_statusstep");
                         });
                     });
}

function GetPhotos() {
    $("#Gallery").html("");
    //====== Get Images and Display on Page ======
    $.ajax({
        url: apiUrl + "/files/getall/?callback=?",
        cache: false,
        type: "GET",
        data: {
            companyId: companyId,
            classId: $("#EquipClassID").val(),
            equipmentId: $("#EquipmentID").val()
        },
        beforeSend: setHeader
    }).always(
                     function (data) {
                         $.each(data, function () {
                             if (this.ThumbUrl != undefined) {
                                 $("<li id='" + this.UPLOADID + "' style='width:220px;height:220px;float:left;'><a href='" + apiUrl + "/files/get/" + this.UPLOADID + "?CompanyId=" + companyId + "'><img src='" + apiUrl + "/files/get/" + this.UPLOADID + "?CompanyId=" + companyId + "' alt='" + this.FileName + "' /></a><span class='delete-photo button-red' style=display:none;'>Delete</span></li>").appendTo("#Gallery");
                             }
                         });
                         myPhotoSwipe = $("#Gallery a").photoSwipe({ enableMouseWheel: false, enableKeyboard: false, jQueryMobile: false, preventSlideshow: true, imageScaleMethod: "fitNoUpscale" });
                     });
}

function capturePhotoEdit(source) {
    //====== Take Image with Camera ======
    // Take picture using device camera, allow edit, and retrieve image as base64-encoded string
    if (source == 'camera') {
        navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: photoQuality, targetWidth: photoWidth,
            targetHeight: photoHeight, allowEdit: false,
            sourceType: navigator.camera.PictureSourceType.CAMERA,
            destinationType: destinationType.DATA_URL,
            saveToPhotoAlbum: false
        });
    } else if (source == 'library') {
        navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: photoQuality, targetWidth: photoWidth,
            targetHeight: photoHeight, allowEdit: false,
            sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY,
            destinationType: destinationType.DATA_URL
        });
    }
}

function onPhotoDataSuccess(imageData) {
    //====== Upload Selected Image ======
    $.ajax({
        url: apiUrl + "/files/upload?CompanyId=" + companyId,
        cache: false,
        type: "POST",
        data: {
            ClassId: $("#EquipClassID").val(),
            EquipmentId: $("#EquipmentID").val(),
            File: imageData
        },
        beforeSend: setHeader
    }).always(
                     function (upload) {
                         if (upload.ThumbUrl != undefined) {
                             $("<li id='" + upload.UPLOADID + "' style='width:220px;height:220px;float:left;'><a href='" + apiUrl + "/files/get/" + upload.UPLOADID + "?CompanyId=" + companyId + "'><img src='" + apiUrl + "/files/get/" + upload.UPLOADID + "?CompanyId=" + companyId + "' alt='" + upload.FileName + "' /></a><span class='delete-photo button-red' style=display:none;'>Delete</span></li>").appendTo("#Gallery");
                             //                     window.Code.PhotoSwipe.unsetActivateInstance(myPhotoSwipe);
                             //                     window.Code.PhotoSwipe.detatch(myPhotoSwipe);
                             myPhotoSwipe = $("#Gallery a").photoSwipe({ enableMouseWheel: false, enableKeyboard: false, jQueryMobile: false, preventSlideshow: true });
                         }
                     });
}

function onFail(message) {
    console.log("Camera Failed: " + message);
}

//====== Map Controls ======

function getGeolocation(fieldName) {
    geoField = fieldName;
    try {
        var loc = navigator.geolocation.getCurrentPosition(onGeoSuccess, onFail, { enableHighAccuracy: true });
    } catch (err) { }

}

function onGeoSuccess(position) {
    var lat = position.coords.latitude;
    var lon = position.coords.longitude;

    $("#" + geoField).val(lat + "," + lon);
}

function showMap(fieldName) {
    $('.map-wrapper').show();
    var location = $("#" + fieldName).val();
    var lat = location.substring(0, location.indexOf(","));
    var long = location.substring(location.indexOf(",") + 1);
    var myLatlng = new google.maps.LatLng(lat, long);

    var myOptions = {
        center: myLatlng,
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.HYBRID
    };

    map_element = document.getElementById("map_canvas");
    map = new google.maps.Map(map_element, myOptions);

    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: "Hello World!"
    });
}

//=============== Save Success Message =================

var saveSuccess = function () {
    $("#message-saving").fadeOut(100, function () {
        $("#message-saved").fadeIn(100);
    });

    $("#saving-modal").delay(1000).fadeOut(500);
}

//=============== Save Success Message =================

function SubmitForm() {
    var valid = $("#editForm").validate().form();
    if (valid) {
        valid = $("#specForm").validate().form();
    }

    //console.log(valid);

    if (valid) {

        $("#EquipInternalNotes").val($("#EquipmentNotes").val());
        //$("#EquipDescription").val($("#EquipmentDescription").html());

        if ($("#other_" + makeSpecId).val() != "") {
            $("#EquipMakeCode").val($("#other_" + makeSpecId).val());
        } else if ($("#spec_" + makeSpecId).length > 0) {
            $("#EquipMakeCode").val($("#spec_" + makeSpecId + " option:selected").text());
        } else {
            $("#EquipMakeCode").val($("#efield_" + makeSpecId).val());
        }

        if (typeof $("#other_" + modelSpecId).val() != "undefined" && $("#other_" + modelSpecId).val() != "") {
            $("#EquipModel").val($("#other_" + modelSpecId).val());
        } else if ($("#spec_" + modelSpecId).length > 0) {
            $("#EquipModel").val($("#spec_" + modelSpecId + " option:selected").text());
        } else {
            $("#EquipModel").val($("#efield_" + modelSpecId).val());
        }

        if ($("#OtherSubType").val() != "") {
            $("#EquipSubTypeCode").val($("#OtherSubType").val());
        } else {
            $("#EquipSubTypeCode").val($("#SubTypeCode").val());
        }

        var tempEquip = $("#editForm").serializeObject();
        tempEquip.EquipAdditionalInformation = $("#EquipmentAdditionalInformation").val();
        //var addl = $("#EquipmentAdditionalInformation").val();
        //console.log(tempEquip);
        //console.log(addl);
        var equipJson = JSON.stringify(tempEquip);
        if ($("#CustomerMakeRecordChangePermanent").attr("checked") === "checked")
            $("#CustomerMakeRecordChangePermanent").val("true");
        var custJson = JSON.stringify($("#ConsignorForm").serializeObject());

        if ($("#CreditorMakeRecordChangePermanent").attr("checked") === "checked")
            $("#CreditorMakeRecordChangePermanent").val("true");
        var credJson = JSON.stringify($("#CreditorForm").serializeObject());
        var json = '{"DB2Equipment":' + equipJson + ',"Db2CustomerRecord":' + custJson + ',"Db2CreditorRecord":' + credJson + '}';

        var action = "";
        var type = "";
        var equipmentId = "";
        var dupSerialNumbers = "";

        //console.log("Duplicate: " + $("#DupSerialNumbers").val());
        if ($("#DupSerialNumbers").val() != "") {
            dupSerialNumbers = "&copySerialNumbers=" + $("#DupSerialNumbers").val();
        }

        if ($("#EquipmentID").val() == "0") {
            action = "add";
            type = "POST";
        } else {
            action = "update";
            type = "PUT";
            equipmentId = "&EquipmentId=" + $("#EquipmentID").val();
        }

        $("#saving-modal").show();
        $("#message-saved").hide();
        $("#message-saving").show();

        $.ajax({
            url: apiUrl + "/equipment/" + action + "?CompanyId=" + companyId + equipmentId + dupSerialNumbers,
            cache: false,
            type: type,
            dataType: "json",
            contentType: 'application/json',
            data: json,
            beforeSend: setHeader
        }).done(function (data) {
            $("#EquipmentID").val(data.EquipmentId);
            $("#DupSerialNumbers").val("");
            $("#DupEquipment table tbody").html('<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>');

            if (data.CustomerNumber > 0) {
                $("#CustomerNumber").val(data.CustomerNumber);
                $("#NewCustomer").val("false");
            }

            if (data.ContactNumber > -1 && data.CustomerNumber > 0) {
                $("#CustomerContactNumber").val(data.ContactNumber);
                $("#NewContact").val("false");
            }

            if (data.CreditorContact > -1) {
                $("#CreditorContactNumber").val(data.ContactNumber);
                $("#NewCreditorContact").val("false");
            }

            if (data.CreditorNumber > 0) {
                $("#CreditorNumber").val(data.CreditorNumber);
                $("#NewCreditorCustomer").val("false");
            }

            $("#ProductDescription").show();
            $(".footer-right").show();


            var equipId = data.EquipmentId;
            equipmentId = "&EquipmentId=" + data.EquipmentId;

            equipJson = JSON.stringify($("#editForm").serializeObject());
            var specJson = JSON.stringify($("#specForm").serializeObject());
            json = '{"DB2Equipment":' + equipJson + ',"Specs":' + specJson + '}';


            $.ajax({
                url: apiUrl + "/equipment/savespecs?CompanyId=" + companyId + equipmentId,
                cache: false,
                type: "PUT",
                dataType: "json",
                contentType: 'application/json; charset=utf-8',
                data: json,
                beforeSend: setHeader
            }).always(function (data) {
                if (data != undefined && data.ReturnResult == "error") {
                    alert(data);
                    // Display Error!
                } else {
                    saveSuccess();
                    $("#EquipmentEdit").html(data.EditResult);
                    if (data.EditResult.trim() != "") {
                        $("#EditIssues").show();
                        $("#EditIssues .collapsiblePanel").show();
                    } else {
                        $("#EditIssues").hide();

                        selectedUnits.push(equipId);
                        $("#CopyMode").hide();
                        $("#EquipDupCount").val("0");
                        $("#Duplicate").val("0");
                        $("#DuplicateButton").show();
                        RefreshDescription(true);
                        if (unitsToProcess.length > 0) {
                            var next = unitsToProcess.shift();
                            eval(next);
                        }
                        else {
                            $("#SaveDialog").dialog("open");
                        }
                    }

                }
            });
        })
        .fail(function (data) {
            console.log(data);
            $("#saving-modal").hide();
            $("#message-saving").hide();
            $("#ErrorMessage #divMessage p").html(data.responseText ? data.responseText : "Error updating unit");
            $("#ErrorMessage").dialog("open");
            RefreshQueues();
        })
        .always(UpdateQueueCount);
    }
}

function UpdateQueueCount() {
    console.log("update Queues");
    $.ajax({
        url: apiUrl + "/equipmentqueues/getall/?callback=?",
        data: {
            companyId: companyId,
            sale: currentSale,
            allReps: viewAllReps
        },
        cache: false,
        type: "GET",
        beforeSend: setHeader
    }).always(
                     function (queueData) {
                         $.each(queueData, function () {
                             //$("<li><input type='checkbox' class='multiQueue' onclick='showMultiQueue()' data-id=" + this.QUEUEID + "><a id='queue_" + this.QUEUEID + "' onclick='ShowList(\"" + this.QUEUE + "\", " + this.QUEUEID + ", " + this.ORDERBY + ")'><span>" + this.EQUIPMENTCOUNT + "</span>" + this.QUEUE + "</a></li>").appendTo("#queueList");
                             $("li a#queue_" + this.QUEUEID + " span").html(this.EQUIPMENTCOUNT);

                         });

                     });

}

function QuickStatus(e) {
    var statusId = $(e).data("id");
    if ($(e).parent().attr("id") == "MultiEditStatusOptions") {
        var len = $("#TableContainer tr.selected").length;
        $("#TableContainer tr.selected").each(function (index, element) {
            console.log("Equipment ID: " + $(this).data("id"));
            var json = '{"EquipmentId":"' + $(this).data("id") + '",' +
                                              '"StatusId":"' + statusId + '",' +
                                              '"ActivityDate":"",' +
                                              '"UserName":"' + window.localStorage.getItem("username") + '",' +
                                              '"AssignedTo":"",' +
                                              '"DueDate":"",' +
                                              '"UserLocation":"' + $("#sw_UserLocation").val() + '"}';

            if (index == len - 1) {
                AddStatus(json, true);
            } else {
                AddStatus(json, false);
            }
        });
        $("#MultiStatusEquipment").dialog("close");
    } else {
        var json = '{"EquipmentId":"' + $("#EquipmentID").val() + '",' +
        '"StatusId":"' + statusId + '",' +
        '"ActivityDate":"",' +
        '"UserName":"' + window.localStorage.getItem("username") + '",' +
        '"AssignedTo":"",' +
        '"DueDate":"",' +
        '"UserLocation":"' + $("#sw_UserLocation").val() + '"}';

        AddStatus(json);
    }
}

function AdvancedStatus() {
    var valid = $("#statusForm").validate().form();

    if (valid) {
        var o = {};

        var json = '{"CompanyId":"' + companyId + '",' +
        '"EquipmentId":"' + $("#EquipmentID").val() + '",' +
        '"StatusId":"' + $("#sw_statusstep").val() + '",' +
        '"ActivityDate":"' + $("#sw_statusdate").val() + '",' +
        '"UserName":"' + window.localStorage.getItem("username") + '",' +
        '"AssignedTo":"' + $("#sw_statusassign").val() + '",' +
        '"DueDate":"' + $("#sw_statusduedate").val() + '",' +
        '"UserLocation":"' + $("#sw_UserLocation").val() + '"}';

        AddStatus(json);
    }
}

function AddStatus(json, refresh) {
    refresh = typeof refresh !== 'undefined' ? refresh : true;

    $.ajax({
        type: "POST",
        cache: false,
        url: apiUrl + "/equipment/addstatus?CompanyId=" + companyId,
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        data: json,
        beforeSend: setHeader
    }).done(function (data) {
        //$(data.responseText).prependTo("#historyList");
        $("#sw_statusstep").val("");
        $("#sw_statusstep").prev().html("choose...");

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

}

function ShareEquipment() {

    $("#ShareEquipment .spinner").css("display", "block");

    var json = '{"CompanyId":"' + companyId + '",' +
    '"EquipmentId":"' + $("#EquipmentID").val() + '",' +
    '"Subject":"' + $("#sw_sharesubject").val() + '",' +
    '"SendTo":"' + $("#sw_shareto").val() + '",' +
    '"Body":"' + $("#sw_sharebody").val() + '"}';
    var jsonComplete = '{"CompanyId":' + companyId + ',"ShareJson":' + json + '}';
    $.ajax({
        type: "POST",
        cache: false,
        url: apiUrl + "/equipment/share?companyId=" + companyId,
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        data: json,
        //        data: {
        //            CompanyId: companyId,
        //            ShareJson: json
        //        },
        beforeSend: setHeader
    }).always(function () {
        $("#ShareEquipment").dialog('close');
        $("#ShareEquipment .spinner").css("display", "none");
    });
}

function CopyEquipment() {
    $("#CopyMode").data("id", $("#EquipmentID").val());
    $("#CopyMode").data("vin", $("#EquipVin1").val());
    $("#CopyMode").data("title", $("#EquipTitle").val());
    $("#CopyMode").data("unitno", $("#EquipUnit").val());
    $("#CopyMode").data("EquipStatus", $("#EquipStatus").val());
    $("#CopyMode").data("EquipHold", $("#EquipHold").val());
    $("#CopyMode").data("EquipLotNbr", $("#EquipLotNbr").val());
    $("#CopyMode").data("EquipLotNbrExt", $("#EquipLotNbrExt").val());
    $("#CopyMode").data("EquipTitleStatus", $("#EquipTitleStatus").val());
    $("#CopyMode").data("EquipPrice", $("#EquipPrice").val());
    $("#CopyMode").data("EquipCondition", $("#EquipCondition").val());
    $("#CopyMode").data("EquipMeter", $("#EquipMeter").val());
    $("#CopyMode").data("EquipActualMiles", $("#EquipActualMiles").val());

    $("#EquipmentID").val(0);
    $("#CopyMode").show();
    $('.ipad-button-save').show();
    $('#editForm').find('input, textarea, button, select').removeAttr('disabled');
    $('#specForm').find('input, textarea, button, select').removeAttr('disabled');


    $(".footer-tab").css("height", "624px");
    $("#EquipTitle").val("");
    $("#EquipVin1").val("");
    $("#EquipUnit").val("");
    $("#EquipStatus").val("");
    $("#EquipHold").val("");
    $("#EquipLotNbr").val("");
    $("#EquipLotNbrExt").val("");
    $("#EquipTitleStatus").val("");
    $("#EquipPrice").val("");
    $("#EquipCondition").val("");
    $("#EquipMeter").val("");
    $("#EquipActualMiles").val("");

    $("#EquipVin1").focus();
}

function CancelCopy() {
    $("#EquipmentID").val($("#CopyMode").data("id"));
    $("#EquipVin1").val($("#CopyMode").data("vin"));
    $("#EquipTitle").val($("#CopyMode").data("title"));
    $("#EquipUnit").val($("#CopyMode").data("unitno"));
    $("#EquipStatus").val($("#CopyMode").data("EquipStatus"));

    $("#EquipHold").val($("#CopyMode").data("EquipHold"));
    $("#EquipLotNbr").val($("#CopyMode").data("EquipLotNbr"));
    $("#EquipLotNbrExt").val($("#CopyMode").data("EquipLotNbrExt"));
    $("#EquipTitleStatus").val($("#CopyMode").data("EquipTitleStatus"));
    $("#EquipPrice").val($("#CopyMode").data("EquipPrice"));
    $("#EquipCondition").val($("#CopyMode").data("EquipCondition"));
    $("#EquipMeter").val($("#CopyMode").data("EquipMeter"));
    $("#EquipActualMiles").val($("#CopyMode").data("EquipActualMiles"));


    $("#CopyMode").hide();
    $(".footer-tab").css("height", "653px");
    ApplySecurity();
}

function ShowAccount() {
    $("#accountInfo").show();
    $(".queues-list").hide();
    $(".footer-left .active").removeClass("active");
    $(".button-settings").parent().addClass("active");
}

function HideAccount() {
    $("#accountInfo").hide();
}

function SignOut(redirect) {
    window.localStorage.setItem("email", "");
    window.localStorage.setItem("password", "");
    window.localStorage.setItem("companyId", "");

    window.location.href = redirect;
}

function BuildElement(typeId, id, fieldName, printorderby, fieldLength, fieldPrecision, options, allownulls, mode, choose) {
    var element = "<label data-label='" + fieldName + "'>" + fieldName + "(<a class='sequence-number' data-id='" + id + "'>" + printorderby + "</a>)</label><input type='hidden' id='po_" + id + "' name='po_" + id + "' value='" + printorderby + "' tabindex'1'/>";
    var validation = "";

    if (!allownulls) {
        validation = "required";
    }

    if (typeId == 1 || typeId == 5 || typeId == 12) {
        if (fieldPrecision > 0) {
            element += "<input type='text' class='" + validation + "' id='" + id + "' name='" + id + "' data-val='true' maxLength='" + (fieldLength + 1) + "' max='" + (Math.pow(10, (fieldLength - fieldPrecision)) - 1) + "' Data-val-number='" + fieldName + " must be a number.' tabindex='1'/>";
        } else {
            element += "<input type='text' class='" + validation + "' id='" + id + "' name='" + id + "' data-val='true' maxLength='" + fieldLength + "' max='" + (Math.pow(10, fieldLength) - 1) + "' Data-val-number='" + fieldName + " must be a number.' tabindex='1'/>";
        }
        //  number || number with decimal || money
        element += "<span class='field-validation-valid' data-valmsg-for='" + id + "' data-valmsg-replace='true'></span>";
    }
    else if (typeId == 2) {
        //  drop down list
        element += "<select class='options-ipad " + validation + "' id='" + id + "' name='" + id + "' tabindex='1'><option value=''>choose...</option>";
        var o = options.split(';');
        $.each(o, function () {
            element += "<option>" + this + "</option>";
        });
        element += "</select>";
    }
    else if (typeId == 3) {
        //  date
        element += "<input class='" + validation + "' type='date' id='" + id + "' name='" + id + "' tabindex='1' />";
    }
    else if (this.FieldTypeId == 4) {
        //  date and time
        element += "<input class='" + validation + "' type='datetime' id='" + id + "' name='" + id + "' tabindex='1' />";
    }
    else if (typeId == 6) {
        //  text
        element += "<input type='text' class='" + validation + "' id='" + id + "' name='" + id + "' maxLength='" + fieldLength + "'  tabindex='1'/>";
    }
    else if (typeId == 7) {
        //  computed
        if (mode == "update") {
            element += "<input type='text' id='" + id + "' name='" + id + "' disabled='disabled'  tabindex='1'/>";
        }
    }
    else if (typeId == 8) {
        //  url
        element += "<input class='" + validation + "' type='url' id='" + id + "' name='" + id + "' maxLength='" + fieldLength + "' tabindex='1' />";
    }
    else if (typeId == 9) {
        //  yes/no checkbox
        element += "<div class='checkbox-single'><div class='checkbox-false' tabindex='1'></div><input class='check-box " + validation + "'  id='" + id + "' name='" + id + "' /></div>";
    }
    else if (typeId == 10) {
        //  geolocation
        element += "<input class='" + validation + "' id='" + id + "' name='" + id + "'  tabindex='1'/><a href='javascript:void(0)' onclick='getGeolocation(\"" + id + "\");' style='font-size:12px;'>Get Location</a> <a href='javascript:void(0)' onclick='showMap(\"" + id + "\");' style='font-size:12px;'>Show Map</a>";
    }
    else if (typeId == 11) {
        //  check all that apply
        element += "<select multiple='multiple' class='options-ipad " + validation + "' id='" + id + "' name='" + id + "' tabindex='1'><option value=''>choose...</option>";
        var o = options.split(';');
        $.each(o, function () {
            element += "<option>" + this + "</option>";
        });
        element += "</select>";
    }
    else if (typeId == 13) {
        //  text
        element += "<textarea class='" + validation + "' id='" + id + "' name='" + id + "' maxLength='" + fieldLength + "' tabindex='1'></textarea>";
    } else {
        element += "<input type='text' class='" + validation + "' id='" + id + "' name='" + id + "' maxLength='" + fieldLength + "'  tabindex='1'/>";
    }
    return "<div class='field-wrapper'>" + element + "</div>";
}

function RefreshSettings() {
    GetBusiness(defaultBusinessId, $("#sw_defaultbusiness"));
    GetBusiness(companyId, $("#sw_business"));

    $("#sw_email").html(window.localStorage.getItem("username"));
    $("#sw_sale").html("<option value='0'>All Sales</option>");
    $("#sw_defaultsale").html("<option value='0'>None</option>");
    $("#ConsignorSearchSale").html("<option value=''>All Sales</option>");
    $.when(GetSales()).then(function (sales) {
        $.each(sales, function () {
            $("<option value='" + this.SASAL_ + "'>" + this.SASAL_ + " - " + this.SADATE.toString().substr(4, 2) + "/" + this.SADATE.toString().substr(6) + "/" + this.SADATE.toString().substr(0, 4) + " - " + this.SACITY + ", " + this.SAST + "</option>").appendTo("#sw_defaultsale");
            $("<option value='" + this.SASAL_ + "'>" + this.SASAL_ + " - " + this.SADATE.toString().substr(4, 2) + "/" + this.SADATE.toString().substr(6) + "/" + this.SADATE.toString().substr(0, 4) + " - " + this.SACITY + ", " + this.SAST + "</option>").appendTo("#sw_sale");
            $("<option value='" + this.SASAL_ + "'>" + this.SASAL_ + " - " + this.SADATE.toString().substr(4, 2) + "/" + this.SADATE.toString().substr(6) + "/" + this.SADATE.toString().substr(0, 4) + " - " + this.SACITY + ", " + this.SAST + "</option>").appendTo("#ConsignorSearchSale");
            $("<option value='" + this.SASAL_ + "'>" + this.SASAL_ + " - " + this.SADATE.toString().substr(4, 2) + "/" + this.SADATE.toString().substr(6) + "/" + this.SADATE.toString().substr(0, 4) + " - " + this.SACITY + ", " + this.SAST + "</option>").appendTo("#saleNumber");
            $("<option value='" + this.SASAL_ + "'>" + this.SASAL_ + " - " + this.SADATE.toString().substr(4, 2) + "/" + this.SADATE.toString().substr(6) + "/" + this.SADATE.toString().substr(0, 4) + " - " + this.SACITY + ", " + this.SAST + "</option>").appendTo("#saleNumberAll");
        });
        GetUser();
    });

    $.ajax({
        url: apiUrl + "/especs/getconfig/?callback=?",
        cache: false,
        type: "GET",
        data: {
            companyId: companyId
        },
        beforeSend: setHeader
    }).done(function (data) {
        $.each(data, function () {
            if (this.CONFIGKEY == "MISCPRINTORDER") {
                miscPrintOrder = parseInt(this.CONFIGVALUE, 10);
            } else if (this.CONFIGKEY == "DEFAULTDIVISION") {
                defaultDivision = this.CONFIGVALUE;
            } else if (this.CONFIGKEY == "DEFAULTCOMMISSION") {
                defaultCommission = this.CONFIGVALUE;
            } else if (this.CONFIGKEY == "PHOTOQUALITY") {
                photoQuality = this.CONFIGVALUE;
            } else if (this.CONFIGKEY == "PHOTOHEIGHT") {
                photoHeight = this.CONFIGVALUE;
            } else if (this.CONFIGKEY == "PHOTOWIDTH") {
                photoWidth = this.CONFIGVALUE;
            }
        });
    }).fail(function (data) {
        console.log("refresh settings failed");
        console.log(data);
    });
}

function GetBusiness(id, element) {
    $.ajax({
        url: apiUrl + "/businesses/get/?callback=?",
        cache: false,
        type: "GET",
        data: {
            id: id
        },
        beforeSend: setHeader
    }).always(
                     function (data) {
                         element.html(data.DESCRIPTION);
                     });
}

function SetDefaultSale() {
    $.ajax({
        url: apiUrl + "/account/setdefaultsale/?callback=?",
        cache: false,
        type: "POST",
        data: {
            UserId: userId,
            CompanyId: companyId,
            SaleNumber: defaultSale
        },
        beforeSend: setHeader
    });
}

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

}

function GetSubTypes() {
    $("#SubTypeCode").html("<option value=''>choose...</option>");
    $("#OtherSubType").val("");
    console.log("Class: " + $("#EquipClassID").val());
    return $.ajax({
        url: apiUrl + "/subtypes/getall/?callback=?",
        cache: false,
        type: "GET",
        data: {
            companyId: companyId,
            classId: $("#EquipClassID").val()
        },
        beforeSend: setHeader
    });
}

function GetSalesPeople() {
    $("#EquipSalesRep").html("<option value=''>choose...</option>");

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

function GetDivisions() {
    $("#EquipDivision").html("<option value=''>choose...</option>");

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

function GetBuyer(buyerId, buyerIndex) {
    $("#buyerline1").html("");
    $("#buyerline2").html("");
    $("#buyerline3").html("");
    $("#buyerline4").html("");
    $("#buyerline5").html("");

    if (buyerId > 0) {
        $.ajax({
            url: apiUrl + "/customers/get/?callback=?",
            cache: false,
            type: "GET",
            data: {
                id: buyerId,
                index: buyerIndex,
                companyId: companyId
            },
            beforeSend: setHeader
        }).always(
                         function (data) {
                             $("#buyerline1").html(data.CUNAME);
                             $("#buyerline2").html(data.CUFNAM + " " + data.CULNAM);
                             $("#buyerline3").html(data.CUMAD1);
                             $("#buyerline4").html(data.CUMCTY + ", " + data.CUMSTA + " " + data.CUMZIP);
                             $("#buyerline5").html(data.CUPHN_);
                         });
    }
}

function GetHeader(equipmentId, classDesc) {
    $("#EquipSale").html("<option value=''>choose...</option>");

    $.when(GetSales(), GetSubTypes(), GetSalesPeople(), GetDivisions()).then(function (sales, subtypes, salespeople, divisions) {
        $.each(sales[0], function () {
            $("<option value='" + this.SASAL_ + "'>" + this.SASAL_ + " - " + this.SADATE.toString().substring(4, 6) + "/" + this.SADATE.toString().substring(6) + "/" + this.SADATE.toString().substring(0, 4) + " - " + this.SACITY + ", " + this.SAST + "</option>").appendTo("#EquipSale");
        });

        $.each(subtypes[0], function () {
            $("<option value='" + this.SBCODE + "'>" + this.SBDESC + "</option>").appendTo("#SubTypeCode");
        });

        var UserSalesRepInit = 0;
        $.each(salespeople[0], function () {
            $("<option value='" + this.SLINIT + "'>" + this.SLNAME + "</option>").appendTo("#EquipSalesRep");
            if (this.USERID == userId) {
                UserSalesRepInit = this.SLINIT;
            }
        });

        $.each(divisions[0], function () {
            $("<option value='" + this.DMDVID + "'>" + this.DMNAME + "</option>").appendTo("#EquipDivision");
        });

        if (equipmentId == 0) {
            ClearEquipmentHeader();
            $("#EquipCommissionAmount").val("0");

            if (currentSale != 0) {
                $("#EquipSale").val(currentSale);
            } else if (defaultSale != 0) {
                $("#EquipSale").val(defaultSale);
            }

            if (UserSalesRepInit != 0) {
                $("#EquipSalesRep").val(UserSalesRepInit);
            }

            if (defaultDivision != null && defaultDivision.length > 0) {
                $("#EquipDivision").val(defaultDivision);
            }

            $(".rightLoading").hide();
        } else {
            $.ajax({
                url: apiUrl + "/equipment/getheader/?callback=?",
                cache: false,
                type: "GET",
                data: {
                    id: equipmentId,
                    companyId: companyId
                },
                beforeSend: setHeader
            }).success(
                function (data) {
                    //console.log(data);
                    if (data.TREDFLG == "Y") {
                        $("#EquipmentEdit").html(data.TREDMSG.trim());
                        $("#EditIssues").show();
                    }
                    
                    if (multiEditActive == false) {
                        $("#EquipmentHeader :input").prop('disabled', false);
                        $(".page-header-internal h1").html("Seq #" + data.TRSEQ_ + " (" + classDesc + ")");
                    }
                    else {
                        $("#EquipmentHeader :input").prop('disabled', true);
                        $(".page-header-internal h1").html("Multiple Units Selected (" + multiEditClass + ")");
                    }

                    $("#EquipmentID").val(equipmentId);
                    $("#EquipStatus").val(data.TRSTAT);
                    $("#EquipDivision").val(data.TRDVID);
                    $("#EquipSale").val(data.TRSAL_);
                    $("#EquipVin1").val(TrimValue(data.TRSERL));
                    $("#EquipYear").val(TrimValue(data.TRYEAR));
                    $("#EquipMakeCode").val(TrimValue(data.TRMAKE));
                    $("#EquipModel").val(TrimValue(data.TRMODL));
                    $("#EquipBidNbr").val(TrimValue(data.TRBID_));
                    $("#EquipLotNbr").val(TrimValue(data.TRLOT_));
                    $("#EquipLotNbrExt").val(TrimValue(data.TRLOTA));
                    $("#EquipUnit").val(TrimValue(data.TRCUNT));

                    $("#EquipSalesRep").val(TrimValue(data.TRSLSM));
                    $("#EquipHiQuote").val(TrimValue(data.TRHIQU));
                    $("#EquipLowQuote").val(TrimValue(data.TRLOWQ));
                    $("#EquipTitle").val(TrimValue(data.TRTTL_));
                    $("#EquipTitleStatus").val(TrimValue(data.TRTTLS));
                    $("#EquipCondition").val(TrimValue(data.TRCOND));
                    $("#EquipHold").val(TrimValue(data.TRHOLD));
                    $("#EquipMeter").val(TrimValue(data.TRODMT));
                    $("#EquipActualMiles").val(TrimValue(data.TRACTM));
                    $("#EquipPrice").val(TrimValue(data.TRPRICE));

                    //var commission = parseFloat(Math.round(data.TRCOMC * 10) / 10).toFixed(1);
                    $("#EquipCommissionCode").val(data.TRCOMC);

                    $("#EquipCommissionAmount").val(data.TRCAMT);

                    $("#EquipInternalNotes").val(TrimValue(data.TRNOTES));
                    $("#EquipmentNotes").val(TrimValue(data.TRNOTES));
                    //$("#EquipDescription").val(data.TRDESCR.trim());
                    $("#EquipmentDescription").html(TrimValue(data.TRDESCR));

                    $("#EquipSubTypeCode").val(TrimValue(data.TRSTYP));

                    $("#EquipNonRunner").val(TrimValue(data.TRNONRUN));
                    $("#EquipTitleInformation").val(TrimValue(data.TRTTLIN));
                    $("#EquipmentAdditionalInformation").val(TrimValue(data.TRADLINF));


                    if (data.TRSTYP.trim() != "") {
                        if ($("#SubTypeCode option[value='" + data.TRSTYP + "']").length > 0) {
                            $("#SubTypeCode").val(data.TRSTYP);
                        } else {
                            $("#OtherSubType").val(data.TRSTYP.trim());
                        }
                    }

                    if ($("#EquipmentNotes").val() != "") {
                        $("#EquipmentNotes").parents(".collapsiblePanel").show();
                    }
                    $(".footer-right").show();
                    $(".rightLoading").hide();

                    
                });
        }

    });
}

function BuildFields(classId, classDesc, equipmentId) {
    cascadingSpecs = [];
    var mode = "insert";
    if (equipmentId != undefined) {
        mode = "update";
    }

    $.ajax({
        url: apiUrl + "/fieldgroups/getall/?callback=?",
        cache: false,
        type: "GET",
        data: {
            companyId: companyId
        },
        beforeSend: setHeader
    }).always(
                     function (data) {
                         $.each(data, function (index, element) {
                             var group = "<h1 style='clear:both;'>" + this.TITLE + "</h1><div class='collapsiblePanel' style='display:none;'><div class='specfields' style='padding:0' id='group_" + this.FIELDGROUPID + "'></div></div>";
                             $(group).appendTo("#metaFields");
                         });

                         $.ajax({
                             url: apiUrl + "/equipmentfields/getall/?callback=?",
                             cache: false,
                             type: "GET",
                             data: {
                                 id: classId,
                                 companyId: companyId
                             },
                             beforeSend: setHeader
                         }).always(
                                      function (data) {

                                          retrocycle(data);

                                          var groupWrapper;
                                          var groupArray = [];

                                          $.each(data, function (index, element) {
                                              var options = this.OPTIONS;
                                              var choose = "choose...";

                                              if (this.FIELDNAME == "Make") { makeSpecId = this.EQUIPMENTFIELDID; }
                                              if (this.FIELDNAME == "Model") { modelSpecId = this.EQUIPMENTFIELDID; }

                                              //Handle the cascading spec
                                              if (this.SPECTYPEs.length > 0) {
                                                  var id = "spec_" + this.EQUIPMENTFIELDID;
                                                  $("<div class='field-wrapper'><label data-label='" + this.FIELDNAME + "'>" + this.FIELDNAME + "(<a class='sequence-number' data-id='" + id + "'>" + this.PRINTORDERBY + "</a>)</label><input type='hidden' id='po_" + id + "' name='po_" + id + "' value='" + this.PRINTORDERBY + "' tabindex='1' /><select style='width:136px;' id='" + id + "' name='" + id + "' tabindex='1'><option value=''>choose...</option></select>").appendTo("#group_" + this.FIELDGROUPID);

                                                  //add the options
                                                  $.each(this.SPECTYPEs, function () {
                                                      var triggerDD = "";
                                                      var defaultSpec = this.DEFAULTSPECID;

                                                      //the array in spec type1 does what?
                                                      if (this.SPECTYPE1.length > 0) {
                                                          $("#" + id).addClass("trigger-change");
                                                      }

                                                      //the array in spec type2 is the parent. So bind the parent ddl to the checkCascade class.
                                                      if (this.SPECTYPE2 != null) {
                                                          triggerDD = "spec_" + this.SPECTYPE2.EQUIPMENTFIELDID;
                                                          $("#" + triggerDD).addClass("checkCascade");
                                                      }

                                                      //is this a child of some other spec?
                                                      if (this.PARENTSPECTYPEID == null) {

                                                          var specs = [];
                                                          $.each(this.SPECs, function () {
                                                              if (mode == "update" || this.ACTIVE == "Y") {
                                                                  var spec = [];
                                                                  spec[0] = this.SPECID;
                                                                  spec[1] = this.DESCRIPTION;
                                                                  spec[2] = this.PARENTSPECID;
                                                                  spec[3] = this.ORDERBY;
                                                                  spec[4] = this.ACTIVE;
                                                                  specs.push(spec);
                                                              }
                                                          });

                                                          specs.sort(function (a, b) { return (a[3] < b[3] ? -1 : (a[3] > b[3] ? 1 : 0)); });

                                                          $.each(specs, function () {
                                                              $("#" + id).append("<option value='" + this[0] + "'>" + this[1] + "</option>");
                                                              if (this[0] == defaultSpec) {
                                                                  $("#" + id).val(this[0]);
                                                              }

                                                          });
                                                          //Yes this is a child
                                                      } else {
                                                          $.each(this.SPECs, function () {
                                                              if (mode == "update" || this.ACTIVE == "Y") {
                                                                  var specs = new Spec(this.SPECID, this.DESCRIPTION, this.PARENTSPECID, id, this.ORDERBY, triggerDD, this.ACTIVE);
                                                                  cascadingSpecs.push(specs);
                                                              }
                                                          });

                                                          if (this.SPECTYPE2 != undefined) {
                                                              $("#" + id + " option:first-child").html("choose " + this.SPECTYPE2.DESCRIPTION + "...");
                                                          }

                                                          $("#" + id + " option:first-child").val("");

                                                      }

                                                  });
                                                  //the array in spec type2 is the parent. So bind the parent ddl to the checkCascade class.
                                                  var otherSp = "other_" + this.EQUIPMENTFIELDID;
                                                  if (this.SPECTYPE2 != null) {
                                                      $("#" + triggerDD).addClass("checkCascade");
                                                  }
                                                  $("#group_" + this.FIELDGROUPID + " #" + id).parent().append("<input class='otherSpec' type='text' id='other_" + this.EQUIPMENTFIELDID + "' name='" + otherSp + "' style='margin-top:5px;' placeholder='other'/>");

                                              } else {
                                                  //this is not a cascading spec.
                                                  var id = "efield_" + this.EQUIPMENTFIELDID;
                                                  $(BuildElement(this.FIELDTYPEID, id, this.FIELDNAME, this.PRINTORDERBY, this.FIELDLENGTH, this.FIELDPRECISION, options, "false", mode, choose)).appendTo("#group_" + this.FIELDGROUPID);
                                              }

                                              if (groupWrapper != "#group_" + this.FieldGroupId) {
                                                  groupWrapper = "#group_" + this.FieldGroupId;
                                                  groupArray.push(groupWrapper);
                                              }

                                          });

                                          $.each(groupArray, function (index, value) {
                                              $("<div style='clear:both;float:none;'></div>").appendTo(value);
                                          });

                                          if (mode == "update") {
                                              $.ajax({
                                                  url: apiUrl + "/equipmentspecs/get/?callback=?",
                                                  cache: false,
                                                  type: "GET",
                                                  data: {
                                                      id: equipmentId,
                                                      companyId: companyId
                                                  },
                                                  beforeSend: setHeader
                                              }).always(
                                                       function (data) {
                                                           $(data).each(function () {
                                                               if (this.SPECID != null) {
                                                                   $("#spec_" + this.EQUIPMENTFIELDID).val(this.SPECID);
                                                                   $("#spec_" + this.EQUIPMENTFIELDID).prev(".selectbox").html(this.DESCRIPTION);
                                                                   if ($("#spec_" + this.EQUIPMENTFIELDID).hasClass("trigger-change")) {
                                                                       $("#spec_" + this.EQUIPMENTFIELDID).trigger("change");
                                                                   }
                                                                   // Print Order
                                                                   $("#po_spec_" + this.EQUIPMENTFIELDID).val(this.PRINTORDERBY);
                                                                   $("#po_spec_" + this.EQUIPMENTFIELDID).prev().children("a").html(this.PRINTORDERBY);
                                                               } else if (this.OTHER != null) {
                                                                   $("#other_" + this.EQUIPMENTFIELDID).val(this.OTHER);
                                                                   $("#other_" + this.EQUIPMENTFIELDID).css("background-color", "#FBFCC7");
                                                               } else if (this.MISCID != null) {
                                                                   miscSpecCount += 1;

                                                                   $("<div class='field-wrapper' style='width:95%;'><label data-label='Miscellaneous'>Miscellaneous (<a class='sequence-number' data-id='misc_" + this.MISCID + "'>" + this.PRINTORDERBY + "</a>)</label><input type='hidden' id='po_misc_" + this.MISCID + "' name='po_misc_" + this.MISCID + "' value='" + this.PRINTORDERBY + "' tabindex='1'/><textarea class='misc-text' id='misc_" + this.MISCID + "' name='misc_" + this.MISCID + "' style='width:100%;' maxlength='200' cols='200' >" + this.SPECVALUE + "</textarea></div>").appendTo($('.specfields'));

                                                                   // Print Order
                                                                   //$("#po_misc_" + this.MISCID).val(this.ORDERBY);
                                                               } else if (this.SPECVALUE != null) {
                                                                   if ($("#efield_" + this.EQUIPMENTFIELDID).hasClass("check-box")) {
                                                                       if (this.SPECVALUE == "true") {
                                                                           $("#efield_" + this.EQUIPMENTFIELDID).prev().toggleClass("checkbox-false checkbox-true");
                                                                       }
                                                                   }
                                                                   $("#efield_" + this.EQUIPMENTFIELDID).val(this.SPECVALUE);

                                                                   // Print Order
                                                                   $("#po_efield_" + this.EQUIPMENTFIELDID).val(this.PRINTORDERBY);
                                                                   $("#po_efield_" + this.EQUIPMENTFIELDID).prev().children("a").html(this.PRINTORDERBY);
                                                               }
                                                           });

                                                           //  Remove all specs that are not active and is not the selected value.
                                                           $("option[data-active='N']:not(:selected)").remove();

                                                           ApplySecurity();
                                                           $("#specForm").validate();

                                                           $("#ItemList").hide();
                                                           $("#AdvSearch").hide();
                                                           $(".footer-tab").hide();
                                                           $(".info-tab").show();
                                                           $("#InfoTab").show();
                                                       });
                                          } else {
                                              $("#ItemList").hide();
                                              $("#AdvSearch").hide();
                                              $(".footer-tab").hide();
                                              $(".info-tab").show();
                                              $("#InfoTab").show();
                                              //$(".page-header-internal h1").html("");
                                          }

                                          $(".selectbox").click(function () {
                                              $(this).next().focus();
                                          });

                                          $(".options-ipad,.options").blur(function () {
                                              var option = $("option:selected", this).text();

                                              if (option == "") {
                                                  option = $(this).val();
                                              }

                                              $(this).siblings().html(option);
                                          });
                                          $("#specForm").validate();
                                          
                                      });
                         //put code to clear changed statuses
                         $(".changed").removeClass("changed");
                     });


    $(".selectbox").click(function () {
        $(this).next().focus();
    });

    $(".options-ipad,.options").blur(function () {
        var option = $("option:selected", this).text();

        if (option == "") {
            option = $(this).val();
        }

        $(this).siblings().html(option);
    });
}

function SavePhotos() {
    var json = '{"EquipmentId":"' + $("#EquipmentID").val() + '",' +
    '"UploadIds":"' + $("#Gallery").sortable('toArray') + '"}';

    $.ajax({
        url: apiUrl + "/files/save?CompanyId=" + companyId,
        type: "POST",
        dataType: "json",
        contentType: 'application/json; charset=utf-8',
        data: json,
        beforeSend: setHeader
    }).always(
                     function (data) {
                         //                     window.Code.PhotoSwipe.unsetActivateInstance(myPhotoSwipe);
                         //                     window.Code.PhotoSwipe.detatch(myPhotoSwipe);
                         myPhotoSwipe = $("#Gallery a").photoSwipe({ enableMouseWheel: false, enableKeyboard: false, jQueryMobile: false, preventSlideshow: true });

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

function ClearEquipmentHeader() {
    $("#EquipmentID").val("0");
    $("#EquipDivision").val(defaultDivision);
    $("#EquipSale").val("");
    $("#EquipVin1").val("");
    $("#EquipYear").val("");
    $("#EquipMakeCode").val("");
    $("#EquipModel").val("");
    $("#EquipBidNbr").val("");
    $("#EquipLotNbr").val("");
    $("#EquipLotNbrExt").val("");
    $("#EquipUnit").val("");
    $("#EquipSalesRep").val("");
    $("#EquipHiQuote").val("");
    $("#EquipLowQuote").val("");
    $("#EquipTitle").val("");
    $("#EquipTitleStatus").val("");
    $("#EquipCondition").val("");
    $("#EquipHold").val("");
    $("#EquipMeter").val("");
    $("#EquipActualMiles").val("");
    $("#EquipPrice").val("");
    $("#EquipCommissionCode").val($("#CustomerCommissionCode").val());
    $("#EquipCommissionAmount").val("");
    $("#EquipInternalNotes").val("");
    $("#EquipmentNotes").val("");
    //$("#EquipDescription").val("");
    $("#EquipmentDescription").html("");
    $("#EquipmentAdditionalInformation").html("");
    $("#EquipTitleInformation").html("");
    $("#EquipNonRunner").html("");
}

function RefreshDescription(includeQuotes) {
    $.ajax({
        url: apiUrl + "/equipment/getdescription/?callback=?",
        cache: false,
        type: "GET",
        data: {
            CompanyId: companyId,
            EquipmentId: $("#EquipmentID").val(),
            IncludeQuotes: includeQuotes
        },
        beforeSend: setHeader
    }).success(
                      function (data) {
                          //$("#EquipDescription").val(data);
                          $("#EquipmentDescription").html(data);
                          $("#SaveDialog p").html(data);
                      });
}

function ApplySecurity(reset) {
    reset = typeof reset !== 'undefined' ? reset : false;

    if (reset) {
        $('#editForm').find('input, textarea, button, select').removeAttr('disabled');
        $('#specForm').find('input, textarea, button, select').removeAttr('disabled');

        $('#DeleteButton').show();
        $('.ipad-button-save').show();
        $('.button-copy').show();
        $('#CopyButton').show();

        $('#EditPhotos').show();
        $('#UploadPhotos').show();

        $('.status').removeAttr('disabled');
        $('.photo').removeAttr('disabled');
    } else {
    $.ajax({
        url: apiUrl + "/users/getpermission/?callback=?",
        cache: false,
        type: "GET",
        data: {
            CompanyId: companyId,
            EquipmentId: $("#EquipmentID").val(),
            UserId: userId
        },
        beforeSend: setHeader
    }).success(
                      function (data) {
                          //console.log(data);
                          $('#DuplicateButton').hide();

                          if (data == "readonly") {
                              $('#editForm').find('input, textarea, button, select').attr('disabled', 'disabled');
                              $('#specForm').find('input, textarea, button, select').attr('disabled', 'disabled');

                              $('#DeleteButton').hide();
                              $('.ipad-button-save').hide();

                              $('#EditPhotos').hide();
                              $('#UploadPhotos').hide();

                              $('.status').attr('disabled', 'disabled');
                              $('.photo').attr('disabled', 'disabled');
                          } else {
                              $('#editForm').find('input, textarea, button, select').removeAttr('disabled');
                              $('#specForm').find('input, textarea, button, select').removeAttr('disabled');

                              $('#DeleteButton').show();
                              $('.ipad-button-save').show();

                              $('#EditPhotos').show();
                              $('#UploadPhotos').show();

                              $('.status').removeAttr('disabled');
                              $('.photo').removeAttr('disabled');

                              if (data == "admin") {
                                  $('#DuplicateButton').show();
                                  adminUser = true;
                              }
                          }
                      });
    }
}

function setHeader(xhr) {

    if (!window.btoa) window.btoa = base64.encode;
    if (!window.atob) window.atob = base64.decode;
    xhr.setRequestHeader("Authorization",
                         "Basic " + window.btoa(window.localStorage.getItem("username") + ":" + window.localStorage.getItem("password"))
                         );
}

function JsonifyForm(form) {
    //    if (form.valid())
    if (true) {
        return JSON.stringify(form.serializeObject());
    }
}

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
}



function createGrid(fields, data) {
    columns = fields.length;

    for (var i = 0, m = null; i < fields.length; ++i) {
        if (fields[i].field == "TRSERL") {
            fields[i].encoded = false;


            //fields[i].template = '<span style="float:right">#= TRSERL #</span>'TRSLSM
        }
        if (fields[i].field == "TRSTAT" || fields[i].field == "SUBTYPE" || fields[i].field == "TYPEID" || fields[i].field == "TRDPST") {
            fields[i].width = 50;
        }
        if (fields[i].field == "TRSLSM" ) {
            fields[i].width = 90;
        }
        fields[i].filterable = { cell: { operator: "contains"} };
    }
    fields.unshift({ "field": "edit", "title": " ", encoded: false , filterable : false, width:50});

    var schemaFields = {};
    var intRegex = /^\d+$/;
    if (data[0]){
        for (var key in data[0]) {
            if (intRegex.test(data[0][key])) {
                //console.log('I am an int: ' + data[0][key]);
                schemaFields[key] = { type: "number" };
            }
            //else { console.log("Not an int: " + data[0][key]); }
        }
    }

    $("#grid").kendoGrid({
        dataSource: {
            type: "json",
            data: data,
            pageSize: currentPageSize,
            schema: {
                model: {
                    fields: schemaFields
                }
            }
        },
        //height: 605,
        navigatable: true,
        selectable: "multiple",
        scrollable: false,
        pageable: {
            input: true,
            numeric: false,
            pageSizes: [10, 25, 50, 100, 200, data.length],
            change: function (e) {
                currentPage = e.index;
                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(currentPage);
                //console.log(currentPageSize);
            }
        },
        sortable: {
            mode: "multiple",
            allowUnsort: true
        },
        filterable: {
            mode: "menu",
            operators: {
                string: {
                    contains: 'Contains'
                }
            }
        },
        groupable: true
         ,
        columns: fields,
        dataBound: onDataBound



    });

    $("#grid").find(".k-pager-wrap").attr("style", "border-bottom: 1px solid #ccc; border-top-style: none;");
    $("#grid").find(".k-pager-wrap").insertBefore(".k-grouping-header");

//    $("#slide-close").trigger("click");
}

$(function () {
    $("#views-search").click(function () {
        console.log("foo")
        $("#slide-open").trigger("click");
    });
});


function onDataBound() {
    dataView = this.dataSource.view();
    var grid = $("#grid").data("kendoGrid");

                //console.log(dataView);
    for (var i = 0; i < dataView.length; i++) {
        var uid = dataView[i].uid;
        var row = $("#grid tbody").find("tr[data-uid=" + uid + "]");
        if (dataView[i].TRSTAT == "A" || dataView[i].TRSTAT == "S") {
            //
            row.addClass("highlighted");
        }
        else  {
            var uid = dataView[i].uid;
            row.addClass("nothighlighted");
        }
        row.addClass(dataView[i].class);
        row.data("id", dataView[i].EQUIPMENTID);
    }

//                 



//    $(".k-grid-content").height("540px");

//    $(".k-grid-content").width(columns * 115 + "px");
}

function showMultiQueue() {
    selectedQueueId = undefined;
    ids = [];
    //console.log("hit showMultiQ");
    $.each($(".multiQueue:checked"), function (i, q) {
        //console.log("hit loop");
        var id = $(q).data("id");
        ids[ids.length] = id;


    });
    //console.log(ids);
    ShowList("Selected Queues", ids, null);
}

$(document).ready(function () {
    //set defaults for grid
    //console.log("setting gred defaults");
    if (window.localStorage.getItem("pageable") == null) {
        //console.log("pageable is null");
        window.localStorage.setItem("pageable", true);
    } else {
        //console.log("pageable is: " + window.localStorage.getItem("pageable"));
    }
    if (window.localStorage.getItem("pageSize") == null) {
        window.localStorage.setItem("pageSize", 25);
    }
});

$("#pagingCount").focusout(function () {
    //console.log("changed to: " + $(this).val());
});
function updatePagingCount() {
    lastPageSize = parseInt($("#pagingCount").val());
    //$("#pagingCount").val(lastPageSize);

    //console.log("changed to: " + lastPageSize);

}



$('select[data-role="dropdownlist"]').select(function(){
    //console.log("selected new page size");
});


