$(function () {
	
    // Video hover
    $(".video-spinner").closest('a').hover(function () {
        $(this).find('video')[0].play();
    }
    , function () {
        $(this).find('video')[0].pause();
    });

    // Menu expand
    $('.main-header .btn-expand').on('click', function (e) {
        e.preventDefault();
        $('.main-menu').toggleClass('expanded');
    });

    // Make/models filters
    $('.js-filter-models').each(function (id, el) {
        var clone = $(el).clone();
        clone.removeAttr('name id class').addClass('js-filter-models-holder').css('display', 'none');
        clone.insertAfter(el);
    });
    $('.js-filter-makes').each(function (id, el) {
        var $makes = $(this),
                $form = $makes.closest('form'),
                $models = $form.find('.js-filter-models'),
                $modelsHolder = $form.find('.js-filter-models-holder'),
                $value = $makes.val();

        $models.html($modelsHolder.html());
        $models.find('option').filter('[data-parent][data-parent!="' + $value + '"]').remove();

        $makes.on('change', function () {
            var $value = $makes.val();

            $models.html($modelsHolder.html());
            $models.find('option').filter('[data-parent][data-parent!="' + $value + '"]').remove();
        });
    });

    // Fancybox
    var $fancybox = $('.fancybox');
    if ($fancybox.length) {
        $fancybox.fancybox();
    }

    // Inquire overlay close
    var $overlay = $('.overlay.timeout');
    if ($overlay.length) {
        // Open dialog after 60s
        setTimeout(function () {
            var id = $overlay.data('id'),
                    dialog_cookie = localStorage.getItem('dialog');
            if (!dialog_cookie) {
                dialog_cookie = {};
            } else {
                dialog_cookie = JSON.parse(dialog_cookie);
            }
            if (!dialog_cookie[id]) {
                $overlay.addClass('active');
            }
        }, 60 * 1000);
    }

    // Close dialog and set cookie
    $('.js-dialog-close').on('click', function (e) {
        e.preventDefault();
        var $overlay = $('.overlay');
        var id = $overlay.data('id');
        $overlay.remove();

        if (!id)
            return;

        var dialog_cookie = localStorage.getItem('dialog');
        if (!dialog_cookie) {
            dialog_cookie = {};
        } else {
            dialog_cookie = JSON.parse(dialog_cookie);
        }

        dialog_cookie[id] = true;
        dialog_cookie = JSON.stringify(dialog_cookie);
        localStorage.setItem('dialog', dialog_cookie);
    });

    // Fill contact url in vehicle inquiry
    var $contactURL = $('input[name="contact-url"]');
    if ($contactURL.length) {
        var url = window.location.href;
        $contactURL.val(url);
    }

    // Search
    $('.js-search-sort').on('change', function () {
        $(this).closest('form').submit();
    });

    // Calculator
    $('.js-calculate').on('click', function (e) {
        e.preventDefault();

        var price = parseFloat($('#calc-price').val()),
                interest = parseFloat($('#calc-interest').val()) / 1200,
                period = parseFloat($('#calc-period').val()),
                tradein = parseFloat($('#calc-tradein').val()) || 0,
                payment = parseFloat($('#calc-payment').val()) + tradein,
                validation_errors = false,
                $alert = $('.calculator-alert');

        //Check if not nan
        if (isNaN(price)) {
            $alert.text("Please fill Vehicle Price field");
            $('#calc-price').addClass('has-error');
            validation_errors = true;
        } else if (isNaN(interest)) {
            $alert.text("Please fill Interest Rate field");
            $('#calc-interest').addClass('has-error');
            validation_errors = true;
        } else if (isNaN(period)) {
            $alert.text("Please fill Period field");
            $('#calc-period').addClass('has-error');
            validation_errors = true;
        } else if (isNaN(payment)) {
            $alert.text("Please fill Down Payment field");
            $('#calc-payment').addClass('has-error');
            validation_errors = true;
        } else if (payment > price) {
            $alert.text("Down payment can not be more than vehicle price");
            $('#calc-payment').addClass('has-error');
            validation_errors = true;
        }

        if (!validation_errors) {
            var monthlyPayment = (((price - payment) * interest * Math.pow(1 + interest, period)) / ((Math.pow(1 + interest, period)) - 1)).toFixed(2),
                    totalAmount = (payment + (monthlyPayment * period)).toFixed(2),
                    totalInterest = (totalAmount - price).toFixed(2);

            $('.calculator-results').slideDown();
            $alert.addClass('hidden');

            $('.js-calculator-monthly-payment').text('$' + monthlyPayment);
            $('.js-calculator-total-interest').text('$' + totalInterest);
            $('.js-calculator-total-amount').text('$' + totalAmount);
        } else {
            $('.calculator-results').slideUp();
            $alert.removeClass('hidden');
        }
    });
    $(".calc-field").on("keypress keyup blur", function (event) {
        $(this).val($(this).val().replace(/[^0-9\.]/g, ''));
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
            event.preventDefault();
        }

        if ($(this).val() != '') {
            $(this).removeClass('has-error');
        }
    });

    var currentUrl = window.location.href,
            afterRemove = currentUrl.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/');

    if (afterRemove[1] == 'thank-you-walkthrough') {
        window.location.hash = '';
    }

    // Walkthrough
    if ($('.walkthrough').length) {
		
        //check if current page is home page
        if (afterRemove[1] != undefined && afterRemove[1] != '' && afterRemove[1] == '#1') {
            location.href = "https://" + afterRemove[0];
        } else if (afterRemove[1] == 'dev-homepage') {
            window.location.hash = '';
        } else if (afterRemove[1] != undefined && afterRemove[1] != '' && afterRemove[1] != '#1') {
            // add #1 when second page opened
            window.location.hash = 1;
        }

        $(window).on('hashchange', function (event) {
			
            var newhash = event.originalEvent.newURL,
                    newstep = 1;

            if (newhash.indexOf('#') !== -1) {
                newstep = parseInt(newhash.substr(newhash.indexOf('#') + 1));
            }
            // Track event if moving forward
//            if (newstep > walk_current_index) {
//                 ga('send', 'event', 'Walkthrough', 'Step process', 'Step ' + newstep);
//            }

            // Go to step
            if (walk_current_index != newstep) {
                $('.walkthrough-step:eq(' + walk_current_index + ')').length;
                if (!$('.walkthrough-step:eq(' + walk_current_index + ')').length)
                    return;
                $('.walkthrough').css('transform', 'translate(-' + (newstep - 1) + '00%, 0)');
                walk_current_index = newstep;
            }
        });

        // Setup Cleave
        if ($('input[name="birthdate"]').length > 0) {
            var cleave = new Cleave('input[name="birthdate"]', {
                date: true,
                datePattern: ['m', 'd', 'Y']
            });
        }
        $('.walkthrough').on('click', '[data-controls]', function (e) {
            e.preventDefault();
        });
        var walk_current_index = 0;
        $('.walkthrough').addClass('wrapped');
        $('.js-walkthrough-next').on('click', function (e) {
			
			$('.lived-step-disabled').addClass('hidden');
         	$('.lived-step-enabled').removeClass('hidden');
			
            var index = $(this).closest('li').index();

            // Check how many steps to skip (usually one, except some edge cases)
            if ($(this).closest('li').find('[name="employment-status"]:checked').length && ($('[name="employment-status"]:checked').val() == 'Employed' || $('[name="employment-status"]:checked').val() == 'Other')) {
                index += 2;
            } else {
                index++;
            }

            // Go to next step
            if (!$('.walkthrough-step:eq(' + index + ')').length) {
                $('.walkthrough-section form').submit();
            }
            e.preventDefault();

            index + 1;

            if (afterRemove[1] != undefined && afterRemove[1] != '' && afterRemove[1] == '#1') {
                window.location.hash = '';
            } else if (afterRemove[1] == 'dev-homepage') {
                window.location.hash = '';
            } else {
                window.location.hash = (index + 1);
            }

            walk_current_index = index;
            newstep = index + 1;

            // Go to step
            if (walk_current_index != newstep) {
                $('.walkthrough-step:eq(' + walk_current_index + ')').length;
                if (!$('.walkthrough-step:eq(' + walk_current_index + ')').length)
                    return;
                $('.walkthrough').css('transform', 'translate(-' + (newstep - 1) + '00%, 0)');
                walk_current_index = newstep;
            }
        });

        $('.js-walkthrough-back').on('click', function (e) {
			
            e.preventDefault();
            $(this).blur();
            var others = $('input[name="employment-status"]:checked').val();
            newstep = newstep - 1;
            if (others == 'Other' && newstep == 3) {
                newstep = newstep - 1;
            }
            $('.walkthrough').css('transform', 'translate(-' + (newstep - 1) + '00%, 0)');
            walk_current_index = newstep;
            history.back();
        });
        $('.js-walkthrough-open-overlay').on('click', function (e) {
            e.preventDefault();
            var vehicle = $('input[name="vehicle[]"]:checked').val();
            var budget = $('input[name="budget"]:checked').data('formatted')
            $('.js-overlay-vehicle').text(vehicle);
            $('.js-overlay-budget').text(budget);
            $('.overlay').addClass('active');
        });

        var email_format = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        var postal_code_format = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/;
        var phone_format = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;

        $('.js-walkthrough-next').prop('disabled', true);
        if ($('.walkthrough-step input:checked').length || $('.js-walkthrough-setvehicle').length) {
            $('.js-walkthrough-next').first().prop('disabled', false);
        }
        $('.walkthrough-step input,.walkthrough-step select').on('keyup change', function (e) {
			
            var disabled = false;
            var error_text = '';
            var income_minimum_text = '';
            var INCOME_MIN = 2200;

  // Validate extra/hidden sections
            // Disable income screen and prevent extra steps
            if (
                    ($('[name="employment-status"]:checked').val() == 'Homemaker' || $('[name="employment-status"]:checked').val() == 'Student' || $('[name="employment-status"]:checked').val() == 'Unemployed') && $('[name="coapplicant"]:checked').val() == 'No'
                    ) {
                $('.income-step-disabled').removeClass('hidden');
                $('.income-step-enabled').addClass('hidden');
            } else {
                $('.income-step-disabled').addClass('hidden');
                $('.income-step-enabled').removeClass('hidden');
            }

            // Show/hide correct title
            if ($('[name="coapplicant"]:checked').val() == 'No' || ($('[name="employment-status"]:checked').val() == 'Employed' || $('[name="employment-status"]:checked').val() == 'Other')) {
                $('.income-step-title-normal').removeClass('hidden');
                $('.income-step-title-combined').addClass('hidden');
            } else {
                $('.income-step-title-normal').addClass('hidden');
                $('.income-step-title-combined').removeClass('hidden');
            }

            // Select minimum income
            if ($('[name="employment-status"]:checked').val() == 'Homemaker' || $('[name="employment-status"]:checked').val() == 'Student' || $('[name="employment-status"]:checked').val() == 'Unemployed') {
                INCOME_MIN = 1800;
            } else if ($('[name="employment-status"]:checked').val() == 'Self-Employed') {
                INCOME_MIN = 2200;
                if ($('[name="coapplicant"]:checked').val() == 'No') {
                    income_minimum_text = 'Self-employed applicants must make at least $2,200 to qualify';
                } else {
                    income_minimum_text = 'Self-employed applicants with co-signers must make a combined income of at least $2,200 to qualify';
                }
            } else if ($('[name="employment-status"]:checked').val() == 'Retired') {
                INCOME_MIN = 2000;
                if ($('[name="coapplicant"]:checked').val() == 'No') {
                    income_minimum_text = 'Retired applicants must make at least $2,000 to qualify';
                } else {
                    income_minimum_text = 'Retired applicants with co-signers must make a combined income of at least $2,000 to qualify';
                }
            }

            // Check all inputs
            var $inputs = $(this).closest('.walkthrough-step').find('input,select');
            $inputs.each(function (id, el) {
                if (!$(el).val() && $(el).prop('required')) {
                    disabled = true;
                    // Special filters
                } else if ($(el).prop('type') == 'checkbox') {
                    if (!$(el).closest('.walkthrough-step').find('input:checked').length) {
                        disabled = true;
                        error_text = 'Please select at least one option';
                        return false;
                    }
                } else if ($(el).prop('type') == 'email') {
                    if (!email_format.test($(el).val())) {
                        disabled = true;
                        error_text = 'Please enter a valid email';
                        return false;
                    }
                } else if ($(el).prop('type') == 'tel') {
                    if (!phone_format.test($(el).val())) {
                        disabled = true;
                        error_text = 'Please enter a valid phone number';
                        return false;
                    }
                } else if ($(el).prop('name') == 'postal-code') {
                    if (!postal_code_format.test($(el).val())) {
                        disabled = true;
                        error_text = 'Please enter a valid postal code';
                        return false;
                    }
                } else if ($(el).prop('name') == 'birthdate') {
                    if (/\d+\/\d+\/\d{4}/.test($(el).val()))
                    {
                    }else
                    {
                        disabled = true;
                        error_text = 'Please enter a valid date of birth';
                        return false;
                    }
                    var birthdate = Date.parse($(el).val());
                    var today = new Date();
                    today = today.getTime();
                    var delta = today - birthdate;
                    var age = delta / 3600 / 24 / 365 / 1000;
                    if (age < 18) {
                        disabled = true;
                        error_text = 'You must be at least 18 years old to apply.';
                        return false;
                    }
                } else if ($(el).prop('name') == 'income') {
                    var income = parseInt($(el).val());
                    // if (income < INCOME_MIN || isNaN(income)) {
                    //     disabled = true;
                    //     if (income_minimum_text) {
                    //         error_text = income_minimum_text;
                    //     } else {
                    //         error_text = 'Your income must be at least $' + INCOME_MIN + ' to apply.';
                    //     }
                    //     return false;
                    // }

                    if (income <= 2200) {
                        disabled = true;
                        if (income_minimum_text) {
                            error_text = income_minimum_text;
                        } else {
                            error_text = 'Your income must be at least $' + INCOME_MIN + ' to apply.';
                        }
                        return false;
                    }
                } else if ($(el).prop('name') == 'address') {
                    var address = $.trim($(el).val());
                    if (address == "") {
                        disabled = true;
                        error_text = 'Please enter a valid Street Address';
                        return false;
                    }
                } else if ($(el).prop('name') == 'city') {
                    var city = $.trim($(el).val());
                    if (city == "") {
                        disabled = true;
                        error_text = 'Please enter a valid City or Town name';
                        return false;
                    }
                } else if ($(el).prop('name') == 'current-address-years' || $(el).prop('name') == 'current-address-months') {
                    var val_address_y = $('[name="current-address-years"]').val();
                    var val_address_m = $('[name="current-address-months"]').val();

                    if (val_address_y == 0 && val_address_m == 0) {
                        disabled = true;
                        error_text = 'Please enter a valid Time';
                        return false;
                    }
                } else if ($(el).prop('name') == 'income-years' || $(el).prop('name') == 'income-months') {
                    var val_income_y = $('[name="income-years"]').val();
                    var val_income_m = $('[name="income-months"]').val();
                    if (val_income_y == 0 && val_income_m == 0) {
                        disabled = true;
                        error_text = 'Please enter a valid Time';
                        return false;
                    }
                }
				else if ($(el).prop('name') == 'lived-canada' ) {
					
						 var lived = $('[name="lived-canada"]:checked').val(); 
                         //alert(lived);
						  if(lived == 'No') {
							 
							 $('.lived-step-disabled').removeClass('hidden');
                			 $('.lived-step-enabled').addClass('hidden');
						  }
				}
                else if ($(el).prop('name') == 'budget') {
                    var budgetVal = $('[name="budget"]:checked').val();
                    if (budgetVal == "Under $250/month") {
                        disabled = true;
                        error_text = 'Apologies, we cannot approve anyone with a budget under $250/mo at this time.';
                        return false;
                    }
                }
            });


            $(this).closest('.walkthrough-step').find('.js-walkthrough-next').prop('disabled', disabled);
            $(this).closest('.walkthrough-step').find('.error-holder').text(error_text);
        });
    }

    // Tabs
    $('.js-tab').addClass('hidden').first().removeClass('hidden');
    $('.js-tab-button').first().addClass('active');
    $('.js-tab-button').on('click', function (e) {
        e.preventDefault();
        var id = $(this).attr('href');
        $('.js-tab').addClass('hidden');
        $(id).removeClass('hidden');
        $('.js-tab-button.active').removeClass('active');
        $(this).addClass('active');
    });

    // Sliders
    if ($('.testimonials-slider').length) {
        var slider = tns({
            container: '.testimonials-slider',
            slideBy: 'page',
            controlsPosition: 'bottom',
            controlsText: ['â€¹', 'â€º'],
            navPosition: 'bottom',
            autoplay: false,
        });
    }
    if ($('.vehicles-slider').length) {
        var vslider = tns({
            container: '.vehicles-slider',
            slideBy: 'page',
            controlsPosition: 'bottom',
            controlsText: ['â€¹', 'â€º'],
            nav: false,
            autoplay: true,
            autoplayButtonOutput: false
        });
        vslider.events.on('indexChanged', function (e) {
            var index = vslider.getInfo().index;
            var type = $('.vehicles-slider > li:eq(' + index + ') img').attr('id') || 'car';
            $('.js-vehicle-type').text(type);
        });
    }
    $('.js-walkthrough-setvehicle').on('click', function (e) {
        var index = vslider.getInfo().index;
        var type = $('.vehicles-slider > li:eq(' + index + ') img').attr('id') || 'car';
        $('.js-vehicle-type-input').val(type);
    });

    // Maps
    var $contactmap = $('.contact-map');
    if ($contactmap.length) {
        var lat = $contactmap.data('lat'),
                lng = $contactmap.data('lng');
        var mapOptions = {
            center: {lat: lat, lng: lng},
            zoom: 10,
            scrollwheel: false,
            disableDefaultUI: true,
            zoomControl: true,
            zoomControlOptions: {
                style: google.maps.ZoomControlStyle.SMALL,
                position: google.maps.ControlPosition.RIGHT_BOTTOM
            },
        };
        var map = new google.maps.Map($contactmap[0], mapOptions);
        // Set pin
        var marker = new google.maps.Marker({
            position: {lat: lat, lng: lng},
            map: map,
            icon: {
                url: THEME.TEMPLATE_URL + '/img/map-pin.svg',
                size: new google.maps.Size(125, 104),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(125, 80)
            },
        });
    }

    // Vehicle map
    var $vehicleMap = $('.vehicle-map');
    if ($vehicleMap.length) {
        var lat = $vehicleMap.data('lat'),
                lng = $vehicleMap.data('lng');
        var mapOptions = {
            center: {lat: lat, lng: lng},
            zoom: 14,
            scrollwheel: false,
            disableDefaultUI: true,
            zoomControl: true,
            zoomControlOptions: {
                style: google.maps.ZoomControlStyle.SMALL,
                position: google.maps.ControlPosition.RIGHT_BOTTOM
            },
        };
        var map = new google.maps.Map($vehicleMap[0], mapOptions);
        // Set pin
        var marker = new google.maps.Marker({
            position: {lat: lat, lng: lng},
            map: map,
            icon: {
                url: THEME.TEMPLATE_URL + '/img/map-pin.svg',
                size: new google.maps.Size(125, 104),
                origin: new google.maps.Point(0, 0),
                anchor: new google.maps.Point(125, 80)
            },
        });
    }
});