Advertisement
Guest User

Untitled

a guest
Sep 15th, 2014
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /****************************************************************************************************************
  2. *
  3. *
  4. *                                           USED CAR SEARCH in Angular
  5. *                                           =========================
  6. *                                           @requires: jquery
  7. *                                           @requires: lodash
  8. *
  9. *****************************************************************************************************************/
  10.  
  11. // Initialise App
  12. var usedCarSearchApp = angular.module('usedCarSearchApp', ['carDataModule', 'directivesModule', 'pasvaz.bindonce']);
  13.  
  14. /*********************************************************
  15.  *
  16.  *      Controller
  17.  *
  18.  ********************************************************/
  19. usedCarSearchApp.controller('usedCarCtrl', function ($scope, $filter, $timeout, $interval, CarData, filterFilter) {
  20.     $scope.loadingCars = 0;
  21.     /**
  22.      *  Store URL
  23.      */
  24.     var url = window.location.pathname.split("/");
  25.     url.shift();
  26.     $scope.url = {
  27.         fullpath: window.location.pathname,
  28.         s1: url[0],
  29.         s2: url[1],
  30.         s3: url[2],
  31.         s4: url[3],
  32.         s5: url[4],
  33.     }
  34.  
  35.     if( $scope.url.s3 !== undefined){
  36.         var text = $scope.url.s2.split("-");
  37.         $scope.keyword = true;
  38.         $scope.fullTextSearch = text.join(" ");
  39.     }
  40.  
  41.     /**
  42.      *  Fetch cars from the database and
  43.      *  then fill cars, filterOptions,
  44.      *  price dropdowns and mileage dropdowns
  45.      */
  46.     CarData.loadCars().then(function(cars){
  47.         cars.sort(function(a,b){
  48.             //return a.price - b.price;
  49.             var first, second;
  50.             first = a.alt_price ? Math.min(+a.alt_price, +a.price) : +a.price;
  51.             second = b.alt_price ? Math.min(+b.alt_price, +b.price) : +b.price;
  52.             return first - second;
  53.         });
  54.        
  55.  
  56.         cars.map(function(x){
  57.             //console.log(x.make +  " " + x.model +" " + x.price + " " + x.alt_price );
  58.             //console.log( typeof(x.price) );
  59.             //console.log($.type(x));
  60.         });
  61.  
  62.         // First, add 20 cars to length
  63.         //var firstSet = cars.slice(0,100);
  64.         //var rest = cars.slice(101,cars.length);
  65.        
  66.         $scope.cars = cars;
  67.         $scope.loadingCars = 1;
  68.  
  69.         if($scope.keyword){
  70.             var filtered = $filter('search')(cars, $scope.fullTextSearch);
  71.             console.log("Showing Filtered Count_____________________");
  72.             if(filtered.length == 0){
  73.                 $scope.fullTextSearch = "";
  74.             }
  75.            
  76.            
  77.            
  78.            
  79.            
  80.            
  81.             /*filtered.map(function(a){
  82.                 console.log(a.make + " " + a.model);
  83.             });*/
  84.         }
  85.        
  86.         $scope.filterOptions = CarData.filters;
  87.  
  88.         fillPriceDropdowns(cars);
  89.         fillMileageDropdowns(cars);
  90.  
  91.         fillYearDropdown(cars);
  92.         fillMpgDropdown(cars);
  93.  
  94.         fillBodyTypes(cars);
  95.         fillEngineSizes(cars);
  96.        
  97.          /*$timeout(function () {
  98.             $scope.cars = $scope.cars.concat(rest);
  99.          }, 2000);*/
  100.        
  101.     }).then(function(){
  102.         CarData.getTaxInfo().then(function(tax){
  103.             $scope.taxTable = tax;
  104.             fillTaxDropdown(tax);
  105.         }).then(function(){
  106.             CarData.getVehicleColours().then(function(colours){
  107.                 //console.log(colours);
  108.                 $scope.coloursTable = colours;
  109.                 fillColoursDropdown(colours);
  110.             })
  111.         })
  112.     })
  113.  
  114.     /**
  115.      *  Fill Price Select Boxes
  116.      */
  117.     function fillPriceDropdowns(cars){
  118.         // Fill an array of all prices
  119.         var prices = cars.map(function(x){ return x.price });
  120.  
  121.         // Get min and max prices
  122.         var minPrice = Math.min.apply(null, prices);
  123.         var maxPrice = Math.max.apply(null, prices);
  124.  
  125.         // Amount to round by
  126.         var rounding = 1000;
  127.  
  128.         var minArray = [];
  129.         var maxArray = [];
  130.  
  131.         // Get start and end for max dropdown
  132.         var maxStart    = rounding * Math.ceil(minPrice / rounding);
  133.         var maxEnd      = rounding * Math.ceil(maxPrice / rounding);
  134.  
  135.         while(maxStart <= maxEnd)
  136.         {
  137.             maxArray.push(maxStart);
  138.             maxStart += 1000;
  139.         }
  140.  
  141.         // Get start and end for min dropdown
  142.         var minStart = 0;
  143.         var minEnd = rounding * Math.floor(maxPrice / rounding);
  144.  
  145.         while(minStart <= minEnd)
  146.         {
  147.             minArray.push(minStart);
  148.             minStart += 1000;
  149.         }
  150.  
  151.         $scope.filterOptions.minPrice = minArray;
  152.         $scope.filterOptions.maxPrice = maxArray;
  153.     }
  154.  
  155.     /**
  156.      *  Fill Mileage Select Boxes
  157.      */
  158.     function fillMileageDropdowns(cars){
  159.         // Fill an array of all prices
  160.         var mileages = cars.map(function(x){ return x.mileage });
  161.  
  162.         // Get min and max prices
  163.         var minMileage = Math.min.apply(null, mileages);
  164.         var maxMileage = Math.max.apply(null, mileages);
  165.  
  166.         // Amount to round by
  167.         var rounding = 10000;
  168.  
  169.         var minStart = 0;
  170.         var minEnd = rounding * Math.floor(maxMileage / rounding);
  171.  
  172.         var maxStart = 10000;
  173.         var maxEnd = rounding * Math.ceil(maxMileage / rounding);
  174.        
  175.         var minArray = [];
  176.         var maxArray = [];
  177.  
  178.         while(minStart <= minEnd)
  179.         {
  180.             minArray.push(minStart);
  181.             minStart += 10000;
  182.         }
  183.  
  184.         while(maxStart <= maxEnd)
  185.         {
  186.             maxArray.push(maxStart);
  187.             maxStart += 10000;
  188.         }
  189.        
  190.         var minMileageContainer = [];
  191.         _.each(minArray, function(item){
  192.             var obj = {
  193.                 name: number_format(item) + " Min Miles",
  194.                 value: item
  195.             }
  196.             minMileageContainer.push(obj);
  197.         });
  198.        
  199.         var maxMileageContainer = [];
  200.         _.each(maxArray, function(item){
  201.             var obj = {
  202.                 name: number_format(item) + " Max Miles",
  203.                 value: item
  204.             }
  205.             maxMileageContainer.push(obj);
  206.         });
  207.  
  208.        
  209.         $scope.filterOptions.minMileage = minMileageContainer;
  210.         $scope.filterOptions.maxMileage = maxMileageContainer;
  211.     }
  212.  
  213.     /**
  214.      *  Fill Year Select Box
  215.      */
  216.     function fillYearDropdown(cars){
  217.         var years = cars.map(function(x){ return x.year_of_man });
  218.        
  219.         var unique = _.unique(years);
  220.        
  221.         unique = unique.sort(function(a,b){
  222.             return b-a;
  223.         })
  224.  
  225.         var len = unique.map(function(x){
  226.             return new Date().getFullYear() - x;
  227.         });
  228.  
  229.        
  230.         if(len[0] === 0) { len.shift(); }
  231.  
  232.         var arrObjs = len.map(function(l){
  233.             return {
  234.                 label: "Up To " + l + " Year",
  235.                 val: l
  236.             }
  237.         })
  238.         //console.log(arrObjs);
  239.         $scope.filterOptions.age = arrObjs;
  240.     }
  241.  
  242.     /**
  243.      *  Fill MPG Select Box
  244.      */
  245.     function fillMpgDropdown(cars){
  246.         // Get array of mpg from each car
  247.         var mpgs = cars.map(function(x){ return x.mpg; });
  248.  
  249.         // Get unique only mpgs
  250.         var unique = _.unique(mpgs);
  251.  
  252.         // Strip zero from the list
  253.         unique = _.pull(unique,0);
  254.  
  255.         // Set rounding amount
  256.         var rounding = 10;
  257.  
  258.         // Get minimum mpg value
  259.         var minMpg = Math.min.apply(0,unique);
  260.        
  261.         // Get minimum mpg for the dropdown list of mpgs
  262.         var mpgListMin = rounding * Math.floor(minMpg / rounding);
  263.         //console.log(minMpg);
  264.         //console.log(mpgListMin);
  265.  
  266.         // Get maximum mpg value
  267.         var maxMpg = Math.max.apply(0,unique);
  268.         //console.log("Max mpg is " + maxMpg);
  269.  
  270.         // Get maximum mpg for the dropdown list of mpgs
  271.         var mpgListMax = rounding * Math.floor(maxMpg / rounding);
  272.  
  273.         // Dropdown List
  274.         var out = [];
  275.  
  276.         // Generate dropdown list values
  277.         while(mpgListMin <= mpgListMax)
  278.         {
  279.             out.push(mpgListMin);
  280.             mpgListMin += 10;
  281.         }
  282.  
  283.         // Create array of objects that have label and val
  284.         var arrObjs = out.map(function(x){
  285.             return {
  286.                 label: "More than " + x + " mpg",
  287.                 val: x
  288.             }
  289.         })
  290.  
  291.         $scope.filterOptions.mpg = arrObjs;
  292.     }
  293.  
  294.     /**
  295.      *  Fill Body Types (Unused)
  296.      */
  297.     function fillBodyTypes(cars){
  298.         // Get array of bodytypes from each car
  299.         var bodytypes = cars.map(function(x){ return x.body_types; });
  300.  
  301.         // Get unique only mpgs
  302.         var unique = _.unique(bodytypes);
  303.  
  304.         var arr = [];
  305.  
  306.         _.each(unique, function(item){
  307.             var name = "";
  308.  
  309.             switch(parseInt(item,10)){
  310.                 case 0:
  311.                     name = "Hatchback";
  312.                 break;
  313.  
  314.                 case 1:
  315.                     name = "Estate";
  316.                 break;
  317.  
  318.                 case 2:
  319.                     name = "4x4";
  320.                 break;
  321.  
  322.                 case 3:
  323.                     name = "MPV";
  324.                 break;
  325.  
  326.                 case 4:
  327.                     name = "SUV";
  328.                 break;
  329.  
  330.                 case 5:
  331.                     name = "Saloon";
  332.                 break;
  333.  
  334.                 case 6:
  335.                     name = "Coupe";
  336.                 break;
  337.  
  338.                 case 7:
  339.                     name = "Convertible";
  340.                 break;
  341.  
  342.                 case 8:
  343.                     name = "Sports";
  344.                 break;
  345.  
  346.                 default:
  347.                     name = "";
  348.                 break;
  349.             }
  350.  
  351.             var obj = {
  352.                 name: name,
  353.                 value: item
  354.             }
  355.  
  356.             arr.push(obj);
  357.         })
  358.  
  359.         //console.log(arr);
  360.     }
  361.  
  362.     /**
  363.      *  Fill Engine Sizes Dropdown
  364.      */
  365.     function fillEngineSizes(cars){
  366.         var dropdowns = [
  367.             {
  368.                 name: "Less Than 1L",
  369.                 value: 1
  370.             },
  371.             {
  372.                 name: "1L - 1.3L",
  373.                 value: 2
  374.             },
  375.             {
  376.                 name: "1.4L - 1.6L",
  377.                 value: 3
  378.             },
  379.             {
  380.                 name: "1.7L - 1.9L",
  381.                 value: 4
  382.             },
  383.             {
  384.                 name: "2L - 2.5L",
  385.                 value: 5
  386.             },
  387.             {
  388.                 name: "2.6L+",
  389.                 value: 6
  390.             },
  391.         ];
  392.  
  393.         $scope.filterOptions.engineSizes = dropdowns;
  394.     }
  395.  
  396.     /**
  397.      *  Fill Tax Dropdown
  398.      */
  399.     function fillTaxDropdown(tax){
  400.         var ret = [];
  401.         tax.map(function(t){
  402.             if(t.id < 14){
  403.                 var a = {
  404.                     name: t.standard_12m,
  405.                     value: t.band
  406.                 };
  407.  
  408.                 ret.push(a);
  409.             }
  410.         });
  411.         $scope.filterOptions.tax = ret;
  412.     }
  413.  
  414.     /**
  415.      *  Fill Colours Dropdown
  416.      */
  417.     function fillColoursDropdown(colours){
  418.         var ret = [];
  419.  
  420.         colours.map(function(c){
  421.             var a = {
  422.                 name: c.name,
  423.                 value: c.bit
  424.             };
  425.  
  426.  
  427.             ret.push(a);
  428.         });
  429.  
  430.         $scope.filterOptions.colours = ret;
  431.     }
  432.    
  433.     /**
  434.      * On click of the "Begin Search" button, lookup postcode in database,
  435.      * if we do not have it, then lookup with Google Maps API
  436.      */
  437.     $scope.lookupPostcode = function(postcode){
  438.  
  439.         // Initialise location
  440.         var location = {};
  441.  
  442.         // Use Data Factory to check for postcode to fetch lat/long information
  443.         CarData.checkDatabaseForPostcode(postcode).then(function(r){
  444.             // If not in the database
  445.             if(r == "false"){
  446.                 fetchLocationFromGoogle(postcode);
  447.             }else{ // Found postcode in database
  448.  
  449.                 // Add location to scope
  450.                 addLocationToScope(postcode, r.lat, r.long);
  451.                
  452.                 // Set scope logic to say found postcode, from Database
  453.                 $scope.postcodeFound = true;
  454.                 $scope.postcodeViaDB = true;
  455.                 $scope.postcodeViaGoogle = false;
  456.                 calculateDistances(postcode, r.lat, r.long);
  457.                 return;
  458.             }  
  459.         })
  460.     };
  461.  
  462.     /**
  463.      *  Fetch Location Details From Google
  464.      */
  465.     function fetchLocationFromGoogle(postcode){
  466.         geocoder.geocode( {'address':postcode}, function(results,status){
  467.             if(status == google.maps.GeocoderStatus.OK){
  468.                 // Get Location Information from the Google Maps API response
  469.                 var lat = results[0].geometry.location.lat();
  470.                 var lng = results[0].geometry.location.lng();
  471.                 //console.log(lat + " " + lng);;
  472.                 // Store location in the database
  473.                 storeLocation(postcode,lat, lng );
  474.  
  475.                 // Add location to scope
  476.                 addLocationToScope(postcode, lat, lng);
  477.    
  478.                 // Set scope logic to say found postcode, from Google
  479.                 $scope.postcodeFound = true;
  480.                 $scope.postcodeViaGoogle = true;
  481.                 $scope.postcodeViaDB = false;
  482.                 calculateDistances(postcode, lat, lng);
  483.             }else{
  484.                 alert("Geocode was not successful for the following reason: " + status);
  485.                 $scope.postcodeFound = false;
  486.             }
  487.         });
  488.     }
  489.  
  490.     /** Helper Function to add location details to the scope **/
  491.     function addLocationToScope(postcode, lat, long){
  492.         $scope.user = {
  493.             location: {
  494.                 postcode:postcode,
  495.                 lat:lat,
  496.                 lng:long
  497.             }
  498.         }
  499.     }
  500.  
  501.     function calculateDistances(postcode, lat, lng){
  502.         lat = parseFloat(lat);
  503.         lng = parseFloat(lng);
  504.         var locations = _.unique($scope.cars, 'name');
  505.         //console.log(locations);
  506.        
  507.         //var distances = [];
  508.  
  509.         /*locations.forEach(function(i){
  510.             var dealerLat = i.latitude;
  511.             var dealerLong = i.longitude;
  512.             var dealerLocationObject = new LatLon(dealerLat,dealerLong);
  513.            
  514.             var customerLocationObject = new LatLon(lat,lng);
  515.             var distance = dealerLocationObject.distanceTo(customerLocationObject);
  516.             //console.log(distance);
  517.             var item = {}; item[i.name] = distance;
  518.             distances.push(item);      
  519.         })*/
  520.        
  521.         /*var distances = locations.map(function(location){
  522.             var dealerLat = parseFloat(location.latitude);
  523.             var dealerLong = parseFloat(location.longitude);
  524.             var dealerLocationObject = new LatLon(dealerLat,dealerLong);
  525.            
  526.             var customerLocationObject = new LatLon(lat,lng);
  527.             var distance = dealerLocationObject.distanceTo(customerLocationObject);
  528.  
  529.             var item = {};
  530.             item[location.name] = distance;
  531.             return item;   
  532.         });*/
  533.        
  534.         var distances = locations.reduce(function(distances, location){
  535.             var dealerLat = parseFloat(location.latitude);
  536.             var dealerLong = parseFloat(location.longitude);
  537.             var dealerLocationObject = new LatLon(dealerLat,dealerLong);
  538.                
  539.             var customerLocationObject = new LatLon(lat,lng);
  540.             var distance = dealerLocationObject.distanceTo(customerLocationObject);
  541.             distance = distance * 0.62137;
  542.             distance = Math.round(distance);
  543.  
  544.             distances[location.name] = distance;
  545.  
  546.             return distances;
  547.  
  548.         }, {})
  549.  
  550.         $scope.cars.forEach(function(car){
  551.             car.distance = distances[car.name];
  552.             console.log(car.distance);
  553.         })
  554.  
  555.         var distanceSortObj = {id : 7, name : 'Distance Closest to Furthest' , "predicate" : "distance" };
  556.         $scope.sortOptions.stores.push( distanceSortObj );
  557.  
  558.         $scope.distances = distances;
  559.     }
  560.  
  561.     /**
  562.      * Store location in database
  563.      */
  564.     storeLocation = function(postcode, lat, long){
  565.         CarData.storeLocation(postcode, lat, long).then(function(r){
  566.             //return r;
  567.         })
  568.     }
  569.  
  570.     /**
  571.      *  Check Database for Postcode -> uses publically exposed method of the Data Factory
  572.      */
  573.     checkDatabaseForPostcode = function(postcode){
  574.         return CarData.checkDatabaseForPostcode(postcode);
  575.     }
  576.  
  577.     $scope.storeSearch = function(){
  578.         /*$scope.postcode;
  579.         $scope.filterItem.make;
  580.         $scope.filterItem.model;
  581.         $scope.fullTextSearch;
  582.  
  583.         $scope.filterItem.minPrice;
  584.         $scope.filterItem.maxPrice;
  585.  
  586.         $scope.filterItem.fuel_type;
  587.         $scope.filterItem.transmission;
  588.         $scope.filterItem.colour;
  589.  
  590.  
  591.         $scope.sortItem.store;
  592.  
  593.         $scope.filteredData.length;
  594. */
  595.         var filteredItems = [];
  596.         angular.forEach($scope.filteredData, function(val,key){
  597.             this.push(val.id);
  598.         }, filteredItems);
  599.     }
  600.  
  601.     /*$scope.$watchCollection('filterItem', function(newCollection, oldCollection){
  602.         console.log("Triggered WATCH");
  603.         $scope.$broadcast('Filter');
  604.     });*/
  605. /*$interval(function(){
  606.     $('.circle, .circle1').toggle();
  607. }, 1000, 2, true);*/
  608.  
  609.     $scope.change = function () {
  610.         $scope.$emit('change')
  611.     }
  612.    
  613.     $scope.$watch('filterItem', function() {
  614.         var isFirstCycle = false;
  615.         if($scope.filterCount == -1){
  616.             $scope.filterCount++;
  617.             isFirstCycle = true;
  618.         }
  619.         if(isFirstCycle === true) return false;
  620.  
  621.         storeSearch();
  622.     }, true); // end watch
  623.  
  624.    
  625.     $scope.runFullTextSearch = function(e){
  626.         if (e.keyCode == 13) {
  627.             $scope.fullTextSearch = $scope.fullTextSearchVal;
  628.             storeSearch();
  629.         }
  630.  
  631.         if(e.keyCode == 27){
  632.             $scope.fullTextSearch.$rollbackViewValue();
  633.         }
  634.     }
  635.  
  636.     $scope.storeSearch = function(){
  637.         $scope.fullTextSearch = $scope.fullTextSearchVal;
  638.         storeSearch();
  639.     }
  640.    
  641.     function storeSearch(){
  642.         $scope.$broadcast('Filter'); // triggers the Filter event to refresh the car images so they load without scroll
  643.         $timeout(function(){
  644.        
  645.             // Gets the filtered items into an array
  646.             if($scope.filteredData) var filteredItems = $scope.filteredData.map(function(x){ return x.id });
  647.            
  648.             var searchData = {
  649.                 filteredCars        : filteredItems,
  650.                 searchNumber        : $scope.filterCount,
  651.                 filterMake          : $scope.filterItem.make,
  652.                 filterModel         : $scope.filterItem.model,
  653.                 filterKeyword       : $scope.fullTextSearch,
  654.                 filterMinPrice      : $scope.filterItem.minPrice,
  655.                 filterMaxPrice      : $scope.filterItem.maxPrice,
  656.                 filterMinMileage    : $scope.filterItem.minMileage,
  657.                 filterMaxMileage    : $scope.filterItem.maxMileage,
  658.                 filterAge           : $scope.filterItem.age,
  659.                 filterMpg           : $scope.filterItem.mpg,
  660.                 filterFuelType      : $scope.filterItem.fuel_type,
  661.                 filterEngineSize    : $scope.filterItem.engine_size,
  662.                 filterTransmission  : $scope.filterItem.transmission,
  663.                 filterTax           : $scope.filterItem.tax,
  664.                 filterColour        : $scope.filterItem.colour,
  665.                 filterBodyType      : $scope.filterItem.body_type,
  666.                 filterDoors         : $scope.filterItem.doors,
  667.                 sortMethod          : $scope.sortItem.store,
  668.                 resultsCount        : filteredItems.length
  669.             };
  670.        
  671.             if($scope.user !== undefined){
  672.                 console.log($scope.user.postcode);
  673.                 searchData.postcode = $scope.user.location.postcode;
  674.             }
  675.  
  676.             // console.log(searchData);
  677.  
  678.             CarData.storeSearch(searchData).then(function(r){
  679.                 console.log(r);
  680.             })
  681.         }) // end timeout
  682.         $scope.filterCount++; // Increase filter count
  683.     }
  684.    
  685.     /**
  686.      *  Fetch Models when Make is selected
  687.      */
  688.     $scope.fetchModels = function(make){
  689.         //console.log(make);
  690.         if(make === null || make === undefined){
  691.             $scope.modelFilterOptions = { stores: [] };
  692.             $scope.filterItem.model = {};
  693.             return;
  694.         }
  695.        
  696.         CarData.fetchModels(make.name).then(function(models){
  697.        
  698.             $scope.modelFilterOptions = { stores: [] };
  699.  
  700.             angular.forEach(models, function(v){
  701.                 v.label = v.model;
  702.                 $scope.modelFilterOptions.stores.push(v);
  703.             })
  704.         })
  705.     }
  706.        
  707.     // Contains the sorting options
  708.     $scope.sortOptions = {
  709.         stores: [
  710.             {id : 1, name : 'Price Lowest to Highest', "predicate" : "price" },      
  711.             {id : 2, name : 'Price Highest to Lowest' , "predicate" : "-price"},
  712.             {id : 3, name : 'Mileage Lowest to Highest' , "predicate" : "mileage" },
  713.             {id : 4, name : 'Mileage Highest to Lowest' , "predicate" : "-mileage" },
  714.             {id : 5, name : 'MPG Highest to Lowest' , "predicate" : "-mpg" },
  715.             {id : 6, name : 'Age Newest to Oldest' , "predicate" : "-year_of_man" },
  716.            
  717.  
  718.         ]
  719.     };
  720.      
  721.     // Mapped to the model to sort
  722.     $scope.sortItem = {
  723.         store: $scope.sortOptions.stores[0]
  724.     };
  725.  
  726.     $scope.getMinPrice = function(priceData){
  727.         if(!priceData) { return;}
  728.         var prices = priceData.map(function(x){ return x.price });
  729.         var min = Math.min.apply(null, prices);
  730.         return min;
  731.     }
  732.  
  733.     $scope.getMaxPrice = function(priceData){
  734.         if(!priceData) { return;}
  735.         var prices = priceData.map(function(x){ return x.price });
  736.         var max = Math.max.apply(null, prices);
  737.         return max;
  738.     }
  739.  
  740.     $scope.minPriceFilter = function( min ){
  741.         return function(item){
  742.             if(!min)
  743.             {
  744.                 return true;
  745.             }
  746.             if(item.price >= min)
  747.             {
  748.                 return true;
  749.             }
  750.         }
  751.     }
  752.  
  753.     $scope.maxPriceFilter = function( max ){
  754.         return function(item){
  755.             if(!max)
  756.             {
  757.                 return true;
  758.             }
  759.             if(item.price <= max)
  760.             {
  761.                 return true;
  762.             }
  763.         }
  764.     }
  765.  
  766.     /**
  767.      *  When the min price is changed, the lowest max
  768.      *  price changes accordingly so that it is always
  769.      *  10000 higher than the min price dropdown.
  770.      */
  771.     $scope.maxPriceMinFilter = function ( maxPrice ){
  772.         return function(item){
  773.             if(!maxPrice)
  774.             {
  775.                 return true;
  776.             }
  777.             if(item > maxPrice)
  778.             {
  779.                 return true;
  780.             }
  781.         }
  782.     }
  783.  
  784.     $scope.minMileageFilter = function( min ){
  785.         return function(item){
  786.             if(!min)
  787.             {
  788.                 return true;
  789.             }
  790.             if(item.mileage >= min)
  791.             {
  792.                 return true;
  793.             }
  794.         }
  795.     }
  796.  
  797.     $scope.maxMileageFilter = function( max ){
  798.         return function(item){
  799.             if(!max)
  800.             {
  801.                 return true;
  802.             }
  803.             if(item.mileage <= max)
  804.             {
  805.                 return true;
  806.             }
  807.         }
  808.     }
  809.  
  810.     /**
  811.      *  When the min mileage is changed, the lowest
  812.      *  max mileage changes accordingly so that it is
  813.      *  always 10000 higher than the min mileage dropdown.
  814.      */
  815.     $scope.maxMileageMinFilter = function ( mil ){
  816.         return function(item){
  817.             if(!mil)
  818.             {
  819.                 return true;
  820.             }
  821.             if(item > mil)
  822.             {
  823.                 return true;
  824.             }
  825.         }
  826.     }
  827.  
  828.     $scope.ageFilter = function ( age ){
  829.         return function(item){
  830.             if(!age){
  831.                 return true;
  832.             }
  833.  
  834.             if(new Date().getFullYear() - item.year_of_man <= age){
  835.                 return true;
  836.             }
  837.         }
  838.     }
  839.  
  840.     $scope.mpgFilter = function ( mpg ){
  841.         return function(item){
  842.             if(!mpg){
  843.                 return true;
  844.             }
  845.  
  846.             if(item.mpg >= mpg){
  847.                 return true;
  848.             }
  849.         }
  850.     }
  851.  
  852.     $scope.engineSizeFilter = function ( option ){
  853.         return function(item){
  854.            
  855.             if( $.isEmptyObject(option) || option === null ){
  856.                 return true;
  857.             }
  858.  
  859.             item = item.engine_size;
  860.            
  861.             switch(option){
  862.                 case 1:
  863.                     return item < 1000;
  864.                     break;
  865.  
  866.                 case 2:
  867.                     return item >= 1000 && item <= 1349;
  868.                     break;
  869.  
  870.                 case 3:
  871.                     return item >= 1350 && item <= 1649;
  872.  
  873.                 case 4:
  874.                     return item >= 1650 && item <= 1949;
  875.  
  876.                 case 5:
  877.                     return item >= 1950 && item <= 2599;
  878.  
  879.                 case 6:
  880.                     return item >= 2600;
  881.  
  882.             } // end switch
  883.         }
  884.     }
  885.  
  886.     $scope.taxFilter = function( tax ){
  887.         return function(item){
  888.             if( !tax || tax === null ){
  889.                 return true;
  890.             }
  891.  
  892.             var row = _.where($scope.taxTable, { band: tax });
  893.             var r = row[0];
  894.             var min = r.value_low !== null ? +r.value_low : 0;
  895.             var max = r.value_high !== null ? +r.value_high : 9999;
  896.  
  897.            
  898.             if(item.co2 <= max){
  899.                 return true;
  900.             }
  901.         }
  902.     }  
  903.  
  904.     /* ########################### COUNT FUNCTIONS ############################ */
  905.     $scope.getFuelTypeCount = function(fuel_type){
  906.         var newData = $filter('filter')($scope.filteredData,{fuel_type: fuel_type});
  907.         return newData.length;
  908.     }
  909.  
  910.     $scope.getTransmissionCount = function(transmission){
  911.         var newData = $filter('filter')($scope.filteredData,{transmission: transmission});
  912.         return newData.length;
  913.     }  
  914.  
  915.     $scope.getColourCount = function(colour){
  916.         var colourNewData = $filter('filter')($scope.filteredData,{colour_categories: colour});
  917.         console.log(colourNewData);
  918.         return colourNewData.length;
  919.     }
  920.  
  921.     $scope.getDoorsCount = function(doors){
  922.         var newData = $filter('filter')($scope.filteredData,{doors: doors});
  923.         return newData.length;
  924.     }
  925.  
  926.     /**
  927.      *      Clear Filters
  928.      */
  929.     $scope.clearFuelTypes = function(){
  930.         $scope.filterItem.fuel_type = [];
  931.     }
  932.  
  933.     $scope.clearTransmissions = function(){
  934.         $scope.filterItem.transmission = [];
  935.     }
  936.  
  937.     $scope.clearColours = function(){
  938.         $scope.filterItem.colour = [];
  939.     }  
  940.  
  941.     $scope.clearDoors = function(){
  942.         $scope.filterItem.doors = [];
  943.     }  
  944.    
  945.     /**
  946.      *      Stores the items to be filtered by
  947.      */
  948.     $scope.filterItem = {fuel_type: [], colour: [], transmission: [], doors: [], body_type: [], engine_size: []};
  949.  
  950.     $scope.filterCount = -1;
  951.    
  952.     /************************* HELPERS **************************/
  953.     /**
  954.      * Same as PHP number_format
  955.      * Call the phpjs number_format function
  956.      */
  957.     $scope.number_format = function(num, decimals,dec_point, seperator){
  958.         return number_format(num, decimals, dec_point, seperator);
  959.     }
  960.  
  961.     /**
  962.      * Loop through array and convert all strings to int
  963.      * @param  {Array} arr Array of Strings
  964.      * @return {Array}     Array of Integers
  965.      */
  966.     $scope.arrayStrToNum = function(arr){
  967.         var numbers = arr.map(function(num){
  968.             return parseInt(num, 10);
  969.         });
  970.  
  971.         return numbers;
  972.     }
  973.  
  974.     /**
  975.      * Generate URL link to specific used car
  976.      * @param  {[type]} car [description]
  977.      * @return {[type]}     [description]
  978.      */
  979.     $scope.generateHref = function(car){
  980.         if(!car) { return; }
  981.         var link = "http://www.sandicliffe.co.uk/used-car/";
  982.  
  983.         var make = car.make.replace(" ","-");
  984.         make = make.toLowerCase();
  985.  
  986.         var model = car.model.replace(" ","-");
  987.         model = model.toLowerCase();
  988.  
  989.         var der = car.derivative;
  990.         der = der.replace(" ","-");
  991.         der = der.toLowerCase();
  992.        
  993.         var reg = car.reg_number;
  994.         reg = reg.replace(" ","-");
  995.         reg = reg.toLowerCase();
  996.  
  997.         link += make + "/" + model + "/" + der + "/" + reg;
  998.  
  999.         return link;
  1000.  
  1001.     }
  1002.  
  1003.     $scope.getDisplayPrice = function(item){
  1004.         // If no item or item price or item alt_price, return
  1005.         if(!item) { return; }
  1006.  
  1007.         var price = parseInt(item.price,10);
  1008.         var alt_price = parseInt(item.alt_price,10);
  1009.  
  1010.         // If alt_price is lower than price
  1011.         if(alt_price < price){
  1012.             // If alt_price is lower than 2
  1013.             if(alt_price < 2){
  1014.                 return number_format(price);
  1015.             }else{
  1016.                 return number_format(alt_price);
  1017.             }
  1018.         }else{
  1019.             return number_format(price);
  1020.         }
  1021.  
  1022.     }
  1023.  
  1024.     $scope.charLimit = function(str, n, useWordBoundary){
  1025.         var toLong = str.length>n,
  1026.         s_ = toLong ? str.substr(0,n-1) : str;
  1027.         s_ = useWordBoundary && toLong ? s_.substr(0,s_.lastIndexOf(' ')) : s_;
  1028.         return  toLong ? s_ + '...' : s_;
  1029.       };
  1030.  
  1031.  
  1032.    
  1033.     $scope.carFilter = function(){
  1034.         return function(item){
  1035.             // If MAKE is set
  1036.             if( $scope.filterItem.make ){
  1037.                 var filterMake = $scope.filterItem.make.name.toLowerCase();
  1038.                 if(filterMake != item.make.toLowerCase() ){
  1039.                     return false;
  1040.                 }
  1041.  
  1042.                 // If MODEL is set
  1043.                 if( $scope.filterItem.model ){
  1044.                     var filterModel = $scope.filterItem.model.model.toLowerCase();
  1045.                     if( filterModel != item.model.toLowerCase()){
  1046.                         return false;
  1047.                     }
  1048.                 }      
  1049.             }
  1050.  
  1051.             if( $scope.filterItem.body_type ){
  1052.                 var filterBodytypes = $scope.arrayStrToNum($scope.filterItem.body_type);
  1053.                 if( !_.contains(filterBodytypes, item.body_types) ){
  1054.                     return false;
  1055.                 }
  1056.                
  1057.             }
  1058.             return true;
  1059.         }
  1060.     }
  1061.  
  1062.     $scope.resetAllFilters = function(){
  1063.         $scope.filterItem = {fuel_type: [], colour: [], transmission: [], doors: [], body_type: [], engine_size: []};
  1064.     }
  1065. }); // end of controller
  1066.  
  1067. /**
  1068.  *      Directive: checkList
  1069.  */
  1070. usedCarSearchApp.directive('checkList', function() {
  1071.   return {
  1072.     scope: {
  1073.       list: '=checkList',
  1074.       value: '@'
  1075.     },
  1076.     link: function(scope, elem, attrs) {
  1077.       var handler = function(setup) {
  1078.         var checked = elem.prop('checked');
  1079.         var index = scope.list.indexOf(scope.value);
  1080.  
  1081.         if (checked && index == -1) {
  1082.           if (setup) elem.prop('checked', false);
  1083.           else scope.list.push(scope.value);
  1084.         } else if (!checked && index != -1) {
  1085.           if (setup) elem.prop('checked', true);
  1086.           else scope.list.splice(index, 1);
  1087.         }
  1088.       };
  1089.      
  1090.       var setupHandler = handler.bind(null, true);
  1091.       var changeHandler = handler.bind(null, false);
  1092.            
  1093.       elem.on('change', function() {
  1094.         scope.$apply(changeHandler);
  1095.       });
  1096.       scope.$watch('list', setupHandler, true);
  1097.     }
  1098.   };
  1099. });
  1100.  
  1101. /**
  1102.  *      Filter: multiFilter
  1103.  *
  1104.  *      @param {array/object}   collection      The original data set to be filtered
  1105.  *      @param {string}         property        The key to filter by
  1106.  *      @param {array}          values          The values to filter by
  1107.  *     
  1108.  */
  1109. usedCarSearchApp.filter('multiFilter',function(){
  1110.   return function(collection, property, values) {
  1111.  
  1112.     if(values.length === 0)
  1113.     {
  1114.       return collection;
  1115.     }
  1116.     return _.filter(collection, function(item) {
  1117.       return _.contains(values, item[property]);
  1118.     });
  1119.   }
  1120. })
  1121.  
  1122. // Unique filter - to extract unique values from a set of data
  1123. //https://github.com/angular-ui/ui-utils/blob/master/modules/unique/unique.js
  1124. usedCarSearchApp.filter('unique', ['$parse', function ($parse) {
  1125.  
  1126.   return function (items, filterOn) {
  1127.  
  1128.     if (filterOn === false) {
  1129.       return items;
  1130.     }
  1131.  
  1132.     if ((filterOn || angular.isUndefined(filterOn)) && angular.isArray(items)) {
  1133.       var newItems = [],
  1134.         get = angular.isString(filterOn) ? $parse(filterOn) : function (item) { return item; };
  1135.  
  1136.       var extractValueToCompare = function (item) {
  1137.         return angular.isObject(item) ? get(item) : item;
  1138.       };
  1139.  
  1140.       angular.forEach(items, function (item) {
  1141.         var isDuplicate = false;
  1142.  
  1143.         for (var i = 0; i < newItems.length; i++) {
  1144.           if (angular.equals(extractValueToCompare(newItems[i]), extractValueToCompare(item))) {
  1145.             isDuplicate = true;
  1146.             break;
  1147.           }
  1148.         }
  1149.         if (!isDuplicate) {
  1150.           newItems.push(item);
  1151.         }
  1152.  
  1153.       });
  1154.       items = newItems;
  1155.     }
  1156.     return items;
  1157.   };
  1158. }]);
  1159.  
  1160. usedCarSearchApp.filter('num', function() {
  1161.     return function(input) {
  1162.       return parseInt(input, 10);
  1163.     }
  1164. });
  1165.  
  1166. /**
  1167.  *      Filter: multiFilter for BODY TYPES
  1168.  *
  1169.  *      @param {array/object}   collection      The original data set to be filtered
  1170.  *      @param {string}         property        The key to filter by
  1171.  *      @param {array}          values          The values to filter by
  1172.  *     
  1173.  */
  1174. usedCarSearchApp.filter('multiFilterBodytype',function(){
  1175.   return function(collection, property, values) {
  1176.  
  1177.     if(values.length === 0) {
  1178.         return collection;
  1179.     }
  1180.  
  1181.     /*if( _.contains(values, "2") && !_.contains(values,"4") ) {
  1182.         values.push("4");
  1183.     }else {
  1184.         _.pull(values, "4");
  1185.     }*/
  1186.  
  1187.     return _.filter(collection, function(item) {
  1188.       return _.contains(values, item[property]);
  1189.     });
  1190.   }
  1191. })
  1192.  
  1193. /**
  1194.  *      Filter: multiFilter for ENGINE SIZES
  1195.  *
  1196.  *      @param {array/object}   collection      The original data set to be filtered
  1197.  *      @param {string}         property        The key to filter by
  1198.  *      @param {array}          values          The values to filter by
  1199.  *     
  1200.  */
  1201. usedCarSearchApp.filter('multiFilterEngineSize',function(){
  1202.   return function(collection, property, values) {
  1203.  
  1204.     if(values.length === 0) {
  1205.         return collection;
  1206.     }
  1207.  
  1208.     if( _.contains(values, "1") ) {
  1209.         if(item[property] < 1000) return true;
  1210.     }else if( _.contains(values, "2") ) {
  1211.        
  1212.     }else if( _.contains(values, "3") ) {
  1213.  
  1214.     }else if( _.contains(values, "4") ) {
  1215.  
  1216.     }else if( _.contains(values, "5") ) {
  1217.  
  1218.     }else if( _.contains(values, "6") ) {
  1219.  
  1220.     }
  1221.  
  1222.     /*return _.filter(collection, function(item) {
  1223.       return _.contains(values, item[property]);
  1224.     });*/
  1225.   }
  1226. });
  1227.  
  1228. usedCarSearchApp.filter('search', function($filter){
  1229.    return function(items, text){
  1230.       if (!text || text.length === 0)
  1231.         return items;
  1232.      
  1233.       // split search text on space
  1234.       var searchTerms = text.split(' ');
  1235.      
  1236.       // search for single terms.
  1237.       // this reduces the item list step by step
  1238.       searchTerms.forEach(function(term) {
  1239.         if (term && term.length)
  1240.           items = $filter('filter')(items, term);
  1241.       });
  1242.  
  1243.       return items
  1244.    };
  1245. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement