var searchFieldsInitialized = false;

$(function(){
  $("#SearchType").change(function(){
                          $("#SearchClass").children('option:not(:first)').remove();
                          var typeId = $(this).val();
                          
                          $.ajax({
                                 url: apiUrl + "/classes/getall/?callback=?",
                                 cache: false,
                                 type: "GET",
                                 data: {
                                 companyId: companyId,
                                 typeId: typeId
                                 },
                                 beforeSend: setHeader
                                 }).done(
                                         
                                         function (classData) {
                                         $.each(classData, function (i, item) {
                                                $("#SearchClass").append("<option value='" + item.CLASSID + "'>" + item.CLDESC + "</option>");
                                                });
                                         });
                          });
  
  $("#SearchClass").change(function(){
                           $("#SearchMake").children('option:not(:first)').remove();
                           var classId = $(this).val();
                           
                           $.ajax({
                                  url: apiUrl + "/makes/getall/?callback=?",
                                  cache: false,
                                  type: "GET",
                                  data: {
                                  companyId: companyId,
                                  classId: classId
                                  },
                                  beforeSend: setHeader
                                  }).done(function (classData) {
                                          $.each(classData, function (i, item) {
                                                 $("#SearchMake").append("<option value='" + item.MKCODE + "'>" + item.MKDESC + "</option>");
                                                 });
                                          });
                           });
  
  $("#AdvSearchForm").submit(function(){
                             AdvancedSearch();
                             return false;
                             });
  });

function PopulateAdvancedSearchFields(){
    $("#SearchType").children('option:not(:first)').remove();
    $("#SearchClass").children('option:not(:first)').remove();
    $("#SearchDivision").children('option:not(:first)').remove();
    $("#SearchMake").children('option:not(:first)').remove();
    
    $.ajax({
           url: apiUrl + "/types/getall/?callback=?",
           cache: false,
           type: "GET",
           data: {
           companyId: companyId
           },
           beforeSend: setHeader
           }).done(
                   function (typeData) {
                   $.each(typeData, function (i, item) {
                          $("#SearchType").append("<option value='" + item.TYPEID + "'>" + item.TYDESC + "</option>");
                          });
                   });
    
    $.ajax({
           url: apiUrl + "/divisions/getall/?callback=?",
           cache: false,
           type: "GET",
           data: {
           companyId: companyId
           },
           beforeSend: setHeader
           }).done(
                   function (typeData) {
                   $.each(typeData, function (i, item) {
                          $("#SearchDivision").append("<option value='" + item.DMDVID + "'>" + item.DMNAME + "</option>");
                          });
                   });
 
    searchFieldsInitialized = true;
}

function PrepSearchResults() {
    $(".page-header-internal h1").html("Search Results");
    $("#ListingsTable").remove();
     $("<table class='tablesorter tablesorter-default' id='ListingsTable' style='width:100%;overflow:auto;'><thead></thead><tbody></tbody></table>").appendTo(".tablesorter-scroller-table");
    $("#ListingsTable thead").html("<tr><th style='width:18px;'></th><th>Year</th><th>Make</th><th>Model</th><th>Mileage</th><th>Sale City</th><th>State</th><th>Sale Price</th><th>Sale Date</th></tr>");
    
    $("#ItemList").hide();
    $("#AdvSearch").hide();
    $(".rightLoading").show();
}

function Search() {
    PrepSearchResults();
    
    $.ajax({
           url: apiUrl + "/equipment/quicksearch/?callback=?",
           cache: false,
           type: "GET",
           data: {
           companyId: companyId,
           searchTerm: $("#sw_SearchText").val()
           },
           beforeSend: setHeader
           }).done(
                   function (data) {
                   console.log(data);
                   PopulateSearchResults(data);
                   })
    .fail(
          function(data){
          console.log(data);
          });
    return false;
}

function AdvancedSearch() {
    PrepSearchResults();
    
    var json = $("#AdvSearchForm").serializeObject();
    
    $.ajax({
           type: "POST",
           cache: false,
           url: apiUrl + "/equipment/advancedsearch?CompanyId=" + companyId,
           dataType: "json",
           contentType: 'application/json; charset=utf-8',
           data: JSON.stringify(json),
           beforeSend: setHeader
           })
    .done(function (data) {
          PopulateSearchResults(data);
          })
    .fail(function(data){
          console.log(data);
          });
    
    return false;
}

function PopulateSearchResults(workData) {
    retrocycle(workData);
    var trClass = "";
    $.each(workData, function () {
           if (trClass == "odd") { trClass = ""; } else { trClass = "odd"; }
           var i = this;
           
           var editItem = "<a onclick='EditItem(" +
           this.TYPEID + ", " +
           this.CLASSID + ", \"" +
           this.CLDESC + "\", " +
           this.EQUIPMENTID + ", " +
           this.TRCSGN	 + ", " +
           this.TRCNTC + ", " +
           this.TRCRDN + ", " +
           this.TRCRDC + ", " +
           this.TRBYR_ + ", " +
           this.TRBCNT + ")' class='edit-icon' data-id='" + this.EQUIPMENTID + "'>edit</a>";
           
           var tr = "<tr class='" + trClass + "'><td style='width:34px;'><a class='view-icon search-details' data-id='" + this.EQUIPMENTID + "' data-class='" + this.CLASSID + "'></a></td>";
           
           tr += "<td>" + this.TRYEAR + "</td><td>" + this.TRMAKE + "</td><td>" + this.TRMODL + "</td><td>" + this.TRODMT + "</td><td>" + this.SACITY + "</td><td>" + this.SAST + "</td><td>" + this.TRPRCE + "</td><td>" + this.SASLDT + "</td></tr>";
           
           $(tr).appendTo("#ListingsTable tbody");
           });
    
    $(".rightLoading").hide();
    $("#ItemList").show();
    $(".edit-button").hide();
    
    $("#ListingsTable").bind("tablesorter-initialized", function (e, table) {
                             $(".tablesorter-scroller-table").css("width", $("#ListingsTable").outerWidth());
                             $("table.tablesorter thead").html($("#ListingsTable thead").html());
                             
                             $.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()-4);
                                    });
                             
                             });

    
    $("#ListingsTable").tablesorter({
                                    theme: 'default',
                                    
                                    // hidden filter input/selects will resize the columns, so try to minimize the change
                                    widthFixed: false,
                                    
                                    // initialize zebra striping and filter widgets
                                    //widgets: ["zebra", "filter", "saveSort", "scroller"],
                                    widgets: ["zebra", "filter", "scroller"],
                                    
                                    headers: { 0: { sorter: false, filter: false} },
                                    widgetOptions: {
                                    
                                    // If there are child rows in the table (rows with class name from "cssChildRow" option)
                                    // and this option is true and a match is found anywhere in the child row, then it will make that row
                                    // visible; default is false
                                    filter_childRows: false,
                                    
                                    // if true, a filter will be added to the top of each table column;
                                    // disabled by using -> headers: { 1: { filter: false } } OR add class="filter-false"
                                    // if you set this to false, make sure you perform a search using the second method below
                                    filter_columnFilters: true,
                                    
                                    // css class applied to the table row containing the filters & the inputs within that row
                                    filter_cssFilter: 'tablesorter-filter',
                                    
                                    // add custom filter functions using this option
                                    // see the filter widget custom demo for more specifics on how to use this option
                                    filter_functions: null,
                                    
                                    // if true, filters are collapsed initially, but can be revealed by hovering over the grey bar immediately
                                    // below the header row. Additionally, tabbing through the document will open the filter row when an input gets focus
                                    filter_hideFilters: false,
                                    
                                    // Set this option to false to make the searches case sensitive
                                    filter_ignoreCase: true,
                                    
                                    // jQuery selector string of an element used to reset the filters
                                    filter_reset: 'button.reset',
                                    
                                    // Delay in milliseconds before the filter widget starts searching; This option prevents searching for
                                    // every character while typing and should make searching large tables faster.
                                    filter_searchDelay: 300,
                                    
                                    // Set this option to true to use the filter to find text from the start of the column
                                    // So typing in "a" will find "albert" but not "frank", both have a's; default is false
                                    filter_startsWith: false,
                                    
                                    // Filter using parsed content for ALL columns
                                    // be careful on using this on date columns as the date is parsed and stored as time in seconds
                                    filter_useParsedData: false,
                                    //save filters
                                    filter_saveFilters: false,
                                    
                                    scroller_barWidth: 0,
                                    scroller_height: 590
                                    
                                    
                                    }
                                    });
}


// =================================================================================================
//                                       VIEWS SEARCH
// =================================================================================================

