Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // NEW CAR SEARCH
- /* Bootstrapping Process
- ============================================================ */
- /**
- * - Define the application
- */
- var newCarSearchApp = angular.module('newCarSearchApp', ['slyCarouselModule', 'newCarSearchModule']);
- /**
- * - Generic AJAX function - replace with $http
- */
- function ajaxCall(url, method, data, callback){
- var obj = {'method':method, 'data':data};
- var request = $.ajax({
- type: "POST",
- url: url,
- dataType: "json",
- data: {json: JSON.stringify(obj)}
- });
- request.done(function(result){
- if(typeof callback !== 'undefined'){
- callback(result);
- }
- });
- }
- /* Controller - newCarCtrl
- ============================================================ */
- newCarSearchApp.controller('newCarCtrl', function ($scope, $location, $timeout, $parse, Server) {
- /**
- * - Get the URL, used among many places in the application
- */
- var url = window.location.pathname.split("/");
- url.shift();
- // Create an array of the current URL - used in the template file for Sly
- var urlArray = window.location.pathname.split("/");urlArray.shift();
- $scope.currentUrl = urlArray;
- // Marker to check if ajax has completed
- $scope.ajaxFinished = false;
- // Determine whether to show X section or not by using class -show or -hide
- $scope.styles = { "refineVisibility": "show" }
- // Variable Initialising
- $scope.body_types = [];
- $scope.fuel_types = [];
- $scope.transmissions = [];
- $scope.doors = [];
- $scope.results = "";
- var urlMake = url[1];
- var urlRange = url[2];
- // Fetch SEO description
- var dataForSeoDescription = {
- "make" : urlMake,
- "range" : urlRange
- };
- // ajaxCall("/newcar/ajax", "getSeoDescriptionText", dataForSeoDescription, parseSeoDescription);
- Server.getSeoDescriptionText(dataForSeoDescription).then(parseSeoDescription);
- // Add SEO data to scope
- function parseSeoDescription(r){
- $scope.seoMainText = r.main_text;
- $scope.seoSubText = r.sub_text;
- }
- // Fetch Icons
- var dataForOffers = {
- "make" : urlMake,
- "range" : urlRange
- };
- //ajaxCall("/newcar/ajax", "getIcons", dataForIcons, parseIcons);
- Server.getNewCarOffers(dataForOffers).then(parseOfferData);
- // Add 3x top offers data to scope
- function parseOfferData(r){
- //console.log(r);
- $scope.offerData = r;
- }
- Server.getMaxDealerDeposit(dataForOffers).then(function(r){
- $scope.maxDealerDeposit = r;
- });
- // Data to count special offers for this make and range
- var dataForCountSpecialOffers = {
- "make" : urlMake,
- "range" : urlRange
- };
- // Fetch count of special offers for this make and range from database
- Server.countSpecialOffers(dataForCountSpecialOffers).then(function(r){
- $scope.offersCount = r.offers;
- });
- // Fetch count of special offers for this make and range from database
- Server.countMotability(dataForCountSpecialOffers).then(function(r){
- $scope.motabCount = r.motab;
- });
- var dataForRangeMaxSavingAndImageSeries = {
- "make" : urlMake,
- "range" : urlRange
- };
- Server.getRangeMaxSavingAndImageSeries(dataForRangeMaxSavingAndImageSeries).then(function(r){
- $scope.rangeInfo = {
- maxSaving: r.maxSaving.maxSaving,
- imageSeries: r.imageSeries.image_series
- };
- //console.log( $scope.rangeInfo );
- });
- // Initial Options
- $scope.options = {
- "make": urlMake,
- "model": urlRange,
- "category": 0,
- "series": ""
- };
- // Data to be sent via AJAX to the server
- var initialDataForSerieses = {
- "make":$scope.options.make,
- "model":$scope.options.model,
- "type":$scope.options.category
- };
- /************************************************
- *
- * Fill Initial Series on Page Load
- *
- ***********************************************/
- // Do Ajax to fetch initial "type 2" serieses
- //ajaxCall("/newcar/ajax", "getSeries", initialDataForSerieses, fillSeries);
- Server.getSeriesData(initialDataForSerieses).then(fillSeries);
- // fill series
- function fillSeries(data){
- //console.log(data);
- // Sort Data based on offer_price and basic_price
- /*data.sort(function(a,b) {
- return Math.min(parseInt(a.min,10), parseInt(a.offer_price,10)) - Math.min(parseInt(b.min,10), parseInt(b.offer_price,10));
- });*/
- data.sort(function(a, b) {
- var first, second;
- first = a.offer_price ? Math.min(+a.offer_price, +a.min) : +a.min;
- second = b.offer_price ? Math.min(+b.offer_price, +b.min) : +b.min;
- return first - second;
- })
- // Hide below sections
- $scope.styles.refineVisibility = "show";
- if ($scope.seriess === undefined) {
- $scope.seriess = {
- data: data
- }
- } else {
- $scope.seriess.data = data;
- }
- // Mark AJAX completed
- $scope.ajaxFinished = true;
- // Refresh the slider
- $scope.refreshSlider();
- $scope.reloadSlider();
- // Set show results to false
- $scope.showResults = true;
- //$scope.setActive();
- //$scope.clickSeriesFn($scope.activeItem);
- var seeMore = {
- min: "",
- series: "See More",
- special_offer: "0",
- seeMore: true
- }
- if($scope.options.category == "1"){
- $scope.seriess.data.push(seeMore);
- }
- // });
- if($scope.activeCount !=="a"){
- // Initialise URL (index 0 is empty, so start from 1 after the leading /)
- var url = window.location.pathname.split("/");
- // Activates series if the series is in the URL
- for (var i = $scope.seriess.data.length - 1; i >= 0; i--) {
- //console.log(scope.seriess[i]);
- if(url[5])
- {
- if(data[i].series.toUpperCase() == url[5].toUpperCase())
- {
- //console.log(i);
- //$timeout(function(){ $scope.activateSeries(i); });
- $scope.activateSeries(i);
- }
- }
- };
- }
- };
- /******************************************************************************************
- *
- * Buttons to change serieses between Normal, Personal Contract Hire, & Motability
- *
- *****************************************************************************************/
- $scope.getNormalSeries = function() {
- $(".new-car-top-button-clicked ").removeClass("new-car-top-button-clicked ");
- $('.new-car-top-buttons').find('button').eq(0).addClass("new-car-top-button-clicked ");
- $scope.options.category = 0;
- resetFilters();
- var normalSeriesData = { "make":urlMake, "model":urlRange, "type":$scope.options.category };
- //ajaxCall("/newcar/ajax", "getSeries", normalSeriesData, fillSeries);
- $scope.animateToSerieses();
- Server.getSeriesData(normalSeriesData).then(fillSeries);
- };
- $scope.getPersonalContractHireSeries = function() {
- $(".new-car-top-button-clicked ").removeClass("new-car-top-button-clicked ");
- $('.new-car-top-buttons').find('button').eq(1).addClass("new-car-top-button-clicked ");
- $scope.options.category = 1;
- resetFilters();
- var personalContractHireSeriesData = { "make":urlMake, "model":urlRange, "type":$scope.options.category };
- // ajaxCall("/newcar/ajax", "getSeries", personalContractHireSeriesData, fillSeries);
- $scope.animateToSerieses();
- Server.getSeriesData(personalContractHireSeriesData).then(fillSeries);
- };
- $scope.getMotabSeries = function() {
- $(".new-car-top-button-clicked ").removeClass("new-car-top-button-clicked ");
- $('.new-car-top-buttons').find('button').eq(2).addClass("new-car-top-button-clicked ");
- $scope.options.category = 2;
- resetFilters();
- var motabSeriesData = { "make":urlMake, "model":urlRange, "type":$scope.options.category };
- // ajaxCall("/newcar/ajax", "getSeries", motabSeriesData, fillSeries);
- $scope.animateToSerieses();
- Server.getSeriesData(motabSeriesData).then(fillSeries);
- };
- /************************************************
- *
- * Get Filters when clicking on a series
- *
- ***********************************************/
- $scope.getSearchOptions = function(series){
- resetFilters();
- $scope.options.series = series.series;
- var dataToGetInitialFilters = {
- "make":$scope.options.make,
- "model":$scope.options.model,
- "type":$scope.options.category,
- "series":$scope.options.series
- };
- //ajaxCall("/newcar/ajax", "getAllData", dataToGetInitialFilters, fillFiltersInitial);
- Server.getInitialFilters(dataToGetInitialFilters).then(fillFiltersInitial);
- }
- function fillFiltersInitial(a) {
- $scope.styles.refineVisibility = "show"
- setFilters({
- body_types: a.body_types,
- fuel_types: a.fuel_types,
- transmissions: a.transmissions,
- doors: a.doors
- });
- $scope.fetchResults();
- }
- function setFilters(o) {
- Object.keys(o).forEach(function(key) {
- if (o[key]) setInScope(key, setFiltered(o[key]))
- })
- }
- function setFiltered(xs) {
- xs.forEach(function(x){ x.filter = true })
- return xs
- }
- function setInScope(type, x) {
- //$scope.$apply(function() {
- $scope[type] = x
- //})
- }
- /**********************************************
- *
- * Refine Filters
- *
- **********************************************/
- $scope.changeFiltersExcept = function(filter){
- var filters = getAllSelectedFilters();
- var replaceFiltersData = {
- "make":$scope.options.make,
- "model":$scope.options.model,
- "type":$scope.options.category,
- "series":$scope.options.series,
- "filters": filters,
- "excluded": filter
- };
- //ajaxCall("/newcar/ajax", "getAllData", replaceFiltersData, replaceFilters);
- Server.getInitialFilters(replaceFiltersData).then(replaceFilters);
- if($scope.fetchResults){
- $scope.fetchResults();
- }
- }
- /*************************************************************************
- *
- * Fetch results based on make, model, type, series, and filters
- *
- *************************************************************************/
- $scope.fetchResults = function(){
- var fetchResultsFilters = getAllSelectedFilters();
- //console.log(fetchResultsFilters);
- var dataToFetchResults = {
- "make":$scope.options.make,
- "model":$scope.options.model,
- "type":$scope.options.category,
- "series":$scope.options.series,
- "filters": fetchResultsFilters
- };
- //ajaxCall("/newcar/ajax", "getResults", dataToFetchResults, fillResults);
- Server.getResults(dataToFetchResults).then(fillResults);
- }
- // Fill Results Div
- var fillResults = function(resultsResponse){
- // Sort Data based on offer_price and basic_price
- if($scope.options.category != '2'){
- resultsResponse.sort(function(a,b) {
- var first, second;
- first = +a.our_price ? Math.min(+a.our_price, +a.basic_price) : +a.basic_price;
- second = +b.our_price ? Math.min(+b.our_price, +b.basic_price) : +b.basic_price;
- return first - second;
- });
- }else{
- resultsResponse.sort(function(a,b) {
- return parseInt(a.motab_price,10) - parseInt(b.motab_price,10);
- });
- }
- $scope.results = resultsResponse;
- $scope.showResults = true; // set to true to show the results div
- }
- /**
- * - Called when changing a refine checkbox, replaces the checkboxes with new data
- * - Fetch new results after replacing data
- */
- function replaceFilters(ajax_response){
- $scope.styles.refineVisibility = "show";
- if(ajax_response.body_types)
- {
- fillBodyTypes(ajax_response.body_types);
- }
- if(ajax_response.fuel_types)
- {
- fillFuelTypes(ajax_response.fuel_types);
- }
- if(ajax_response.transmissions)
- {
- fillTransmissions(ajax_response.transmissions);
- }
- if(ajax_response.doors)
- {
- fillDoors(ajax_response.doors);
- }
- }
- /************************* FILL OF FILTERS DATA *************************/
- function fillBodyTypes(response){
- angular.forEach(response, function(x){
- x.filter = true;
- });
- angular.forEach(response, function(d){
- angular.forEach($scope.body_types, function(scope){
- if(scope.body_styles == d.body_styles)
- {
- d.filter = scope.filter;
- }
- });
- });
- $scope.body_types = response;
- }
- function fillFuelTypes(response){
- angular.forEach(response, function(x){
- x.filter = true;
- });
- angular.forEach(response, function(d) {
- angular.forEach($scope.fuel_types, function(scope) {
- if( scope.fuel_type == d.fuel_type )
- {
- d.filter = scope.filter;
- }
- });
- });
- $scope.fuel_types = response;
- }
- function fillTransmissions(response){
- angular.forEach(response, function(x){
- x.filter = true;
- });
- angular.forEach(response, function(d) {
- angular.forEach($scope.transmissions, function(scope) {
- if( scope.transmission == d.transmission )
- {
- d.filter = scope.filter;
- }
- });
- });
- $scope.transmissions = response;
- }
- function fillDoors(response){
- angular.forEach(response, function(x){
- x.filter = true;
- });
- angular.forEach(response, function(d) {
- angular.forEach($scope.doors, function(scope) {
- if( scope.doors == d.doors )
- {
- d.filter = scope.filter;
- }
- });
- });
- $scope.doors = response;
- }
- /**********************************************
- *
- * Get filters
- *
- **********************************************/
- function getAllSelectedFilters(){
- var ret = {
- "body_types" : getSelectedBodyTypes(),
- "fuel_types" : getSelectedFuelTypes(),
- "transmissions" : getSelectedTransmissions(),
- "doors" : getSelectedDoors()
- };
- return ret;
- }
- function getSelectedBodyTypes(){
- // Create array of body types
- var selectedBodyTypes = [];
- angular.forEach($scope.body_types, function(d){
- if(d.filter == true) {
- selectedBodyTypes.push(d.body_styles);
- }
- });
- // Fill array with ALL if no tick boxes are ticked
- if(selectedBodyTypes.length == 0){
- angular.forEach($scope.body_types, function(d){
- selectedBodyTypes.push(d.body_styles);
- });
- }
- return selectedBodyTypes;
- }
- function getSelectedFuelTypes(){
- // Create array of fuel types
- var selectedFuelTypes = [];
- angular.forEach($scope.fuel_types, function(d){
- if(d.filter == true) {
- selectedFuelTypes.push(d.fuel_type);
- }
- });
- // Fill array with ALL if no tick boxes are ticked
- if(selectedFuelTypes.length == 0){
- angular.forEach($scope.fuel_types, function(d){
- selectedFuelTypes.push(d.fuel_type);
- });
- }
- return selectedFuelTypes;
- }
- function getSelectedTransmissions(){
- // Create array of transmissions
- var selectedTransmissions = [];
- angular.forEach($scope.transmissions, function(d){
- if(d.filter == true){
- selectedTransmissions.push(d.transmission);
- }
- });
- // Fill array with ALL if no tick boxes are ticked
- if(selectedTransmissions.length == 0){
- angular.forEach($scope.transmissions, function(d){
- selectedTransmissions.push(d.transmission);
- });
- }
- return selectedTransmissions;
- }
- function getSelectedDoors(){
- // Create array of doors
- var selectedDoors = [];
- angular.forEach($scope.doors, function(d){
- if(d.filter == true) {
- selectedDoors.push(d.doors);
- }
- });
- // Fill array with ALL if no tick boxes are ticked
- if(selectedDoors.length == 0){
- angular.forEach($scope.doors, function(d){
- selectedDoors.push(d.doors);
- });
- }
- return selectedDoors;
- }
- /**********************************************
- *
- * Reset filters to empty arrays
- *
- **********************************************/
- function resetFilters(){
- $scope.body_types = [];
- $scope.fuel_types = [];
- $scope.transmissions = [];
- $scope.doors = [];
- }
- /**********************************************
- *
- * Convert numbers into body types
- *
- **********************************************/
- $scope.convertBodyTypeToString = function(num){
- switch(num){
- case '2':
- return "4x4";
- break;
- case '4':
- return "City-Car";
- break;
- case '8':
- return "Coupe";
- break;
- case '16':
- return "Estate";
- break;
- case '32':
- return "Hatchback";
- break;
- case '64':
- return "MPV";
- break;
- case '128':
- return "Saloon";
- break;
- case '256':
- return "Sports";
- break;
- }
- }
- $scope.getImageRangeName = function(name){
- name = name.trim();
- return name;
- }
- $scope.getImageSeriesName = function(name){
- name = name.trim();
- return name.replace(/\s|\[|\]|\/|\-/g,"-");
- }
- $scope.getLowestPrice = function(){
- if($scope.seriess){
- var prices = [];
- $scope.seriess.data.map(function(item,index,array){
- var min = item.min.replace(",","");
- if(min !== "") this.push( parseInt(min, 10));
- }, prices);
- $scope.seriess.data.map(function(item,index,array){
- if(item.offer_price) var offer_price = item.offer_price.replace(",","");
- if(offer_price != "" && offer_price > 0) this.push( parseInt(offer_price, 10));
- }, prices);
- var min = Math.min.apply(Math, prices);
- return number_format(min);
- }
- else{
- return "";
- }
- }
- $scope.number_format = function(num, decimals,dec_point, seperator){
- return number_format(num, decimals, dec_point, seperator);
- }
- $scope.num = function(item){
- return parseInt(item,10);
- }
- $scope.ceil = function(item){
- return Math.ceil(item);
- }
- $scope.parseHTML = function(html){
- return html;//$parse(html);
- }
- $scope.animateToRefine = function(){
- $("body, html").animate({scrollTop: $('.refine-box-show').offset().top-100}, "fast");
- }
- $scope.animateToPromotedSpec = function(){
- if($scope.activeItem.promoted_spec){
- $("body, html").animate({scrollTop: $('.new-car-promoted-spec-title').offset().top-100}, "fast");
- }
- else{
- $scope.animateToRefine();
- }
- }
- $scope.animateToSerieses = function(){
- $("body").animate({scrollTop: $('.mousearea').offset().top-100}, "fast");
- }
- $scope.chooseSpecButtonText = function(){
- if($scope.activeItem.promoted_spec){
- return "View Specification";
- }
- else{
- return "Choose Specification";
- }
- }
- }).filter('unsafe', function($sce) {
- return function(val) {
- return $sce.trustAsHtml(val);
- };
- });
- ;
- /** Refresh the carousel when you resize the window **/
- $(window).resize(function(e) {
- $('.frame').sly('reload');
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement