var value_locator = "#motor_deal_vehicle_attributes_value";
var year_locator = "#motor_deal_vehicle_attributes_year";
var make_locator = "#motor_deal_vehicle_attributes_make";
var family_locator = "#motor_deal_vehicle_attributes_family";
var model_locator = "#motor_deal_vehicle_attributes_model_and_series";
var body_type_container = "#body_type";
var body_type_locator = "#motor_deal_vehicle_attributes_body_type";
var registration_type_locator = "#motor_deal_vehicle_attributes_registration_type"
var bike_usage = ".bike_usage_select"
var extended_bike_usage = "#extended_bike_usage";
var extended_bike_usage_show_flag = "#extended_bike_usage #always_show";

var additional_rider_radio_locator = "#additional_rider input"
var additional_rider_false_locator = "#additional_rider_false"

var rider_questions_locator = ".rider_questions";
var one_rider_header_locator = ".rider .one_rider_header"
var two_rider_header_locator = ".rider .two_rider_header"
var rider_licence_question_text_locator = "label[for$='years_licence_held']";
var rider_1_questions_locator = "#rider_1 .rider_questions";
var rider_1_percentage_use_locator = "#rider_1_percentage_use"

var rider_2_section_locator = "#rider_2"

var facility_state_locator = "#motor_deal_facility_state"

var year = new DependentSelect(new YearBox());
var make = new DependentSelect(new MakeBox());
var family = new DependentSelect(new FamilyBox());
var model = new ModelSelect(new ModelBox());

$j(function() {
    $j(value_locator).bind("blur", updateRiderLicenceQuestionText);
    $j(body_type_locator).bind("change", updateRiderLicenceQuestion);
    $j(registration_type_locator).bind("change", updateRiderLicenceQuestion);
    $j(bike_usage).bind("change", showOrHideExtendedUsage);

    $j(year_locator).bind("change", year.onChange);
    $j(make_locator).bind("change", make.onChange);
    $j(family_locator).bind("change", family.onChange);
    $j(model_locator).bind("change", model.onChange);
    $j(additional_rider_radio_locator).each(function() {
        $j(this).bind("click", toggleAdditionalRiderDetails);
    });

    $j(rider_questions_locator).find("select.licence_question").each(function() {
        $j(this).bind("change", updateLastTwoYearAccidentsQuestion);
    });
    $j(rider_questions_locator).find("select.licence_question").each(function() {
        $j(this).change();
    });

    $j('#motor_deal_loan_contract_attributes_vehicle_value').val($j('#motor_deal_vehicle_attributes_value').val());

    toggleBodyType();
    toggleRiderLicenceQuestions($j(body_type_locator).val(), $j(registration_type_locator).val());
    showOrHideExtendedUsage();

    if (onlyOneRider()) {
        toggleAdditionalRiderDetails();
    }
});

function toggleBodyType() {
    if ($j(body_type_locator).find("option").size() > 2) {
        $j(body_type_container).show();
    } else {
        $j(body_type_container).hide();
    }
}

function showOrHideExtendedUsage() {
    if ($j(extended_bike_usage_show_flag).val() == 'true') {
        return false;
    }

    if ($j(bike_usage).val() == 'BUSINESS') {
        $j(extended_bike_usage).show();
    } else {
        $j(extended_bike_usage).hide();
    }
}

function updateRiderLicenceQuestion() {
    toggleRiderLicenceQuestions($j(body_type_locator).val(), $j(registration_type_locator).val());
    updateRiderLicenceQuestionText();
}

function toggleRiderLicenceQuestions(body_type, registration_type) {
    $j.get("/motor/riders/show_rider_licence_questions", {'vehicle[body_type]':body_type, 'vehicle[registration_type]':registration_type}, function(data) {
        var container_locator = (onlyOneRider() ? rider_1_questions_locator : rider_questions_locator);
        MotorcycleUtilities.toggleSectionAndClearValue($j(container_locator), data == 'true', ['select']);
    });
}

function updateRiderLicenceQuestionText() {
    var value = $j(value_locator).val();
    var year = $j(year_locator).val()
    var make = $j(make_locator).val()
    var family = $j(family_locator).val()
    var body_type = $j(body_type_locator).val()

    if (value == '' || year == '' || make == '' || family == '' || body_type == '') {
        return;
    }

    $j.get("/motor/riders/years_licence_held_question", {'vehicle[value]':value, 'vehicle[year]':year, 'vehicle[make]':make, 'vehicle[family]':family, 'vehicle[body_type]':body_type}, function(data) {
        $j(rider_licence_question_text_locator).text(data);
    });
}


function updateLastTwoYearAccidentsQuestion() {
    var parent = $j(this).parents(".rider_questions");
    var licence_years = parent.find("select[name*=years_licence_held]").val();
    var total_accidents = parent.find("select[name*=total_number_of_accident]").val();

    if (licence_years == '' || total_accidents == '') {
        MotorcycleUtilities.toggleSectionAndClearValue(parent.find("div[id$=two_year_accidents_number]"), false, ['select']);
        return;
    }

    $j.get("/motor/riders/show_last_two_year_accidents_question", {licence_years:licence_years, total_accidents:total_accidents}, function(data) {
        MotorcycleUtilities.toggleSectionAndClearValue(parent.find("div[id$=two_year_accidents_number]"), data == 'true', ['select'])
    });

}

