﻿$(document).ready(function() {

    /* CHANGE VEHICLE BUTTON CLICK *******************************************************************
    When the 'change vehicle' button is clicked, remove the current das_vehicle cookie and
    show the other divs to allow the user to re-enter a new vehicle (registration / detail drill-down 
    */


    $("#btnChangeVehicle").bind("click", function() {
        deleteCookie('das_vehicle');
        clearSessionVariables();

        if ($("#regFind") != undefined) {
            $("#regFind").show();
        }
        if ($("#makeModelFind") != undefined) {
            $("#makeModelFind").show();
        }
        if ($("#yourVehicle") != undefined) {
            $("#yourVehicle").hide();
        }
        if ($("#vehicleDetails") != undefined) {
            $("#vehicleDetails").hide();
        }
    });


    /* VEHICLE MAKE SELECTION CHANGED **************************************************************** 
    When the 'make' dropdown list has another option selected, we want to get a new list of car models
    from the web service for the selected car make to populate the car model dropdown list. 
    */
    $("#make").bind("change", function() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "VehicleServices.asmx/MamGetCarModels",
            data: "{ carMake: '" + $("#make").val() + "' }",
            dataType: "json",
            beforeSend: function() {
                /* TODO: get rid of pathed image here and add a class to the div to show this progress gif instead */
                $('#loaderMake').empty().html('<img src="App_Themes/Skin_2/images/common/ajax-loader.gif" />');
            },
            success: function(mamCarModels) {
                /* Clear existing dropdown values */
                $("#model").find('option').remove();
                $("#submodel").find('option').remove();
                $("#engine").find('option').remove();
                $("#year").find('option').remove();

                /* add initial select value 'please select' */
                appendOptionToDropDownList('#model', "Please select");

                /* go through the returned list of car models and fill the 'Model' dropdown */
                $.each(mamCarModels.d, function(key, value) {
                    appendOptionToDropDownList('#model', value);
                });
            },
            error: function() {
                alert('error getting vehicle info (Models).');
                /* TODO: have a div I can fill in with some error text */
                $('#loaderMake').empty();
            },
            complete: function() {
                /* TODO: remove the class that shows the progress gif */
                $('#loaderMake').empty();
            }
        });
    });

    /* VEHICLE MODEL SELECTION CHANGED ****************************************************************
    When the 'model' dropdown list has another option selected, we want to get a new list of car sub-models (if any)
    from the web service for the selected car make to populate the car sub-model dropdown list. 
    */
    $("#model").bind("change", function() {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "VehicleServices.asmx/MamGetCarSubModels",
            data: "{carMake: '" + $("#make").val() + "'," + "carModel: '" + $("#model").val() + "' }",
            dataType: "json",
            beforeSend: function() {
                /* TODO: get rid of pathed image here and add a class to the div to show this progress gif instead */
                $('#loaderModel').empty().html('<img src="App_Themes/Skin_2/images/common/ajax-loader.gif" />');
            },
            success: function(mamCarSubModels) {
                /* Clear existing dropdown values that depend on the car model */
                $("#submodelContainer").remove();
                $("#engine").find('option').remove();
                $("#year").find('option').remove();

                if (mamCarSubModels.d.length > 0) {
                    /* if there are sub-models, create a new dropdown list and insert it beneath the model dropdown */
                    $('#divSubModel').append("<div id='submodelContainer'><label for='submodel'>Sub Model</label><select id='submodel' name='submodel' onchange='setCarEnginesDropDown();'></select><div id='loaderSubModel'></div><br /></div>");

                    /* add initial select value 'please select' */
                    appendOptionToDropDownList('#submodel', "Please select");

                    /* go through the returned list of sub-models and fill the 'submodel' dropdown */
                    $.each(mamCarSubModels.d, function(key, value) {                        
                        appendOptionToDropDownList('#submodel', value);                        
                    });
                }
                else {
                    /* if there are no sub models, we can forget creating & populating the sub-models dropdown
                    and go straight on with calling the web service to get the available engine sizes */
                    setCarEnginesDropDown();
                }
            },
            error: function() {
                alert('error getting vehicle info (Sub Models).');
                /* TODO: have a div I can fill in with some error text */
                $('#loaderModel').empty();
            },
            complete: function() {
                /* TODO: remove the class that shows the progress gif */
                $('#loaderModel').empty();
            }
        });
    });


    /* VEHICLE ENGINE SELECTION CHANGED **************************************************************** 
    When the 'engine' dropdown list has another option selected, we want to get a new list of car years
    from the web service for the selected car engine to populate the car engine dropdown list. 
    */
    $("#engine").bind("change", function() {
        // set subModel to an emty string if it's undefined.
        var subModel = $("#submodel").val();
        if (subModel == undefined) {
            subModel = "";
        }

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "VehicleServices.asmx/MamGetCarYears",
            data: "{carMake: '" + $("#make").val() + "'," + "carModel: '" + $("#model").val() + "'," + "carSubModel: '" + subModel + "'," + "carEngine: '" + $("#engine").val() + "' }",
            dataType: "json",
            beforeSend: function() {
                /* TODO: get rid of pathed image here and add a class to the div to show this progress gif instead */
                $('#loaderEngine').empty().html('<img src="App_Themes/Skin_2/images/common/ajax-loader.gif" />');
            },
            success: function(mamCarYears) {
                /* Clear existing dropdown values */
                $("#year").find('option').remove();

                /* add initial select value 'please select' */
                appendOptionToDropDownList('#year', "Please select");

                /* go through the returned list of car models and fill the 'Model' dropdown */
                $.each(mamCarYears.d, function(key, value) {
                    appendOptionToDropDownList('#year', value);
                });
            },
            error: function() {
                alert('error getting vehicle info (Years).');
                /* TODO: have a div I can fill in with some error text */
                $('#loaderEngine').empty();
            },
            complete: function() {
                /* TODO: remove the class that shows the progress gif */
                $('#loaderEngine').empty();
            }
        });
    });


    // this is running on every page load at the moment.
    var cookie = getCookie('das_vehicle');

    /* if the vehicle cookie is available, display the vehicle details with the details div elements. */
    if (cookie != null) {

        if ($('#makeModelFind') != undefined) {
            $('#makeModelFind').hide();
        }
        if ($('#regFind') != undefined) {
            $('#regFind').hide();
        }

        var vehicleDetail;

        vehicleDetail = getVehicleCookieSubString(cookie, 'CarReg', '&');
        if (vehicleDetail == undefined) { vehicleDetail = 'NO REG'; }
        $('#yourReg').html(vehicleDetail);

        vehicleDetail = getVehicleCookieSubString(cookie, 'MamMake', '&');
        if (vehicleDetail == '') { vehicleDetail = 'N/A'; }
        $('#yourMake').html(vehicleDetail);

        vehicleDetail = getVehicleCookieSubString(cookie, 'MamModel', '&');
        if (vehicleDetail == '') { vehicleDetail = 'N/A'; }
        $('#yourModel').html(vehicleDetail);

        vehicleDetail = getVehicleCookieSubString(cookie, 'MamEngineSize', '&');
        if (vehicleDetail == '') { vehicleDetail = 'N/A'; }
        $('#yourEngine').html(vehicleDetail);

        vehicleDetail = getVehicleCookieSubString(cookie, 'RegisteredYear', '&');
        if (vehicleDetail == '') { vehicleDetail = 'N/A'; }
        $('#yourRegistered').html(vehicleDetail);

        vehicleDetail = getVehicleCookieSubString(cookie, 'Transmission', '&');
        if (vehicleDetail == '') { vehicleDetail = 'N/A'; }
        $('#yourTransmission').html(vehicleDetail);

        vehicleDetail = getVehicleCookieSubString(cookie, 'Colour', '&');
        if (vehicleDetail == '') { vehicleDetail = 'N/A'; }
        $('#yourColour').html(vehicleDetail);

        vehicleDetail = getVehicleCookieSubString(cookie, 'ManufacturedYear', '&');
        if (vehicleDetail == '') { vehicleDetail = 'N/A'; }
        $('#yourYear').html(vehicleDetail);

    }
    /* otherwise, there's no cookie so display the divs that allow a new vehicle lookup */
    else {

        if ($('#makeModelFind') != undefined) {
            $('#makeModelFind').show();
        }
        if ($('#regFind') != undefined) {
            $('#regFind').show();
        }
        if ($("#yourVehicle") != undefined) {
            $("#yourVehicle").hide();
        }
        if ($("#vehicleDetails") != undefined) {
            $("#vehicleDetails").hide();
        }

        /* retrieve car makes for initial 'Make' dropdown list */
        fillVehicleMakeDropdown();
    }

});


