
$(document).ready(function () {

    // address script
    var AddressExists = false;
    $('#addressDetails .appFormRow').each(function () {
        if ($(this).hasClass('error')) {
            AddressExists = true;
        }
    });
    if (AddressExists == false) {
        $('#addressDetails input:text').each(function () {
            if ($(this).val() != "") {
                AddressExists = true;
            }
        });
    }


    $('#addressLoaderGif').hide();
    if (AddressExists) {
        show_the_div($('#addressDetails'), true); // show addresses
        hide_the_div($('#addressSelector'), true);
    }
    else {
        hide_the_div($('#addressDetails'), true);
        hide_the_div($('#addressSelector'), true);
    }

    $('#findAddress').click(function (e) {// find address function
        e.preventDefault();
        var myAddress;
        var myPostcode;
        myPostcode = $('#postcode_lookup_field').val();
        myAddress = ADDRESSES_URL + escape(myPostcode);
        var parentRow = $('#postcode_lookup_field').parents('.appFormRow');
	// Clear any previous errors.
	parentRow.find('.errorlist').replaceWith("");

        //myAddress = (myPostcode);
        if (myPostcode != "") {
            $('#addressLoaderGif').show();
            $.getJSON(myAddress, function (data) {
                parentRow.removeClass('error');
                show_the_div($('#addressDetails'), true);
                myDataBlob = data;
                if (data.length <= 1) {
                    if (data.length == 0) {
                        $('#addressLoaderGif').hide();
                        parentRow.addClass('error');
                        if (parentRow.find('.errorlist').length > 0) {
                            parentRow.find('.errorlist').replaceWith("<ul class='clearBoth errorlist'><li>No address found, please enter an address below</li><ul>");
                        } else {
                            parentRow.append("<ul class='clearBoth errorlist'><li>No address found, please enter an address below</li><ul>");
                        }
                    } else {
                        hide_the_div($('#addressSelector'), true);
                        populateData(data, 0); // index of 0 single item
                    }
                } else {
                    $('#addressLoaderGif').hide();

                    var addressSelectBox = $('<select name="addressSelect" id="addressSelect"></select>');
                    addressSelectBox.append("<option value='-1'>-- Please select an address --</option>");

                    var index = 0;
                    $.each(data, function (i, item) {
                        addressSelectBox.append("<option value=" + index + ">" + item["addr1"] + "</option>");
                        index++; // used to select correct element of array
                    });

                    addressSelectBox.change(function () { // select an address
                        var myAddress;
                        $("#addressSelect option:selected").each(function () { //get the selected value
                            myAddress = $(this).val(); //assign it to the variable
                            populateData(myDataBlob, myAddress); // fill in the fields for address
                        });
                    });
                    $('#addressSelector .appFormField').html(addressSelectBox);
                    if ('function' == typeof nonIE6Function) {
                        addressSelectBox.selectmenu({ style: 'dropdown', maxHeight: 200 });
                    }
                    show_the_div($('#addressSelector'), true);
                }
            });
        } else { // no postcode entered
            parentRow.addClass('error');
            if (parentRow.find('.errorlist').length > 0) {
                parentRow.find('.errorlist').replaceWith("<ul class='clearBoth errorlist'><li>Please enter a postcode</li><ul>");
            } else {
                parentRow.append("<ul class='clearBoth errorlist'>Please enter a postcode</li><ul>");
            }
        } // end postcode check
        return false;
    }); // end find address
    
    

    function populateData(jsonData, needle) {
        if (needle >= 0) {
		$('#id_house_number').val(jsonData[needle]["number"]);
                $('#id_address1').val(jsonData[needle]["addr2"]);
                //$('#id_address2').val(jsonData[needle]["addr2"]);
                //$('#id_address3').val(jsonData[needle]["addr3"]);
                $('#id_town').val(jsonData[needle]["town"]);
                $('#id_county').val(jsonData[needle]["county"]);
            //$('#id_postcode').val(jsonData[needle]["postcode"]);
        }
        $('#addressLoaderGif').hide();
    }

    $("#id_date_of_birth").datepicker({ showOn: 'button', buttonImage: '/library/images/common/calender.gif', buttonImageOnly: true, onSelect: setDate2, dateFormat: 'd-m-yy', changeMonth: true, changeYear: true, beforeShow: function (input) { updateHiddenDateInput(input, 1) } });

    updateHiddenDateInput($("#id_date_of_birth"), 1);
    setMaxMinDates($("#id_date_of_birth"), 1);
	
	function setMaxMinDates(dateInput, longDates) {
        $(dateInput).each(function () {
            var day, month, year;
            var dates = ['day', 'mth', 'yr'];
            if (longDates) {
                dates = ['day', 'month', 'year'];
            }
            var minYear, maxYear;
            $(this).parents('.appFormRow').find('select[id$=' + dates[2] + '] option').each(function () {
                var val = parseInt($(this).val());
                if (!isNaN(val) && val >= 0) {
                    if ((minYear && minYear > val) || (!minYear)) {
                        minYear = val;
                    }
                    if ((maxYear && maxYear < val) || (!maxYear)) {
                        maxYear = val;
                    }
                }
            });

            $(this).datepicker('option', 'yearRange', minYear + ':' + maxYear);
        });
    }

    function updateHiddenDateInput(dateInput, longDates) {
        $(dateInput).each(function () {
            var day, month, year;
            var dates = ['day', 'mth', 'yr'];
            if (longDates) {
                dates = ['day', 'month', 'year'];
            }

            $(this).parents('.appFormRow').find('select').each(function () {
                if ($(this).attr('id').match(dates[0])) {
                    day = $(this).val();
                }
                if ($(this).attr('id').match(dates[1])) {
                    month = $(this).val();
                }
                if ($(this).attr('id').match(dates[2])) {
                    year = $(this).val();
                }
            });

            if (day && month && year) {
                var date = new Date();
                date.setFullYear(year, month - 1, day);
                $(this).datepicker('setDate', date);
            }
        });
    }

    function updateDateInputs(dateInput, longDates) {
        $(dateInput).each(function () {
            var dates = ['day', 'mth', 'yr'];
            if (longDates) {
                dates = ['day', 'month', 'year'];
            }

            var values = $(this).val().split('-');
            if (values.length == 3) {
                $(this).parents('.appFormRow').find('select').each(function () {

                    if ($(this).attr('id').match(dates[0])) {
                        $(this).val(values[0]).change();
                    }
                    if ($(this).attr('id').match(dates[1])) {
                        $(this).val(values[1]).change();
                    }
                    if ($(this).attr('id').match(dates[2])) {
                        $(this).val(values[2]).change();
                    }
                });
            }
        });
    }

    $("#id_date_of_birth").change(function () {
        updateDateInputs($(this), 1)
    });

    function setDate(text, control) {
        //
        // Text is the value selected by the user in the form d/m/yyyy
        // Control is the html input element, so we can use
        // the id value to select the drop downs.
        //
        var dt = text.split('-');
        $('#' + control.id + '_day').val(dt[0]).change();
        $('#' + control.id + '_mth').val(dt[1]).change();
        $('#' + control.id + '_yr').val(dt[2]).change();
    }

    function setDate2(text, control) {
        //
        // Text is the value selected by the user in the form d/m/yyyy
        // Control is the html input element, so we can use
        // the id value to select the drop downs.
        //
        var dt = text.split('-');
        $('#' + control.id + '_day').val(dt[0]).change();
        $('#' + control.id + '_month').val(dt[1]).change();
        $('#' + control.id + '_year').val(dt[2]).change();
    }
	
	

    // Set the models when a Vehicle make is chosen. 
    function updateVehicleModel(makeInput, keepValue) {
        $(makeInput).each(function () {
            var myMake;
            $('option:selected', this).each(function () {
                myMake = MODELS_URL + $(this).text();
            });

            var myModelID = this.id;
            var thelength = myModelID.length - 1;
            myModelID = myModelID.charAt(thelength); // get the last character of the id to select the model

            var newVehicleModelSelect = $('<select id="id_vehicle_model_' + myModelID + '" name="vehicle_model_' + myModelID + '"><option selected="selected" value="">- Select model -</option></select>');

            if ($(this).val() != "") {
                $('#loaderGif_vehicle_' + myModelID).css('display', 'inline');
                $.getJSON(myMake, function (data) {
                    $.each(data.models, function (i, item) {
                        newVehicleModelSelect.append("<option value=" + item["name"] + ">" + item["value"] + "</option>"); // raw html needed not "new option()  IE7 bug"
                    });
                    if (keepValue) {
                        newVehicleModelSelect.val($('#id_vehicle_model_' + myModelID).val());
                    }
                    $('#id_vehicle_model_' + myModelID).before(newVehicleModelSelect).remove();
                    if ('function' == typeof nonIE6Function) {
                        newVehicleModelSelect.selectmenu({ style: 'dropdown', maxHeight: 200 });
                    }

                    $('#loaderGif_vehicle_' + myModelID).hide(); //hide loader
                });
            } else {
                $('#id_vehicle_model_' + myModelID).before(newVehicleModelSelect).remove();
                if ('function' == typeof nonIE6Function) {
                    newVehicleModelSelect.selectmenu({ style: 'dropdown', maxHeight: 200 });
                }
                $('#loaderGif_vehicle_' + myModelID).hide(); //hide loader
            }
        });
    }

    for (n = 1; n <= 3; n++) {
        if ($('#id_vehicle_make_' + n)) {
            updateVehicleModel($('#id_vehicle_make_' + n), true);
            $('#id_vehicle_make_' + n).change(function () { // select make and model
                updateVehicleModel(this);
            });
        }
    }

});