function DependentSelect(thebox) {
    this.onChange = onChange;

    function onChange() {
        thebox.clear();
        $j.getJSON(thebox.url(), thebox.params(), function(data) {
            populate(data, thebox);
        });
    }

    function populate(data, thebox) {
        $j(thebox.dependent_field + " option").remove();
        if (data.length == 0) {
            $j(thebox.dependent_field).append("<option value=''>-</option>");
        } else {
            $j(thebox.dependent_field).append("<option value=''>Please Select</option>");

            data.each(function(obj) {
                var option = thebox.vehicle(obj.vms_vehicle);
                $j(thebox.dependent_field).append("<option value='" + option.value + "'>" + option.text + "</option>");
            });
        }
        $j(thebox.dependent_field).removeAttr("disabled");

        toggleRiderLicenceQuestions($j(body_type_locator).val(), $j(registration_type_locator).val());
    }
}

function ModelSelect(thebox) {
    this.onChange = onChange;

    function onChange() {
        thebox.clear();
        $j.getJSON(thebox.url(), thebox.params(), function(data) {
            populate(data, thebox);
        });
    }

    function populate(data, thebox) {
        $j(body_type_container).hide();
        $j(thebox.dependent_field + " option").remove();
        if (data.length > 1) {
            $j(thebox.dependent_field).append("<option value=''>Please Select</option>");
        }
        data.each(function(obj) {
            var option = thebox.vehicle(obj.vms_vehicle);
            $j(thebox.dependent_field).append("<option value='" + option.value + "'>" + option.text + "</option>");
        });
        $j(thebox.dependent_field).removeAttr("disabled");
        if (data.length > 1 && $j(model_locator).value != '') {
            $j(body_type_container).show();
        }

        toggleRiderLicenceQuestions($j(body_type_locator).val(), $j(registration_type_locator).val());
        updateRiderLicenceQuestionText();
    }
}

function YearBox() {
    this.dependent_field = make_locator;
    this.url = url;
    this.params = params;
    this.vehicle = vehicle;
    this.clear = clear;

    function url() {
        return "/motor/vehicle/make";
    }

    function params() {
        return {year: $j(year_locator).val(), deal_id: $j('#deal_id').val()};
    }

    function vehicle(vms_vehicle) {
        return {"value": vms_vehicle.make, "text": vms_vehicle.make};
    }

    function clear() {
        $j(body_type_container).hide();
        [make_locator, family_locator, model_locator, body_type_locator].each(function(locator) {
            clearSelect(locator);
        });
    }
}

function MakeBox() {
    this.dependent_field = family_locator;
    this.url = url;
    this.params = params;
    this.vehicle = vehicle;
    this.clear = clear;

    function url() {
        return "/motor/vehicle/family";
    }

    function params() {
        return {year: $j(year_locator).val(), make: $j(make_locator).val()};
    }

    function vehicle(vms_vehicle) {
        return {"value": vms_vehicle.family, "text": vms_vehicle.family};
    }

    function clear() {
        $j(body_type_container).hide();
        [family_locator, model_locator, body_type_locator].each(function(locator) {
            clearSelect(locator);
        });
    }
}

function FamilyBox() {
    this.dependent_field = model_locator;
    this.url = url;
    this.params = params;
    this.vehicle = vehicle;
    this.clear = clear;

    function url() {
        return "/motor/vehicle/model";
    }

    function params() {
        return {year: $j(year_locator).val(), make: $j(make_locator).val(), family: $j(family_locator).val()};
    }

    function vehicle(vms_vehicle) {
        return {"value": vms_vehicle.model + "|" + vms_vehicle.series, "text": vms_vehicle.model + " " + vms_vehicle.series};
    }

    function clear() {
        $j(body_type_container).hide();
        [model_locator, body_type_locator].each(function(locator) {
            clearSelect(locator);
        });
    }
}

function ModelBox() {
    this.dependent_field = body_type_locator;
    this.url = url;
    this.params = params;
    this.vehicle = vehicle;
    this.clear = clear;

    function url() {
        return "/motor/vehicle/body_type";
    }

    function params() {
        return {year: $j(year_locator).val(), make: $j(make_locator).val(), family: $j(family_locator).val(), model_and_series: $j(model_locator).val()};
    }

    function vehicle(vms_vehicle) {
        return {"value": vms_vehicle.body_type, "text": vms_vehicle.body_type};
    }

    function clear() {
    }
}

function clearSelect(locator) {
    $j(locator).attr("disabled", "disabled");
    $j(locator + " option").remove();
    $j(locator).append("<option value=''>-</option>");
}

function toggleAdditionalRiderDetails() {
    var showIt = !onlyOneRider();
    toggleHeaderOfRiders(!showIt);
    MotorcycleUtilities.toggleSectionAndClearValue($j(rider_2_section_locator), showIt, ["select", "input"]);
    MotorcycleUtilities.toggleSectionAndClearValue($j(rider_1_percentage_use_locator), showIt);
    toggleRiderLicenceQuestions($j(body_type_locator).val(), $j(registration_type_locator).val());
}

function toggleHeaderOfRiders(onlyOneRider) {
    if (onlyOneRider) {
        $j(one_rider_header_locator).show();
        $j(two_rider_header_locator).hide();
    } else {
        $j(one_rider_header_locator).hide();
        $j(two_rider_header_locator).show();
    }
}

function onlyOneRider() {
    return $j(additional_rider_false_locator).length == 0 || $j(additional_rider_false_locator).is(':checked');
}

function update_stamp_duty() {
    deal_id = $j('#deal_id').val();
    selected_state = $j(facility_state_locator).val();

    new Ajax.Request('/motor/deal_facilities/'+ deal_id + '/calculate_stamp_duty', {
        method: 'post',
        asynchronous:false,
        evalScripts:true,
        parameters: 'state=' + selected_state
    });
    
    registerToolTipEvents();
}

function cancel_facility_adjustment() {
    deal_id = $j('#deal_id').val();

    new Ajax.Request('/motor/deal_facilities/'+ deal_id + '/cancel', {
        method: 'get',
        asynchronous:true,
        evalScripts:true
    });
    tb_remove();
    registerToolTipEvents();
}