/*  
Function used to call our web service to go and get the appropriate vehicle data using 
the passed in registration number.
*/
function findCarByReg() {

    if (($("#registration").val() != '') && ($("#registration").val() != 'Enter Reg')) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "VehicleServices.asmx/GetVehicleInfo",
            data: "{ regNumber: '" + $("#registration").val() + "' }",
            dataType: "json",
            beforeSend: function() {
                /* TODO: get rid of pathed image here and add a class to the div to show this progress gif instead */
                $('#loaderReg').empty().html('<img src="App_Themes/Skin_2/images/common/ajax-loader.gif" />');
            },
            success: function(vehicle) {
                /* set the das_vehicle cookie on the client with the vehicle object returned */
                setVehicleCookie(vehicle);

                /* show the vehicle details divs and hide the find your vehicle divs*/
                if ($('#makeModelFind') != undefined) {
                    $('#makeModelFind').hide();
                }
                if ($('#regFind') != undefined) {
                    $('#regFind').hide();
                }
                if ($("#yourVehicle") != undefined) {
                    $("#yourVehicle").show();
                }
                if ($("#vehicleDetails") != undefined) {
                    $("#vehicleDetails").show();
                }

                /* populate the relevant fields to display car data from the returned vehicle object */
                /* NOTE: I believe the IE bug of everything disappearing occurs around setting the html elements here.*/
                $("#yourReg").html($("#registration").val());
                $("#yourMake").html(vehicle.d.Make);
                $("#yourModel").html(vehicle.d.Model);
                $("#yourEngine").html(vehicle.d.MamEngineSizeDisplay);
                $("#yourYear").html(vehicle.d.ManufacturedYear);
                $("#yourRegistered").html(vehicle.d.RegisteredYear);
                $("#yourTransmission").html(vehicle.d.Transmission);
                $("#yourColour").html(vehicle.d.Colour);

                _gaq.push(['_trackEvent', 'findMyCarByReg', 'clicked']);

                /* Force a refresh as the new cookie values need to be picked up by our session variables used in the xml package.
                We use the session variables in the title when viewing a set of sub-category images i.e. 'Brakes section for 
                [vehicle details stored in the session variables]. This also fixes the sub category links generated by the xml package
                if you select a new vehicle whilst looking within a category's page.  */
                //document.location.href = document.URL;

                var url = document.URL;
                if (url.indexOf('#') != -1) {
                    url = url.replace('#', '');
                }

                window.location.href = url;
            },
            error: function() {
                $('#noVehicle').fadeIn('slow', function() {
                    $('#noVehicle').delay(4000).fadeOut('slow', function() {
                    });
                });

                /* TODO: have a div I can fill in with some error text */
                $('#loaderReg').empty();
            },
            complete: function() {
                /* TODO: remove the class that shows the progress gif */
                $('#loaderReg').empty();
            }
        });
    }
    else {
        $('#noVehicle').fadeIn('slow', function() {
            $('#noVehicle').delay(4000).fadeOut('slow', function() {
            });
        });
    }
}

/* PROCESS VEHICLE DRILL DOWN **************************************************************************
Validates all the required vehicle detail dropdowns from the lookup control before adding the details
to the das_vehicle cookie.
*/
function processVehicleDrillDown() {
    var valid = true;

    if (($("#make").val() == undefined) || ($("#make").val() == "Please select") ||
            ($("#model").val() == undefined) || ($("#model").val() == "Please select") ||
            ($("#engine").val() == undefined) || ($("#engine").val() == "Please select") ||
            ($("#year").val() == undefined) || ($("#year").val() == "Please select")
        ) {
        valid = false;
    }

    if (valid) {
        SetVehicleCookieFromDrillDown();

        /* populate the relevant fields to display car data from the returned vehicle object */
        $('#yourReg').html('NO REG');
        $("#yourMake").html($("#make").val());
        $("#yourModel").html($("#model").val());
        $("#yourEngine").html($("#engine").val());
        $("#yourYear").html($("#year").val());
        $("#yourRegistered").html('N/A');
        $("#yourTransmission").html('N/A');
        $("#yourColour").html('N/A');

        /* show the vehicle details divs and hide the find your vehicle divs*/
        if ($('#makeModelFind') != undefined) {
            $('#makeModelFind').hide();
        }
        if ($('#regFind') != undefined) {
            $('#regFind').hide();
        }
        if ($("#yourVehicle") != undefined) {
            $("#yourVehicle").show();
        }
        if ($("#vehicleDetails") != undefined) {
            $("#vehicleDetails").show();
        }

        _gaq.push(['_trackEvent', 'findMyCarByDrilldown', 'clicked']);

        /* Force a refresh as the new cookie values need to be picked up by our session variables used in the xml package.
           We use the session variables in the title when viewing a set of sub-category images i.e. 'Brakes section for 
           [vehicle details stored in the session variables]. */

        var url = document.URL;
        if (url.indexOf('#') != -1) {
            url = url.replace('#', '');
        }

        window.location.href = url;
    }
    else {
        $('#noVehicle').fadeIn('slow', function() {
            $('#noVehicle').delay(4000).fadeOut('slow', function() {
            });
        });
    }
}


