﻿$(function () {


    var postcodeFilter = /([A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2})/i;
    var emailFilter = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

    var startlat;
    var startlng;

    // Show a swipe event on swipe test
    //    $('#swipeme').swipe(function(evt, data) {
    //        $(this).html('You swiped <strong>' + data.direction + '</strong>!');
    //    });

    $('a[target="_blank"]').click(function () {
        if (confirm('This link opens in a new window.')) {
            return true;
        } else {
            $(this).removeClass('active');
            return false;
        }
    });
    // Page animation callback events
    $('#pageevents').
                    bind('pageAnimationStart', function (e, info) {
                        $(this).find('.info').append('Started animating ' + info.direction + '&hellip; ');
                    }).
                    bind('pageAnimationEnd', function (e, info) {
                        $(this).find('.info').append(' finished animating ' + info.direction + '.<br /><br />');
                    });
    // Page animations end with AJAX callback event, example 1 (load remote HTML only first time)
    $('#callback').bind('pageAnimationEnd', function (e, info) {
        if (!$(this).data('loaded')) {                      // Make sure the data hasn't already been loaded (we'll set 'loaded' to true a couple lines further down)
            $(this).append($('<div>Loading</div>').         // Append a placeholder in case the remote HTML takes its sweet time making it back
                            load('ajax.html .info', function () {        // Overwrite the "Loading" placeholder text with the remote HTML
                                $(this).parent().data('loaded', true);  // Set the 'loaded' var to true so we know not to re-load the HTML next time the #callback div animation ends
                            }));
        }
    });

    $("document").ready(function () {
        $(".mapHeader").click(function () {
            $("#geomap").hide();
            $('html,body').animate({ scrollTop: 0 }, 10);
            
        });

        $("select#location").change(function () {
            if ($(this).val() == "") {
                $("#showroomSubmit").fadeOut();
            }
            else {
                $("#showroomSubmit").fadeIn();
            }

        });

        $("#aboutCarCraftLnk").click(function () {
            jumpToElementAndShowIt($("#aboutCarCraftDiv"), 40);
        });
        $("#aboutCarCraftClose").click(function () {
            $("#aboutCarCraftDiv").hide();
            jumpToElementAndShowIt($("#home"), 0);
        });

        $("#minfo").click(function () {
            $("#gallery").hide();
            $("#horizontal-slide-example").hide();
            jumpToElementAndShowIt($("#aboutCarCraftDivcar"), 90)
        });

        $("#closeAboutCar").click(function () {
            $("#aboutCarCraftDivcar").hide();
            jumpToElementAndShowIt($("#gallery"), 0);
        });
        $("#closeAboutCarZoom").click(function () {
            $("#aboutCarCraftDivcar").hide();
            jumpToElementAndShowIt($("#horizontal-slide-example"), 0);
        });

        $("#SearchBoxForm").submit(function () {
            var lowPrice = $("#Price").val();
            var highPrice = $("#MaxPriceMobile").val();
            if (lowPrice != "Any" && highPrice != "Any") {
                if (parseInt(lowPrice) >= parseInt(highPrice)) {
                    alert("Min price cannot be greater than the max price");
                    return false;
                }
            }
        });

        $("#advancedSearch").click(function () {
            if ($(this).val() == "Advanced Search") {
                $("ul.advancedSearch").slideDown();
                $(this).val("Simple Search")
            }
            else {
                $("ul.advancedSearch").slideUp();
                $(this).val("Advanced Search")
                // Reset advanced fields
                $("#Fuel").html($("#Fuel").html());
                $("#Transmission").html($("#Transmission").html());
                $("#CO2").html($("#CO2").html());
                $("#InsuranceGroup").html($("#InsuranceGroup").html());
                $("#Mileage").html($("#Mileage").html());
                GetCarCount();
            }
        });

        if ($("#carCount").length) {
            GetCarCount();
            $("#Makes").change(function () { GetCarCount() });
            $("#Models").change(function () { GetCarCount() });
            $("#Price").change(function () { GetCarCount() });
            $("#MaxPriceMobile").change(function () { GetCarCount() });
            $("#Colour").change(function () { GetCarCount() });
            $("#Fuel").change(function () { GetCarCount() });
            $("#Transmission").change(function () { GetCarCount() });
            $("#CO2").change(function () { GetCarCount() });
            $("#InsuranceGroup").change(function () { GetCarCount() });
            $("#Mileage").change(function () { GetCarCount() });
        }

    });


    //    // Orientation callback event
    $('body').bind('turn', function (e, data) {
        $('#orient').html('Orientation: ' + data.orientation);
    });

    $("#Makes").change(function () {
        var Make = $(this).val();
        $.ajax(
        {
            url: "/Mobile/Models",
            type: "GET",
            data: "make=" + Make,
            cache: false,
            success: function (data) {
                $("#Models option").remove();
                $("#Models").addItems(data);
            }
        });
    });

    $(".directionBack").click(function () {
        $("#directions").hide();
        $(".showRoomBody").show();
    });

    //for part exchange page.
    $("#AppointmentDay").live("change", function () {
        var selectedDate = $(this).val();
        $.ajax(
        {
            url: "/Mobile/getBookingTime",
            type: "GET",
            data: "selectedDate=" + selectedDate,
            cache: false,
            success: function (data) {
                $("#bookAppointment option").remove();
                $("#bookAppointment").addItems(data);
            }
        });
    });

    //Custom function to create select list on the fly
    //$("#Model option").remove(); to remove the init list
    $.fn.addItems = function (data) {
        return this.each(function () {
            var list = this;
            $.each(data, function (index, itemData) {
                var option = new Option(itemData.Text, itemData.Value);
                list.add(option);
            });
        });
    };

    function autoFill(id, v) {
        $(id).css({ color: "#000" }).attr({ value: v }).focus(function () {
            if ($(this).val() == v) {
                $(this).val("").css({ color: "#999" });
            }
        })
        .blur(function () {
            if ($(this).val() == "") {
                $(this).css({ color: "#999" }).val(v);
            }
        });

    }

});

    function GetCarCount() {

        var formData = $("#SearchBoxForm").serialize();

        $.post("/used/carscount", formData, function (data) {

            $("#searchsubmit").attr("disabled", "");

            if (data != '') {
                $("#carCount").fadeOut("fast", function () {

                    $(this).html(data);

                    if (data == 'Available Cars: 0 - Select different criteria.') {
                        $("#searchsubmit").attr("disabled", "true");
                    }

                }).fadeIn("slow");
            }
            else {
                $("#carCount").empty();
            }
        });  //end post


    }



    var directionDisplay;
    var directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
    var map;
    var startpos;


    function geomap(lat, lng, description, jumpToMap) {
        var latlng = new google.maps.LatLng(lat, lng);
        var myOptions =
        {
            zoom: 12,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        map = new google.maps.Map($("#map_canvas").get(0), myOptions);
        directionsDisplay.setMap(map);
        directionsDisplay.setPanel(document.getElementById("dir_canvas"));


        var contentString = '<div id="content">' + '<p> ' + description + '</p>' + '</div>';

        var infowindow = new google.maps.InfoWindow(
        {
            content: contentString
        });

        var marker = new google.maps.Marker(
        {
            position: latlng,
            map: map,
            title: "Carcraft"
        });

        google.maps.event.addListener(marker, 'click', function () {
            infowindow.open(map, marker);
        });

        $(".getRouteButton").show().addClass('graybutton');
        if (jumpToMap == true) {
            jumpToElementAndShowIt($("#geomap"), -15);
        }
        
    }

    function jumpToElementAndShowIt(elementToJumpTo, additionalOffSet) {
        elementToJumpTo.show();
        var offSet = elementToJumpTo.offset().top + additionalOffSet;
        $('html,body').animate({ scrollTop: offSet }, 1);
    }



    var latitude, longitude, callback;

    function checkGeoLocation() {
        return navigator.geolocation;
    }
    function updateLocation(fn) {
        if (checkGeoLocation()) {
            callback = fn;
            navigator.geolocation.getCurrentPosition(savePosition);
            return true;
        }
        else {
            console.log('Device not capable of geo-location.');
            fn(false);
            return false;
        }
    }
    function savePosition(position) {
        latitude = position.coords.latitude;
        longitude = position.coords.longitude;
        if (callback) {
            callback(getLocation());
        }
    }
    function getLocation() {
        if (latitude && longitude) {
            return {
                latitude: latitude,
                longitude: longitude
            }
        } else {
            console.log('No location available. Try calling updateLocation() first.');
            return false;
        }
    }

    function getdirection(lat, lng) {

//                if ($("map_canvas").html() == null) {            
//                    geomap(lat, lng, '', false);
//                }

        updateLocation(function (coords) {
            if (coords) {
                latitude = coords.latitude;
                longitude = coords.longitude;
            } else {
                alert('Device not capable of geo-location.');
                latitude = 0;
                longitude = 0;
            }
        });

        //startlat and startlng are calculated on Moblie.Master
        startpos = new google.maps.LatLng(latitude, longitude);        
        endpos = new google.maps.LatLng(lat, lng);

        //demo
        //startpos = new google.maps.LatLng(37.7699298, -122.4469157);
        //endpos = new google.maps.LatLng(37.7683909618184, -122.51089453697205);


        var request = {
            origin: startpos,
            destination: endpos,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
        };

        directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                directionsDisplay.setDirections(response);
            }
        });


        $("#directions").show();
        $(".showRoomBody").hide();
    }
