Advertisement
Guest User

Untitled

a guest
Jul 28th, 2015
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // NEW CAR SEARCH
  2.  
  3.  
  4. /* Bootstrapping Process
  5. ============================================================ */
  6. /**
  7.  * - Define the application
  8.  */
  9. var newCarSearchApp = angular.module('newCarSearchApp', ['slyCarouselModule', 'newCarSearchModule']);
  10.  
  11. /**
  12.  * - Generic AJAX function - replace with $http
  13.  */
  14. function ajaxCall(url, method, data, callback){
  15.     var obj = {'method':method, 'data':data};
  16.    
  17.     var request = $.ajax({
  18.         type:   "POST",
  19.         url:    url,
  20.         dataType: "json",
  21.         data:   {json: JSON.stringify(obj)}
  22.     });
  23.    
  24.     request.done(function(result){
  25.         if(typeof callback !== 'undefined'){
  26.             callback(result);
  27.         }
  28.     });
  29. }
  30.  
  31. /* Controller - newCarCtrl
  32. ============================================================ */
  33. newCarSearchApp.controller('newCarCtrl', function ($scope, $location, $timeout, $parse, Server) {
  34.  
  35.     /**
  36.      * - Get the URL, used among many places in the application
  37.      */
  38.     var url = window.location.pathname.split("/");
  39.     url.shift();
  40.  
  41.     // Create an array of the current URL - used in the template file for Sly
  42.     var urlArray = window.location.pathname.split("/");urlArray.shift();
  43.     $scope.currentUrl = urlArray;
  44.    
  45.     // Marker to check if ajax has completed
  46.     $scope.ajaxFinished = false;
  47.  
  48.     // Determine whether to show X section or not by using class -show or -hide
  49.     $scope.styles = { "refineVisibility": "show" }
  50.  
  51.     // Variable Initialising
  52.     $scope.body_types = [];
  53.     $scope.fuel_types = [];
  54.     $scope.transmissions = [];
  55.     $scope.doors = [];
  56.  
  57.     $scope.results = "";
  58.  
  59.     var urlMake = url[1];
  60.     var urlRange = url[2];
  61.  
  62.     // Fetch SEO description
  63.     var dataForSeoDescription = {
  64.         "make" : urlMake,
  65.         "range" : urlRange
  66.     };
  67.  
  68.     // ajaxCall("/newcar/ajax", "getSeoDescriptionText", dataForSeoDescription, parseSeoDescription);
  69.     Server.getSeoDescriptionText(dataForSeoDescription).then(parseSeoDescription);
  70.  
  71.     // Add SEO data to scope
  72.     function parseSeoDescription(r){
  73.         $scope.seoMainText = r.main_text;
  74.         $scope.seoSubText = r.sub_text;
  75.     }
  76.  
  77.     // Fetch Icons
  78.     var dataForOffers = {
  79.         "make" : urlMake,
  80.         "range" : urlRange
  81.     };
  82.  
  83.     //ajaxCall("/newcar/ajax", "getIcons", dataForIcons, parseIcons);
  84.     Server.getNewCarOffers(dataForOffers).then(parseOfferData);
  85.  
  86.     // Add 3x top offers data to scope
  87.     function parseOfferData(r){
  88.         //console.log(r);
  89.         $scope.offerData = r;
  90.     }
  91.  
  92.     Server.getMaxDealerDeposit(dataForOffers).then(function(r){
  93.         $scope.maxDealerDeposit = r;
  94.     });
  95.      
  96.     // Data to count special offers for this make and range
  97.     var dataForCountSpecialOffers = {
  98.         "make" : urlMake,
  99.         "range" : urlRange
  100.     };
  101.  
  102.     // Fetch count of special offers for this make and range from database
  103.     Server.countSpecialOffers(dataForCountSpecialOffers).then(function(r){
  104.         $scope.offersCount = r.offers;
  105.     });
  106.  
  107.     // Fetch count of special offers for this make and range from database
  108.     Server.countMotability(dataForCountSpecialOffers).then(function(r){
  109.         $scope.motabCount = r.motab;
  110.     });
  111.  
  112.     var dataForRangeMaxSavingAndImageSeries = {
  113.         "make" : urlMake,
  114.         "range" : urlRange
  115.     };
  116.  
  117.     Server.getRangeMaxSavingAndImageSeries(dataForRangeMaxSavingAndImageSeries).then(function(r){
  118.         $scope.rangeInfo = {
  119.             maxSaving: r.maxSaving.maxSaving,
  120.             imageSeries: r.imageSeries.image_series
  121.         };
  122.  
  123.         //console.log( $scope.rangeInfo );
  124.     });
  125.  
  126.     // Initial Options
  127.     $scope.options = {
  128.         "make": urlMake,
  129.         "model": urlRange,
  130.         "category": 0,
  131.         "series": ""
  132.     };
  133.  
  134.     // Data to be sent via AJAX to the server
  135.     var initialDataForSerieses = {
  136.         "make":$scope.options.make,
  137.         "model":$scope.options.model,
  138.         "type":$scope.options.category
  139.     };
  140.  
  141.     /************************************************
  142.      *
  143.      *      Fill Initial Series on Page Load
  144.      *
  145.      ***********************************************/
  146.     // Do Ajax to fetch initial "type 2" serieses
  147.     //ajaxCall("/newcar/ajax", "getSeries", initialDataForSerieses, fillSeries);
  148.     Server.getSeriesData(initialDataForSerieses).then(fillSeries);
  149.    
  150.     // fill series
  151.     function fillSeries(data){
  152.        
  153.         //console.log(data);
  154.         // Sort Data based on offer_price and basic_price
  155.         /*data.sort(function(a,b) {
  156.             return Math.min(parseInt(a.min,10), parseInt(a.offer_price,10)) - Math.min(parseInt(b.min,10), parseInt(b.offer_price,10));
  157.         });*/
  158.        
  159.         data.sort(function(a, b) {
  160.             var first, second;
  161.             first = a.offer_price ? Math.min(+a.offer_price, +a.min) : +a.min;
  162.             second = b.offer_price ? Math.min(+b.offer_price, +b.min) : +b.min;
  163.             return first - second;
  164.         }) 
  165.         // Hide below sections
  166.         $scope.styles.refineVisibility = "show";
  167.  
  168.         if ($scope.seriess === undefined) {
  169.             $scope.seriess = {
  170.                 data: data
  171.             }
  172.         } else {
  173.             $scope.seriess.data = data;
  174.         }
  175.  
  176.         // Mark AJAX completed
  177.         $scope.ajaxFinished = true;
  178.  
  179.         // Refresh the slider
  180.         $scope.refreshSlider();
  181.            
  182.         $scope.reloadSlider();
  183.  
  184.         // Set show results to false
  185.         $scope.showResults = true;
  186.            
  187.         //$scope.setActive();
  188.         //$scope.clickSeriesFn($scope.activeItem);             
  189.  
  190.         var seeMore = {
  191.             min: "",
  192.             series: "See More",
  193.             special_offer: "0",
  194.             seeMore: true
  195.         }
  196.  
  197.         if($scope.options.category == "1"){
  198.             $scope.seriess.data.push(seeMore);
  199.         }
  200.            
  201.         // });
  202.  
  203.         if($scope.activeCount !=="a"){
  204.             // Initialise URL (index 0 is empty, so start from 1 after the leading /)
  205.             var url = window.location.pathname.split("/");
  206.  
  207.             // Activates series if the series is in the URL
  208.             for (var i = $scope.seriess.data.length - 1; i >= 0; i--) {
  209.                 //console.log(scope.seriess[i]);
  210.                 if(url[5])
  211.                 {
  212.                     if(data[i].series.toUpperCase() == url[5].toUpperCase())
  213.                     {
  214.                         //console.log(i);
  215.                         //$timeout(function(){ $scope.activateSeries(i); });
  216.                         $scope.activateSeries(i);
  217.                     }
  218.                 }              
  219.             };
  220.         }
  221.        
  222.     };
  223.  
  224.     /******************************************************************************************
  225.      *
  226.      *      Buttons to change serieses between Normal, Personal Contract Hire, & Motability
  227.      *
  228.      *****************************************************************************************/
  229.     $scope.getNormalSeries = function() {
  230.         $(".new-car-top-button-clicked ").removeClass("new-car-top-button-clicked ");
  231.         $('.new-car-top-buttons').find('button').eq(0).addClass("new-car-top-button-clicked ");
  232.  
  233.         $scope.options.category = 0;
  234.         resetFilters();
  235.        
  236.         var normalSeriesData = { "make":urlMake, "model":urlRange, "type":$scope.options.category };
  237.         //ajaxCall("/newcar/ajax", "getSeries", normalSeriesData, fillSeries);
  238.         $scope.animateToSerieses();
  239.         Server.getSeriesData(normalSeriesData).then(fillSeries);
  240.     };
  241.  
  242.     $scope.getPersonalContractHireSeries = function() {
  243.         $(".new-car-top-button-clicked ").removeClass("new-car-top-button-clicked ");
  244.         $('.new-car-top-buttons').find('button').eq(1).addClass("new-car-top-button-clicked ");
  245.  
  246.         $scope.options.category = 1;
  247.         resetFilters();
  248.        
  249.         var personalContractHireSeriesData = { "make":urlMake, "model":urlRange, "type":$scope.options.category };
  250.         // ajaxCall("/newcar/ajax", "getSeries", personalContractHireSeriesData, fillSeries);
  251.         $scope.animateToSerieses();
  252.         Server.getSeriesData(personalContractHireSeriesData).then(fillSeries);
  253.     };
  254.    
  255.     $scope.getMotabSeries = function() {
  256.         $(".new-car-top-button-clicked ").removeClass("new-car-top-button-clicked ");
  257.         $('.new-car-top-buttons').find('button').eq(2).addClass("new-car-top-button-clicked ");
  258.        
  259.         $scope.options.category = 2;
  260.         resetFilters();
  261.        
  262.         var motabSeriesData = { "make":urlMake, "model":urlRange, "type":$scope.options.category };
  263.         // ajaxCall("/newcar/ajax", "getSeries", motabSeriesData, fillSeries);
  264.         $scope.animateToSerieses();
  265.         Server.getSeriesData(motabSeriesData).then(fillSeries);
  266.     };
  267.  
  268.     /************************************************
  269.      *
  270.      *      Get Filters when clicking on a series
  271.      *
  272.      ***********************************************/
  273.      $scope.getSearchOptions = function(series){
  274.    
  275.         resetFilters();
  276.         $scope.options.series = series.series;
  277.        
  278.         var dataToGetInitialFilters = {
  279.             "make":$scope.options.make,
  280.             "model":$scope.options.model,
  281.             "type":$scope.options.category,
  282.             "series":$scope.options.series
  283.         };
  284.  
  285.         //ajaxCall("/newcar/ajax", "getAllData", dataToGetInitialFilters, fillFiltersInitial);
  286.         Server.getInitialFilters(dataToGetInitialFilters).then(fillFiltersInitial);
  287.     }
  288.    
  289.     function fillFiltersInitial(a) {
  290.         $scope.styles.refineVisibility = "show"
  291.      
  292.         setFilters({
  293.             body_types:    a.body_types,
  294.             fuel_types:    a.fuel_types,
  295.             transmissions: a.transmissions,
  296.             doors:         a.doors
  297.         });
  298.      
  299.         $scope.fetchResults();
  300.        
  301.     }
  302.          
  303.     function setFilters(o) {
  304.         Object.keys(o).forEach(function(key) {
  305.             if (o[key])  setInScope(key, setFiltered(o[key]))
  306.         })
  307.     }
  308.      
  309.     function setFiltered(xs) {
  310.         xs.forEach(function(x){ x.filter = true })
  311.         return xs
  312.     }
  313.      
  314.     function setInScope(type, x) {
  315.       //$scope.$apply(function() {
  316.         $scope[type] = x
  317.       //})
  318.     }
  319.  
  320.     /**********************************************
  321.     *
  322.     *       Refine Filters
  323.     *
  324.     **********************************************/
  325.     $scope.changeFiltersExcept = function(filter){
  326.  
  327.         var filters = getAllSelectedFilters();
  328.        
  329.         var replaceFiltersData = {
  330.             "make":$scope.options.make,
  331.             "model":$scope.options.model,
  332.             "type":$scope.options.category,
  333.             "series":$scope.options.series,
  334.             "filters": filters,
  335.             "excluded": filter
  336.         };
  337.  
  338.         //ajaxCall("/newcar/ajax", "getAllData", replaceFiltersData, replaceFilters);
  339.         Server.getInitialFilters(replaceFiltersData).then(replaceFilters);
  340.  
  341.         if($scope.fetchResults){
  342.             $scope.fetchResults();
  343.         }
  344.     }
  345.  
  346.     /*************************************************************************
  347.     *
  348.     *       Fetch results based on make, model, type, series, and filters
  349.     *
  350.     *************************************************************************/
  351.     $scope.fetchResults = function(){
  352.         var fetchResultsFilters = getAllSelectedFilters();
  353.         //console.log(fetchResultsFilters);
  354.  
  355.         var dataToFetchResults = {
  356.             "make":$scope.options.make,
  357.             "model":$scope.options.model,
  358.             "type":$scope.options.category,
  359.             "series":$scope.options.series,
  360.             "filters": fetchResultsFilters
  361.         };
  362.         //ajaxCall("/newcar/ajax", "getResults", dataToFetchResults, fillResults);
  363.         Server.getResults(dataToFetchResults).then(fillResults);
  364.     }
  365.  
  366.     // Fill Results Div
  367.     var fillResults = function(resultsResponse){
  368.         // Sort Data based on offer_price and basic_price
  369.         if($scope.options.category != '2'){
  370.             resultsResponse.sort(function(a,b) {
  371.                 var first, second;
  372.                 first = +a.our_price ? Math.min(+a.our_price, +a.basic_price) : +a.basic_price;
  373.                 second = +b.our_price ? Math.min(+b.our_price, +b.basic_price) : +b.basic_price;
  374.                 return first - second;
  375.             });
  376.         }else{
  377.             resultsResponse.sort(function(a,b) {
  378.                 return parseInt(a.motab_price,10) - parseInt(b.motab_price,10);
  379.             });
  380.         }
  381.        
  382.         $scope.results = resultsResponse;
  383.         $scope.showResults = true; // set to true to show the results div
  384.     }
  385.  
  386.     /**
  387.      *  - Called when changing a refine checkbox, replaces the checkboxes with new data
  388.      *  - Fetch new results after replacing data
  389.      */
  390.     function replaceFilters(ajax_response){
  391.         $scope.styles.refineVisibility = "show";
  392.  
  393.         if(ajax_response.body_types)
  394.         {
  395.             fillBodyTypes(ajax_response.body_types);
  396.  
  397.         }
  398.         if(ajax_response.fuel_types)
  399.         {
  400.             fillFuelTypes(ajax_response.fuel_types);
  401.         }
  402.  
  403.         if(ajax_response.transmissions)
  404.         {
  405.             fillTransmissions(ajax_response.transmissions);
  406.         }
  407.  
  408.         if(ajax_response.doors)
  409.         {
  410.             fillDoors(ajax_response.doors);
  411.         }
  412.  
  413.     }
  414.  
  415.  
  416.  
  417.     /************************* FILL OF FILTERS DATA *************************/
  418.  
  419.     function fillBodyTypes(response){
  420.         angular.forEach(response, function(x){
  421.             x.filter = true;
  422.         });
  423.  
  424.         angular.forEach(response, function(d){
  425.             angular.forEach($scope.body_types, function(scope){
  426.                 if(scope.body_styles == d.body_styles)
  427.                 {
  428.                     d.filter = scope.filter;
  429.                 }
  430.             });
  431.  
  432.         });
  433.  
  434.         $scope.body_types = response;
  435.     }
  436.  
  437.     function fillFuelTypes(response){
  438.         angular.forEach(response, function(x){
  439.             x.filter = true;
  440.         });
  441.  
  442.         angular.forEach(response, function(d) {
  443.             angular.forEach($scope.fuel_types, function(scope) {
  444.                 if( scope.fuel_type == d.fuel_type )
  445.                 {
  446.                     d.filter = scope.filter;
  447.                 }
  448.             });
  449.         });
  450.  
  451.         $scope.fuel_types = response;
  452.     }
  453.  
  454.     function fillTransmissions(response){
  455.         angular.forEach(response, function(x){
  456.             x.filter = true;
  457.         });
  458.  
  459.         angular.forEach(response, function(d) {
  460.             angular.forEach($scope.transmissions, function(scope) {
  461.                 if( scope.transmission == d.transmission )
  462.                 {
  463.                     d.filter = scope.filter;
  464.                 }
  465.             });
  466.         });
  467.        
  468.         $scope.transmissions = response;
  469.     }
  470.  
  471.     function fillDoors(response){
  472.         angular.forEach(response, function(x){
  473.             x.filter = true;
  474.         });
  475.  
  476.         angular.forEach(response, function(d) {
  477.             angular.forEach($scope.doors, function(scope) {
  478.                 if( scope.doors == d.doors )
  479.                 {
  480.                     d.filter = scope.filter;
  481.                 }
  482.             });
  483.         });
  484.  
  485.         $scope.doors = response;
  486.     }
  487.  
  488.     /**********************************************
  489.     *
  490.     *       Get filters
  491.     *
  492.     **********************************************/
  493.     function getAllSelectedFilters(){
  494.         var ret = {
  495.             "body_types"    : getSelectedBodyTypes(),
  496.             "fuel_types"    : getSelectedFuelTypes(),
  497.             "transmissions" : getSelectedTransmissions(),
  498.             "doors"         : getSelectedDoors()
  499.         };
  500.  
  501.         return ret;
  502.     }
  503.  
  504.     function getSelectedBodyTypes(){
  505.         // Create array of body types
  506.         var selectedBodyTypes = [];
  507.         angular.forEach($scope.body_types, function(d){
  508.             if(d.filter == true) {
  509.                 selectedBodyTypes.push(d.body_styles);
  510.             }
  511.         });
  512.  
  513.         // Fill array with ALL if no tick boxes are ticked
  514.         if(selectedBodyTypes.length == 0){
  515.             angular.forEach($scope.body_types, function(d){
  516.                 selectedBodyTypes.push(d.body_styles);
  517.             });
  518.         }
  519.         return selectedBodyTypes;
  520.     }
  521.  
  522.     function getSelectedFuelTypes(){
  523.         // Create array of fuel types
  524.         var selectedFuelTypes = [];
  525.         angular.forEach($scope.fuel_types, function(d){
  526.             if(d.filter == true) {
  527.                 selectedFuelTypes.push(d.fuel_type);
  528.             }
  529.         });
  530.  
  531.         // Fill array with ALL if no tick boxes are ticked
  532.         if(selectedFuelTypes.length == 0){
  533.             angular.forEach($scope.fuel_types, function(d){
  534.                 selectedFuelTypes.push(d.fuel_type);
  535.             });
  536.         }
  537.  
  538.         return selectedFuelTypes;
  539.     }
  540.  
  541.     function getSelectedTransmissions(){
  542.         // Create array of transmissions
  543.         var selectedTransmissions = [];
  544.         angular.forEach($scope.transmissions, function(d){
  545.             if(d.filter == true){
  546.                 selectedTransmissions.push(d.transmission);
  547.             }
  548.         });
  549.  
  550.         // Fill array with ALL if no tick boxes are ticked
  551.         if(selectedTransmissions.length == 0){
  552.             angular.forEach($scope.transmissions, function(d){
  553.                 selectedTransmissions.push(d.transmission);
  554.             });
  555.         }
  556.  
  557.         return selectedTransmissions;
  558.     }
  559.  
  560.     function getSelectedDoors(){
  561.         // Create array of doors
  562.         var selectedDoors = [];
  563.         angular.forEach($scope.doors, function(d){
  564.             if(d.filter == true) {
  565.                 selectedDoors.push(d.doors);
  566.             }
  567.         });
  568.  
  569.         // Fill array with ALL if no tick boxes are ticked
  570.         if(selectedDoors.length == 0){
  571.             angular.forEach($scope.doors, function(d){
  572.                 selectedDoors.push(d.doors);
  573.             });
  574.         }
  575.  
  576.         return selectedDoors;
  577.     }
  578.  
  579.     /**********************************************
  580.     *
  581.     *       Reset filters to empty arrays
  582.     *
  583.     **********************************************/
  584.     function resetFilters(){
  585.  
  586.             $scope.body_types = [];
  587.             $scope.fuel_types = [];
  588.             $scope.transmissions = [];
  589.             $scope.doors = [];
  590.  
  591.     }
  592.  
  593.     /**********************************************
  594.     *
  595.     *       Convert numbers into body types
  596.     *
  597.     **********************************************/
  598.     $scope.convertBodyTypeToString = function(num){
  599.         switch(num){
  600.             case '2':
  601.                 return "4x4";
  602.                 break;
  603.            
  604.             case '4':
  605.                 return "City-Car";
  606.                 break;
  607.  
  608.             case '8':
  609.                 return "Coupe";
  610.                 break;
  611.  
  612.             case '16':
  613.                 return "Estate";
  614.                 break;
  615.  
  616.             case '32':
  617.                 return "Hatchback";
  618.                 break;
  619.  
  620.             case '64':
  621.                 return "MPV";
  622.                 break;
  623.  
  624.             case '128':
  625.                 return "Saloon";
  626.                 break;
  627.  
  628.             case '256':
  629.                 return "Sports";
  630.                 break;
  631.         }
  632.     }
  633.  
  634.     $scope.getImageRangeName = function(name){
  635.         name = name.trim();
  636.         return name;
  637.     }
  638.  
  639.     $scope.getImageSeriesName = function(name){
  640.         name = name.trim();
  641.         return name.replace(/\s|\[|\]|\/|\-/g,"-");
  642.     }
  643.  
  644.     $scope.getLowestPrice = function(){
  645.         if($scope.seriess){
  646.             var prices = [];
  647.  
  648.             $scope.seriess.data.map(function(item,index,array){
  649.                 var min = item.min.replace(",","");
  650.                 if(min !== "") this.push( parseInt(min, 10));
  651.             }, prices);
  652.  
  653.             $scope.seriess.data.map(function(item,index,array){
  654.                 if(item.offer_price) var offer_price = item.offer_price.replace(",","");
  655.                 if(offer_price != "" && offer_price > 0) this.push( parseInt(offer_price, 10));
  656.             }, prices);
  657.  
  658.             var min = Math.min.apply(Math, prices);
  659.  
  660.             return number_format(min);
  661.         }
  662.         else{
  663.             return "";
  664.         }
  665.     }
  666.  
  667.     $scope.number_format = function(num, decimals,dec_point, seperator){
  668.         return number_format(num, decimals, dec_point, seperator);
  669.     }
  670.    
  671.     $scope.num = function(item){
  672.         return parseInt(item,10);
  673.     }
  674.    
  675.     $scope.ceil = function(item){
  676.         return Math.ceil(item);
  677.     }  
  678.    
  679.     $scope.parseHTML = function(html){
  680.         return html;//$parse(html);
  681.     }
  682.  
  683.     $scope.animateToRefine = function(){
  684.         $("body, html").animate({scrollTop: $('.refine-box-show').offset().top-100}, "fast");
  685.     }
  686.  
  687.     $scope.animateToPromotedSpec = function(){
  688.         if($scope.activeItem.promoted_spec){
  689.             $("body, html").animate({scrollTop: $('.new-car-promoted-spec-title').offset().top-100}, "fast");
  690.         }
  691.         else{
  692.             $scope.animateToRefine();
  693.         }
  694.        
  695.     }
  696.  
  697.     $scope.animateToSerieses = function(){
  698.         $("body").animate({scrollTop: $('.mousearea').offset().top-100}, "fast");
  699.     }
  700.  
  701.     $scope.chooseSpecButtonText = function(){
  702.         if($scope.activeItem.promoted_spec){
  703.             return "View Specification";
  704.         }
  705.         else{
  706.             return "Choose Specification";
  707.         }
  708.     }
  709. }).filter('unsafe', function($sce) {
  710.     return function(val) {
  711.         return $sce.trustAsHtml(val);
  712.     };
  713. });
  714. ;
  715.  
  716.  
  717.  
  718.  
  719. /** Refresh the carousel when you resize the window **/
  720. $(window).resize(function(e) {
  721.     $('.frame').sly('reload');
  722. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement