﻿
$(document).ready(function () {

    // hide the contact form initially
    $(function () {

        // Contact form
        $("#ContactForm").hide();
        $("#SuccessDialog").hide();
        $("#ErrorDialog").hide();

        // Competition Success Forms
        $("#CompetitionSuccessForm").hide();
        $("#CompetitionFailureForm").hide();

        $("#TellFriendSuccessDialog").hide();
        $("#TellFriendErrorDialog").hide();
        $("#ReserveVehicleForm").hide();

        // vehicle location more info form
        $("#MoreInfoForm").hide();

        // Tell a friend form
        $("#TellAFriendForm").hide();

        // control for all datepickers on the site
        $(".DateField").datepicker({
            showOn: "button",
            buttonImage: "/images/calendar.gif",
            dateFormat: 'dd/MM/yy',
            buttonImageOnly: true
        });

        // reservation form
        $("#ReserveSuccessDialog").hide();
        $("#ReserveErrorDialog").hide();
    });

    // extend the validator plugin
    jQuery.validator.addMethod("accept", function (value, element, param) {
        return value.match(new RegExp("^" + param + "$"));
    });

    jQuery.validator.addMethod("PhoneNumber", function (value, element, param) {
        return value.match(new RegExp("^" + param + "$"));
    });

    jQuery.validator.addMethod(
        "postcode",
        function (value, element, param) {
            return value.match(new RegExp("^" + param + "$"));
        });

    // Contact form
    $("#enquiryFormSubmit").click(function () {

        if ($("#commentForm").valid()) {

            // post the data, and submit the form
            PostContactFormData();
        }
        else {
            return false;
        }
    });

    // Tell a friend form
    $("#TellFriendSubmit").click(function () {

        if ($("#TellFriendForm").valid()) {

            // post the data, and submit the form
            PostTellFriendData();
        }
        else {
            return false;
        }
    });

    // Reserve Vehicle form
    $("#ReserveVehicleFormSubmit").click(function () {

        if ($("#ReservationForm").valid()) {
            // post the data, and submit the form
            PostReserveVehicleFormData();
        }
        else {
            return false;
        }
    });

    $(".PartExchangeContainerReserve").hide();

    $("#ShowPartExchangeReserve").click(function () {

        if ($("#ShowPartExchangeReserve").is(':checked')) {
            $(".PartExchangeContainerReserve").show("2500");
        }
        else {
            $(".PartExchangeContainerReserve").hide("2500");
        }
    });

    // Competition form
    $("#CompetitionFormSubmitButton").click(function () {

        if ($("#CompetitionForm").valid()) {

            // post the data, and submit the form
            PostCompetitionFormData();

            return false;
        }
    });
});


// ***************************
// *** No image functions ****
// ***************************
// Large No Image
function ImgErrorWidgetLarge(source) {
    source.src = "/images/NoCarImages/NormStyle/optimized/213x160.png";
    source.onerror = "";
    // add some styling to the element
    //$(source).attr("Style", "position:relative; left:20px;");
    return true;
}

// Medium No Image
function ImgErrorWidget(source) {
    source.src = "/images/NoCarImages/NormStyle/optimized/no_images_medium.png";
    source.onerror = "";
    // add some styling to the element
    $(source).attr("Style", "position:relative; left:20px;");
    return true;
}

// Small No Image
function ImgErrorWidgetSmall(source) {
    source.src = "/images/NoCarImages/NormStyle/optimized/no_images_small.png";
    source.onerror = "";
    return true;
}

// Super Small No Image
function ImgErrorWidgetReallySmall(source) {
    source.src = "/images/NoCarImages/NormStyle/optimized/150x113.png";
    source.onerror = "";
    return true;
}

// Missing image for the browse stock page
function ImgErrorWidgetBrowseStock(source) {
    source.src = "/images/NoCarImages/NormStyle/optimized/browseStockNoImage.png";
    // add some styling to the element
    $(source).attr("Style", "position:relative; left:20px; border:0");
    source.onerror = "";
    return true;
}

// Opens the contact More form
function OpenMoreInfoForm() {

    // unhide the div
    $("#MoreInfoForm").show();

    $("#MoreInfoForm").dialog({
        width: 350,
        height: 250,
        modal: true,
        resizable: true,
        draggable: false
    });
}

// Opens the Contact form
function OpenContactForm() {

    // untick the PX box if it is ticked
    if($("#ShowPartExchangeContact").is(':checked'))
    {
        $("#ShowPartExchangeContact").attr('checked', false);
        $(".PartExchangeContainerContact").hide(); 
    }

    // unhide the div
    $("#ContactForm").show();
	
	$("#ContactForm").dialog({
	    width: 756,
		modal: true,
		resizable: true,
		draggable: false
    });
}

// Opens the Contact form
function OpenValueMyVehicleForm() {

    OpenContactForm();

    // tick the px check box and show the PX field
    $("#ShowPartExchangeContact").attr('checked', true);
    $(".PartExchangeContainerContact").show(); 
}

// Opens the tell a friend form
function OpenTellAFriendForm() {

    // unhide the div
    $("#TellAFriendForm").show();

    $("#TellAFriendForm").dialog({
        height: 450,
        width: 700,
        modal: true,
        resizable: false,
        draggable: false
    });
}