$(function () {
  
  // Expand/Collapse Accordions
  $("#viewsSearch").on("click", ".view-accordion-heading", function () {
                                                  $(this).toggleClass("active");
                                                  $(this).find(".view-accordion-heading").removeClass("active");
                                                  $(this).next().slideToggle(300);
                                                  });
  
  // Create Details Dialog
  $("#ViewSearchDetails, #CustomerDetails").dialog({
                                 modal: true,
                                 autoOpen: false,
                                 width: 750,
                                 resizable: false
                                 });
  
  // Click Event to Open Dialog
  $("#viewsSearch, #ItemList").on("click", ".view-icon", function () {
                       console.log("Equipment ID: " + $(this).data("id"));
                       
                       $.ajax({
                              url: apiUrl + "/equipment/getresultitem/?callback=?",
                              cache: false,
                              type: "GET",
                              data: {
                              companyId: companyId,
                              equipmentId: $(this).data("id"),
                              },
                              beforeSend: setHeader
                              }).done(
                                      function (data) {
                                      var editItem = "EditItem(" +
                                      data.TYPEID + ", " +
                                      data.CLASSID + ", " +
                                      "\"" + data.CLDESC + "\", " +
                                      data.EQUIPMENTID + ", " +
                                      data.SASAL_ + ", " +
                                      data.TRCSGN + ", " +
                                      data.TRCNTC + ", " +
                                      data.TRCRDN + ", " +
                                      data.TRCRDC + ", " +
                                      data.TRBYR_ + ", " +
                                      data.TRBCNT + ")";

                                      $("#OpenEquipment").attr("onclick", editItem);
                                      $("#ViewSearchDetails .item-mainphoto").attr("src", rootUrl + "/images/nophoto.jpg");
                                      $("#ViewSearchDetails .item-header").html(data.SALELOCATION + " - <span style='color:#43689d;'>$" + (data.TRPRCE).formatMoney() + "</span>");
                                      $("#ViewSearchDetails .item-saledate").html("Sale Date: " + data.TRSLDT);
                                      $("#ViewSearchDetails .item-description").html(data.TRDESCR);
                                      $("#ViewSearchDetails").dialog('option', 'title', data.TRYEAR + " " + data.MKDESC.trim() + " " + data.TRMODL.trim());
                                      
                                      $("#ViewSearchDetails").dialog("open");
                                      
                                      $.ajax({
                                             url: apiUrl + "/files/getall/?callback=?",
                                             cache: false,
                                             type: "GET",
                                             data: {
                                             companyId: companyId,
                                             classId: $(this).data("class"),
                                             equipmentId: $(this).data("id")
                                             },
                                             beforeSend: setHeader
                                             }).done(
                                                     function (data) {
                                                     $.each(data, function (i) {
                                                            if (this.ThumbUrl != undefined) {
                                                            $("#ViewSearchDetails .item-mainphoto").attr("src", apiUrl + "/files/get/" + this.UPLOADID + "?CompanyId=" + companyId);
                                                            }
                                                            return i == 0;
                                                            });
                                                     }).fail(function(data){
                                                             console.log(data);
                                                             });

                                      }).fail(function(data){
                                              console.log(data);
                                              });
                       
                       });
  
  // Click Event to Open Share Dialog
  $("#ViewSearchDetails .save-button").click(function () {
                                             $("#ShareEquipment").dialog("open");
                                             $("#ViewSearchDetails").dialog("close");
                                             });
  
  $(".footer-left li a").click(function () {
                               $(".view-search-list, #viewsSearch").hide();
                               });
  
  // Show Views Search
  $("#views-search").click(function () {
                                  $(".view-search-list, #viewsSearch").show();
                                  $(".queues-list, #accountInfo, #ClassList, #ItemList, #AdvSearch, #InfoTab").hide();
                                  });
  
  $("#viewSearchList").on("click", ".searchListItem", function(){
                          $(".page-header-internal h1").html($(this).html());
                          $("#viewsSearchContainer").html("");
                          
                          $("#ClassList, #ItemList, #InfoTab, #AdvSearch, #customerSearch, #viewsSearch").hide();
                          
                          var view = $(this).data("view");
                          
                          if(view=="Advanced"){
                          if (!searchFieldsInitialized){
                          PopulateAdvancedSearchFields();
                          }
                          $("#AdvSearch").show();
                          }else if(view=="Seller"){
                          $("#customerSearch").show();
                          }else{
                          $("#viewsSearch").show();

                          var current = searchViewPaths.filter(function(x){
                                                               return (x[0] == view && x[1] == 'root');
                                                               })[0];
                          
                          var criteria = '{}';
                          
                          $.ajax({
                                 url: apiUrl + "/equipment/viewsearch/?CompanyId=" + companyId + "&FilterBy=" + view,
                                 cache: false,
                                 type: "POST",
                                 data: {
                                 criteria: criteria
                                 },
                                 beforeSend: setHeader
                                 }).done(function(data){
                                         $.each(data, function () {
                                                $("<div class='view-accordion' data-view='" + view + "' data-next='" + current[2] + "' data-field='" + current[3] + "' data-id='" + this.key + "'><div class='view-accordion-heading'><span></span>" + this.description.trim() + " (" + this.count + ") $" + (this.avgprice).formatMoney() + "</div><div class='view-accordion-content'></div></div>").appendTo($("#viewsSearchContainer"));
                                                });
                                         
                                         $heading.addClass("loaded");
                                         
                                         }).fail(function(data){
                                                 console.log(data);
                                                 });
                          }
                          });
  
  
  $("#viewsSearchContainer").on("click", ".view-accordion-heading", function(){
                                var $this = $(this);
                                var view = $this.parent().data("view");
                                var next = $this.parent().data("next");
                                
                                if(!$this.hasClass("loaded")){
                                $this.next().html("");

                                var criteria = '{';
                                $this.parents().each(function(){
                                                     if ($(this).hasClass("view-accordion")){
                                                     criteria += '"' + $(this).data('field') + '":"' + $(this).data('id') + '",';
                                                     }
                                                     });
                                criteria = criteria.substring(0, criteria.length - 1) + '}';
                                
                                var current = searchViewPaths.filter(function(x){
                                                                     return (x[0] == view && x[1] == next);
                                                                     })[0];
                                
                                if (next != "Results"){
                                $.ajax({
                                       url: apiUrl + "/equipment/viewsearch/?CompanyId=" + companyId + "&FilterBy=" + next,
                                       cache: false,
                                       type: "POST",
                                       data: {
                                       criteria: criteria
                                       },
                                       beforeSend: setHeader
                                       }).done(function(data){
                                               $.each(data, function () {
                                                      var r = "<div class='view-accordion' data-view='" + view + "' data-next='" + current[2] + "' data-field='" + current[3] + "' data-id='" + this.key + "'><div class='view-accordion-heading'><span></span>" + this.description.trim() + " (" + this.count + ") $" + (this.avgprice).formatMoney() + "</div><div class='view-accordion-content'></div></div>";
                                                      
                                                      $(r).appendTo($this.next());
                                                      });
                                               
                                               $this.addClass("loaded");

                                               }).fail(function(data){
                                                       console.log(data);
                                                       });
                                } else {
                                $.ajax({
                                       url: apiUrl + "/equipment/getsearchresults/?CompanyId=" + companyId + "&FilterBy=" + next,
                                       cache: false,
                                       type: "POST",
                                       data: {
                                       criteria: criteria
                                       },
                                       beforeSend: setHeader
                                       }).done(function (equipment) {
                                               var rows = "";
                                               $.each(equipment, function () {
                                                      console.log(this);
                                                      rows = rows + "<tr><td><a class='view-icon search-details' data-id='" + this.EQUIPMENTID + "' data-class='" + this.CLASSID + "'></a></td>" +
                                                      "<td>" + this.TRSLDT + "</td>" +
                                                      "<td>" + this.SALELOCATION + "</td>" +
                                                      "<td>$" + (this.TRPRCE).formatMoney() + "</td>" +
                                                      "<td>" + this.TRCOND + "</td>" +
                                                      "</tr>";
                                                      });
                                               
                                               var r = "<table class='classes-table tablesorter tablesorter-default' style='width:100%;'><tr><th></th><th>Sale Date</th><th>Location</th><th>Price</th><th>Condition</th></tr>" +
                                               rows + "</table>";
                                               
                                               $(r).appendTo($this.next());
                                               //$(r).tablesorter();
                                               
                                               $heading.addClass("loaded");
                                               }).fail(function(data){
                                                       console.log(data);
                                                       });
                                }
                                }
                                });
});