/* VEHICLE SUB-MODEL SELECTION CHANGED **************************************************************** 
When the 'submodel' dropdown list has another option selected, we want to get a new list of engine sizes
from the web service for the selected car sub-model to populate the engine dropdown list. 
*/
function setCarEnginesDropDown() {
    // set subModel to an emty string if it's undefined.
    var subModel = $("#submodel").val();
    if (subModel == undefined) {
        subModel = "";
    }

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "VehicleServices.asmx/MamGetCarEngines",
        data: "{carMake: '" + $("#make").val() + "'," + "carModel: '" + $("#model").val() + "'," + "carSubModel: '" + subModel + "' }",
        dataType: "json",
        beforeSend: function() {
            /* TODO: get rid of pathed image here and add a class to the div to show this progress gif instead */
            $('#loaderSubModel').empty().html('<img src="App_Themes/Skin_2/images/common/ajax-loader.gif" />');
        },
        success: function(mamCarEngines) {
            /* Clear existing dropdown values */
            $("#engine").find('option').remove();
            $("#year").find('option').remove();

            /* add initial select value 'please select' */
            appendOptionToDropDownList('#engine', "Please select");

            /* go through the returned list of car engines and fill the 'engine' dropdown */
            $.each(mamCarEngines.d, function(key, value) {
                appendOptionToDropDownList('#engine', value);
            });
        },
        error: function() {
            alert('error getting vehicle info (Engines).');
            /* TODO: have a div I can fill in with some error text */
            $('#loaderSubModel').empty();
        },
        complete: function() {
            /* TODO: remove the class that shows the progress gif */
            $('#loaderSubModel').empty();
        }
    });
}



/*
Populates the Vehicle Make dropdown on the vehicle lookup control.
*/
function fillVehicleMakeDropdown() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "VehicleServices.asmx/MamGetCarMakes",
        data: "{}",
        dataType: "json",
        beforeSend: function() {
            /* TODO: add a class to show a progress gif */
        },
        success: function(mamCarMakes) {
            /* Clear existing dropdown values */
            $("#make").find('option').remove();

            /* add initial select value 'please select' */
            appendOptionToDropDownList('#make', "Please select");

            /* go through the returned list of car makes and fill the 'Make' dropdown */
            $.each(mamCarMakes.d, function(key, value) {
                appendOptionToDropDownList('#make', value);
            });
        },
        error: function(err) {
            alert('error getting Car Make info.');
            /* TODO: have a div I can fill in with some error text */
        },
        complete: function() {
            /* TODO: remove the class that shows the progress gif */
        }
    });
}


/*
Appends an option to the passed in dropdown list with the passed in value.
*/
function appendOptionToDropDownList(dropdownlist, value) {

    if (value == 'All') {
        $(dropdownlist).
          append($("<option></option>").
          attr("value", '').
          text(value));
    }
    else {
        $(dropdownlist).
          append($("<option></option>").
          attr("value", value).
          text(value));
    }    
}

/*
Calls a web method to clear out the current session variables holding vehicle information.
*/
function clearSessionVariables() {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "VehicleServices.asmx/ClearSessionVariables",
        data: "{}",
        dataType: "json",
        beforeSend: function() {
            /* TODO: add a class to show a progress gif */
        },
        success: function() {
            window.location.href = "/";
        },
        error: function(err) {
            // just for debugging for now.
            alert('error clearing session variables.');            
        },
        complete: function() {
            /* TODO: remove the class that shows the progress gif */            
        }
    });
}

/*
** COOKIE FUNCTIONS ******************************************************************************************
*/

/*  
Sets the das_vehicle cookie on the client with the passed in vehicle object data. This data/cookie is needed
When the webquery xml package attempts to retrieve the vehicle part data 
*/
function setVehicleCookie(vehicle) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 1);

    var value = "&CarReg=" + vehicle.d.RegNumber +
                "&MamMake=" + vehicle.d.MamMake +
                "&MamModel=" + vehicle.d.MamModel +
                "&MamSubModel=" + vehicle.d.MamSubModel +
                "&MamEngineSize=" + vehicle.d.MamEngineSizeDisplay +
                "&RegisteredYear=" + vehicle.d.RegisteredYear +
                "&Transmission=" + vehicle.d.Transmission +
                "&Colour=" + vehicle.d.Colour +
                "&ManufacturedYear=" + vehicle.d.ManufacturedYear +
                "&Fuel=" + vehicle.d.Fuel;

    document.cookie = "das_vehicle" + "=" + value + ";expires=" + exdate.toUTCString();
}


/* 'FIND MY CAR' FROM LOOKUP DRILL DOWN **************************************************************** 
When the 'find my car' button is clicked on within the drill-down vehicle lookup, the values within the
dropdowns need to be taken and added within a new das_vehicle cookie (just like the VRM findMyCarByReg)
function except it won't have as many details.
*/
function SetVehicleCookieFromDrillDown() {    
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + 1);     

    // set subModel to an emty string if it's undefined.
    var subModel = $("#submodel").val();
    if (subModel == undefined) {
        subModel = "";
    }

    var value = "&MamMake=" + $("#make").val() +
                "&MamModel=" + $("#model").val() +
                "&MamSubModel=" + subModel +
                "&MamEngineSize=" + $("#engine").val() +
                "&RegisteredYear=" +
                "&Transmission=" +
                "&Colour=" +
                "&ManufacturedYear=" + $("#year").val() + 
                "&Fuel=";

    document.cookie = "das_vehicle" + "=" + value + ";expires=" + exdate.toUTCString();   
}


/* 
Gets the cookie we're asking for.
*/
function getCookie(cookie_name) {
    var results = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');

    if (results)
        return (unescape(results[2]));
    else
        return null;
}

/*
Deletes the specified cookie by setting the expiry date to the past.
*/
function deleteCookie(cookie_name) {
    var expireDate = new Date();
    expireDate.setTime(expireDate.getTime() - 1);

    document.cookie = cookie_name + "=;expires=" + expireDate.toUTCString();
}

/*
Gets a particular vehicle detail from the cookie.
*/
function getVehicleCookieSubString(cookie, vehicleDetail, endChar) {
    var startIndex;
    var endIndex;

    startIndex = cookie.indexOf(vehicleDetail);

    if (startIndex != -1) {
        startIndex += vehicleDetail.length + 1;

        if (endChar != '') {
            endIndex = cookie.indexOf(endChar, startIndex);
        }
        else {
            endIndex = cookie.length + 1;
        }

        return cookie.substring(startIndex, endIndex);
    }
}


/*
* Checks if the vehicle cookie is present for when user's are trying to view inside a category. If there
is no vehicle i.e. a vehicle hasn't been selected, an info window appears asking the user to select a vehicle.
*/
function checkVehicleSelected() {
    var cookie = getCookie('das_vehicle');
    
    /* If the cookie is not available, show the info tooltip to select a vehicle first. */
    if (cookie == null) {
        /*alert("NO VEHICLE SELECTED! THIS IS WHERE WE NEED TO TRIGGER OFF THE JQUERY POPUP USING SOMETHING LIKE App_Themes/Skin_2/images/common/select-car-m.gif");*/

        $('#noVehicle').fadeIn('slow', function() {
            $('#noVehicle').delay(4000).fadeOut('slow', function() {
            });
        });
        
    }
}


/*************************************************************************************************************/