// Opens the Contact form
function OpenReserveVehicleForm() {

    // unhide the div
    $("#ReserveVehicleForm").show();

    $("#ReserveVehicleForm").dialog({
        width: 750,
        modal: true,
        resizable: false,
        draggable: false
    });
}

// function to send the contact form
function PostContactFormData() {

    var formData = $("#commentForm").serialize();

    $.ajax({
        dataType: "json",
        type: "POST",
        url: "/ContactForm/SendEnquiry",
        data: formData,
        success: function (data) {

            // if the return data.Success was true
            if (data.Success == true) {
                // close the contact form
                $("#ContactForm").dialog('close');

                // the contact us enquiry was sent sucessfully - track this in alalytics
                _gaq.push(['_trackEvent', 'UserEnquiry', 'ContactUs']);

                // show a success form
                $("#SuccessDialog").show();
                $("#SuccessDialog").dialog({
                    modal: true,
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }
            else {
                // show a success form
                $("#ErrorDialog").show();
                $("#ErrorDialog").dialog({
                    modal: true,
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }

        },
        error: function (data) {
            //alert("fodder");
        },
        async: false,
        cache: false
    });

}

// function to send the tell a friend form
function PostTellFriendData() {

    var formData = $("#TellFriendForm").serialize();

    $.ajax({
        dataType: "json",
        type: "POST",
        url: "/ContactForm/TellAFriend",
        data: formData,
        success: function (data) {

            // any error message
            //alert("value is - " + data.ErrorMessage);

            // if the return value was true
            if (data.Success == true) {
                // close the contact form
                $("#TellAFriendForm").dialog('close');

                // the tell a friend was sent sucessfully - track this in alalytics
                _gaq.push(['_trackEvent', 'UserEnquiry', 'TellAFriend']);

                // show a success form
                $("#TellFriendSuccessDialog").show();
                $("#TellFriendSuccessDialog").dialog({
                    modal: true,
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }
            else {

                // alert the error
                //alert("value message is both - " + data.Success + " " + data.ErrorMessage);

                // show a success form
                $("#TellFriendErrorDialog").show();
                $("#TellFriendErrorDialog").dialog({
                    modal: true,
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }
        },
        error: function (data) {

            // alert the error
            //alert("Error - " + data.Success + " " + data.ErrorMessage);

        },
        async: false,
        cache: false
    });

}

// Post the competition form
function PostCompetitionFormData() {

    var formData = $("#CompetitionForm").serialize();

    $.ajax({
        dataType: "json",
        type: "POST",
        url: "/ContactForm/CompetitionEntry",
        data: formData,
        success: function (data) {


            if (data.Success == true) {

                // show a success form
                $("#CompetitionSuccessForm").show();
                $("#CompetitionSuccessForm").dialog({
                    modal: true,
                    buttons: {
                        Ok: function () {
                            // on OK click, close teh dialog and redirect to the competitions main page
                            $(this).dialog("close");
                            window.location = '/MotorpointCompetitions';
                        }
                    }
                });
            }
            else {
                // show a the failure form
                $("#CompetitionFailureForm").show();
                $("#CompetitionFailureForm").dialog({
                    modal: true,
                    closeOnEscape: false,
                    open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); },
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }


        },
        error: function (data) {
            //alert("fodder error");
        },
        async: false,
        cache: false
    });

}

// function to send the contact form
function PostReserveVehicleFormData() {

    var formData = $("#ReservationForm").serialize();

    $.ajax({
        dataType: "json",
        type: "POST",
        url: "/ContactForm/SecureReserveVehiclePost",
        data: formData,
        success: function (data) {


            //alert("The Success Value is " + data.Success);

            // if the return Success value was true
            if (data.Success == true) {
                // close the contact form
                $("#ReserveVehicleForm").dialog('close');

                // if the vehicle reservation was successful then log as a goal 
                _gaq.push(['_trackEvent', 'UserEnquiry', 'ReserveVehicle']);

                // show a success form
                $("#ReserveSuccessDialog").show();
                $("#ReserveSuccessDialog").dialog({
                    modal: true,
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");

                            // clear the form and redirect to the home page
                            $('#ReservationForm')[0].reset();
                            window.location = '/';
                        }
                    }
                });
            }
            else {
                // show an error form
                $("#ReserveErrorDialog").show();
                $("#ReserveErrorDialog").dialog({
                    modal: true,
                    buttons: {
                        Ok: function () {
                            $(this).dialog("close");
                        }
                    }
                });
            }

        },
        error: function (data) {
            //alert("fodder");
        },
        async: false,
        cache: false
    });

}

// function to change the style of the serach results - Cube or List
function ChangeSearchResultsView(ListView, XScrol, YScroll) {

    //alert(window.pageXOffset + " " + window.pageYOffset);
    //alert(XScrol + " - " + YScroll);
    //alert(XScrol + " - " + YScroll + " - " + ListView);

    $.ajax({
        dataType: "json",
        type: "GET",
        url: "/SearchBar/ChangeResultsView/" + ListView + "/" + XScrol + "/" + YScroll,
        error: function (data) {
            //alert("Error with grid view");
        },
        async: false,
        cache: false
    });

    // now refresh the current page
    window.location.reload(true);
}

// *******************************************************************
// *** functions to counter the multiple browser issues of page offsets
// *******************************************************************

function f_clientWidth() {
    return f_filterResults(
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function f_clientHeight() {
    return f_filterResults(
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}
function f_scrollLeft() {
    return f_filterResults(
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
    return f_filterResults(
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
