﻿/*!
*  carfinder.js
*/

function updateModels(data) {
    //if data exists load into options
    if (data.model.length > 0) {
        var optArr = [];
        for (i = 0; i < data.model.length; i++) {
            optArr.push('<option value="' + data.model[i]['value'] + '">' + data.model[i]['value'] + '</option>');
        }
        //populate select list
        if (optArr.length) {
            $('select#cfmodel').html('<option value="">Choose...</option>' + optArr.join(','));
        } else {
            $('select#cfmodel').html('<option value="">Choose...</option>');
        }
    } else {
        $('select#cfmodel').html('<option value="">Error</option>');
    }
}

function isMvt(str) {
    if ($('#mvt4').length) {
        if (!~str.indexOf('Enter')) {
            if (!!~str.indexOf('@')) return 'email';
            if (!isNaN(parseFloat(str)) && isFinite(str)) return 'phone';
        }
    }    
    return false;
}

function carfinder() {   

    //run uniform plugin on checkboxes
    //$('.userdetails input:checkbox').uniform();

    var eml = (isMvt($('#mvtcfcontact').val()) == 'email') ? $('#mvtcfcontact') : $('#cfemailaddress'),
        mbi = (isMvt($('#mvtcfcontact').val()) == 'phone') ? $('#mvtcfcontact') : $('#cfmobilenumber'),
        dmn = $('#cfdomain'),
        dta = motors.constants.jsonfilter.document,
        mvtExists = false;
    /*
     * Certain manufacturers commented out to save errors from the server
     * Difinitive list for future release.
     */
    
    var manu = { "manufacturer": [{ "value": "AC" }, { "value": "Abarth" }, { "value": "Aixam" }, { "value": "Alfa Romeo" }, /*{ "value": "Ariel" },*/ { "value": "Asia" }, { "value": "Aston Martin" }, { "value": "Audi" }, { "value": "Austin" }, { "value": "BMW" }, { "value": "Bentley" }, { "value": "Cadillac" }, { "value": "Caterham" }, { "value": "Chevrolet" }, { "value": "Chrysler" }, { "value": "Citroen" }, /*{ "value": "Coleman Milne" },*/ { "value": "Daewoo" }, { "value": "Daihatsu" }, { "value": "Daimler" }, { "value": "Dodge" }, { "value": "Ferrari" }, { "value": "Fiat" }, { "value": "Ford" }, { "value": "Hillman" }, { "value": "Holden" }, { "value": "Honda" }, { "value": "Hyundai" }, /*{ "value": "Infiniti" },*/ { "value": "Isuzu" }, { "value": "Jaguar" }, { "value": "Jeep" }, { "value": "Jensen" }, { "value": "KTM" }, { "value": "Kia" }, { "value": "Koenigsegg" }, { "value": "Lamborghini" }, { "value": "Lancia" }, { "value": "Land Rover" }, { "value": "Lexus" }, { "value": "Ligier" }, { "value": "Lincoln" }, { "value": "Lotus" }, { "value": "MG" }, { "value": "MINI" }, { "value": "Maserati" }, { "value": "Mazda" }, { "value": "McLaren" }, { "value": "Mercedes-Benz" }, { "value": "Microcar" }, { "value": "Mitsubishi" }, { "value": "Morgan" }, { "value": "Morris" }, { "value": "Nissan" }, { "value": "Opel" }, { "value": "Perodua" }, { "value": "Peugeot" }, { "value": "Plymouth" }, { "value": "Porsche" }, { "value": "Proton" }, { "value": "Reliant" }, { "value": "Renault" }, { "value": "Rolls Royce" }, { "value": "Rover" }, { "value": "Saab" }, { "value": "SEAT" }, { "value": "Skoda" }, { "value": "Smart" }, { "value": "Ssangyong" }, { "value": "Subaru" }, { "value": "Suzuki" }, { "value": "TVR" }, { "value": "Talbot" }, { "value": "Toyota" }, { "value": "Triumph" }, { "value": "Vauxhall" }, { "value": "Volkswagen" }, { "value": "Volvo" }, { "value": "Westfield" }, { "value": "Wolseley"}] };    

    //populate email if available
    if (eml.val() != eml.prev('label').text()) {
        $('#cfemail').val(eml.val());
    }
    
    //populate mobile if available
    if (mbi.val() != mbi.prev('label').text()) {
        $('#cfmobile').val(mbi.val());
    }
    
    //populate postcode if available
    if (dta.postcode) {
        $('#cflocation').val(dta.postcode);
    }

    //populate manufacturer options
    var manuOps = [];
    for (var i = 0; i < manu.manufacturer.length; i++) {        
        var val = manu.manufacturer[i].value,
            selected = '';
        if (dta.data['manufacturer'].item[0] != null) {
            if (dta.data['manufacturer'] && dta.data['manufacturer'].item[0].name == val) {
                selected = 'selected="selected"';
            } 
        }
        manuOps.push('<option value="'+ val +'" '+ selected +'>'+ val +'</option>');
    }
    $('select#cfmake').append(manuOps.join(','));

    //populate model options
    function populateModels(make) {
        //loading
        $('select#cfmodel').html('<option value="">Loading...</option>');

        //get json feed from Limitless
        make = (make == 'Mercedes-Benz') ? 'Mercedes' : make;
        $.getJSON('http://api.carsource.co.uk/json-models-list.php?callback=updateModels&maker_F=' + make + '&used_new_F=M&all_stockF=Y&jsoncallback=?');
        
        // Send ajax request to get options
        /*$.ajax({
            type: 'GET',
            url: motors.helper.applicationRoot + '/ajax/models.ashx?' + make + '&type=ops',
            error: function() {
                $('select#cfmodel').html('<option value="">Error</option>');
            },
            success: function (data) {
                //populate select list
                if (data) {
                    $('select#cfmodel').html('<option value="">Choose...</option>' + data);
                } else {
                    $('select#cfmodel').html('<option value="">Choose...</option>');
                }
            }
        });*/
    }
    if (dta.data['manufacturer'].item[0] != null) {
        populateModels(dta.data['manufacturer'].item[0].name);
    }
    $('#cfmake').change(function () {        
        populateModels($(this).val());
    });

    //price range    
    function isEmpty(obj) {
        for (var i in obj) { return false; }
        return true;
    }

    function getNum(op) {

        function toNearest(val, num) {
            return Math.round(val / num) * num;
        }

        var rounded;

        if (op < 10000) {
            rounded = toNearest(op, 1000);
        } else if (op > 10000 && op < 20000) {
            rounded = toNearest(op, 2000);
        } else if (op > 20000 && op < 30000) {
            rounded = toNearest(op, 5000);
        } else if (op > 30000 && op < 40000) {
            rounded = toNearest(op, 10000);
        } else if (op > 30000 && op < 40000) {
            rounded = toNearest(op, 10000);
        } else if (op > 40000) {
            rounded = 75000;
        } else if (op > 75000) {
            rounded = 100000;
        } else {
            rounded = 100000;
        }

        return rounded;

    }

    function buildPrices(mn,mx) {
        var args = arguments,
            minrange = ['Min',0,1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 12000, 14000, 16000, 18000, 20000, 25000, 30000, 40000, 75000],
            maxrange = ['Max', 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 12000, 14000, 16000, 18000, 20000, 25000, 30000, 40000, 75000,100000];

        function createOps(grp,arr,amt) {
            var priceOps = [];
            for (var i = 0; i < arr.length; i++) {
                var val = arr[i],
                disp = val,
                selected = '';

                if (disp == 'Min' || disp == 'Max') {
                    val = (disp == 'Min') ? 0 : 100000;
                }

                if (val == amt) {
                    selected = 'selected="selected"';
                }
                
                priceOps.push('<option value="' + val + '" '+ selected +'>' + disp + '</option>');
            }            
            $('select#cfprice' + grp).html(priceOps.join(','));          
        }
        
        createOps('min', minrange, mn);
        createOps('max', maxrange, mx);
    }
    
    //check object is not empty
    if (!isEmpty(dta.sliders['nav-price'])) {
        var min = getNum(dta.sliders['nav-price'].posStart),
            max = getNum(dta.sliders['nav-price'].posEnd);

        min = (min == 100000) ? 0 : min;
        max = (max == 0) ? 100000 : max;

        buildPrices(min, max);
    } else {
        buildPrices('','');
    }

    //populate request domain
    if (dmn.val()) $('#cfrequestdomain').val(dmn.val());
    
    //populate mvt variant
    if ($('#mvtvariation').length) {
        $('#cfmvtvariation').val($('#mvtvariation').val());
        mvtExists = true;
    } else {
        $('#cfmvtvariation').val(0);
    }

    //submit
    $('form#carfinder').submit(function () {
        var form = $(this),
            send = true,
            valid = 0;

        if (!$('#cflocation').val()) {
            $('#cflocation').parent('div.formrow').addClass('error');
            valid--;
        } else {
            $('#cflocation').parent('div.formrow').removeClass('error');
            valid++;
        }

        //validate email
        function isValidEmail(e) {
            var emailRegEx = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
            return emailRegEx.test(e);
        }
        if ($('#cfemail').val() && !isValidEmail($('#cfemail').val())) {
            $('#cfemail').parent('div.formrow').addClass('error');
            valid--;
        } else {
            $('#cfemail').parent('div.formrow').removeClass('error');
            valid++;
        }

        //validate mobile
        if ($('#cfmobile').val() && isNaN($('#cfmobile').val())) {
            $('#cfmobile').parent('div.formrow').addClass('error');
            valid--; ;
        } else {
            $('#cfmobile').parent('div.formrow').removeClass('error');
            valid++;
        }

        //make sure email or mobile submitted
        if (!$('#cfemail').val() && !$('#cfmobile').val()) {
            $('#cfemail,#cfmobile').parent('div.formrow').addClass('error');
            valid--;
        } else {
            $('#cfemail,#cfmobile').parent('div.formrow').removeClass('error');
            valid++;
        }

        //validate makes
        if (!$('#cfmake').val()) {
            $('#cfmake').parent('div.formrow').addClass('error');
            valid--;
        } else {
            $('#cfmake').parent('div.formrow').removeClass('error');
            valid++;
        }

        //validate models
        if (!$('#cfmodel').val()) {
            $('#cfmodel').parent('div.formrow').addClass('error');
            valid--;
        } else {
            $('#cfmodel').parent('div.formrow').removeClass('error');
            valid++;
        }

        //validate prices
        if (parseInt($('#cfpricemin').val()) > parseInt($('#cfpricemax').val())) {
            var label = $('#cfpricemin').parent('div.formrow').addClass('error').children('label[for="cfpricemin"]');
            label.find('em').remove().end().append(' <em style="color:#000; font-size:10px;">Min price larger than Max</em>');
            valid--;
        } else {
            $('#cfpricemin').parent('div.formrow').removeClass('error').children('label[for="cfpricemin"]').find('em').remove();
            valid++;
        }

        //if enough fields filled send request
        if (valid == 7) {
            //loading
            form.find('input[type="image"]').after('<span class="carfinderloading">Sending request...</span>');

            //ajax
            $.ajax({
                type: 'POST',
                url: motors.buildUrl(form.attr('action')),
                data: form.serialize(),
                error: function(msg) {
                    form.html('<strong style="color:red;">An error occured whilst trying to process your request, please try again later.</strong>');
                },
                success: function(msg) {
                    form.html(msg);
                    if (msg.indexOf('ajax-success') > -1) {
                        form.append('<p class="ajax-success newform"><a href="#" onclick="motors.ajax.showCarFinder(\'form\');return false;">Set up another alert &raquo;</a></p>');
                        //google MVT conversion http://www.google.com/support/websiteoptimizer/bin/answer.py?hl=en-uk&answer=61426
                        if (mvtExists) {
                            try {
                                var gwoTracker = _gat._getTracker("UA-1084356-2");
                                gwoTracker._trackPageview("/0386147485/goal");
                            } catch (err) { }
                        }
                        //event tracking
                        motors.ajax.trackGoals('/ajax/carfinder_sent.ashx');
                    }
                }
            });

        }

        return false
    });
}
