/**
 * Handles functionality for the public facing LEED offset calculator.
 */

var ajax_url = '/leed-calculator-ajax.html?';
var leedType = [];

/**
 * Setup autocomplete fields and event handlers once the html has loaded
 */
$(document).ready(function() {
    $('a.help').click(function(event) {
        event.preventDefault();
    });
    $('.tool-tip').tooltip({
        effect: 'fade',
        offset: [0, 10],
        position: 'center right'
    }).dynamic();

    if ($('#form_city').length > 0) {
        var completerCity = $('#form_city').autocomplete(ajax_url + jQuery.param({action: 'city'}), {
            autoFill: true,
            dataType: 'json',
            parse: function(data) {
                var parsed = [];
                jQuery.each(data, function(index, item) {
                    parsed.push({
                        data: [item],
                        value: item,
                        result: item
                    });
                });
                return parsed;
            },
            highlight: function(value, term) {
                return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<span class=\"ac_highlight\">$1</span>");
            },
            max: 20,
            minChars: 1,
            multiple: false,
            mustMatch: false,
            scroll: true,
            selectFirst: true,
            extraParams: {
                action: 'city',
                state: $('#form_state').val()
            }
        });

        $('#form_state').change(function() {
            $('#form_city').val('');
            completerCity.setOptions({
                extraParams: {
                    action: 'city',
                    state: $(this).val()
                }
            });
        });
    }

    if ($('#form_leedtype').length > 0) {
        $('#form_leedtype').change(showAdditionalInputs);
        showAdditionalInputs();
    }

    if ($('#form_energy_model_yes').length > 0) {
        $('#form_energy_model_yes').click(showEnergyModel);
        $('#form_energy_model_no').click(showEnergyModel);
        showEnergyModel();
    }
});

/*
 * Toggle visibility on LEED type-dependent calculation input fields
 */
var showAdditionalInputs = function() {
    // Hide the input fields initially
    $('#form_energy_model_entry').hide();
    $('.leed-option').each(function(index, el) {
        $(el).hide();
    });

    // Request LEED type details from the server to determine which fields to show
    if ($('#form_leedtype').val() != '') {
        var request = jQuery.ajax({
            type: 'GET',
            url: ajax_url + jQuery.param({action: 'leed_type', leed_type: $('#form_leedtype').val()}),
            dataType: 'json',
            complete: function(response) {
                var data = jQuery.parseJSON(response.responseText);

                if (data.success) {
                    leedType = data.category;

                    if (leedType == 'EB' || leedType == 'EB OM') {
                        $('#form_eb_entry').show();
                    }

                    if (leedType == 'EB OM') {
                        $('#form_eb_om_entry').show();
                    }

                    if (leedType == 'NC 2.1') {
                        $('#form_nc2_1_entry').show();
                    }

                    if (leedType == 'Other') {
                        $('#form_other_entry').show();
                    }

                    if (leedType == 'CI') {
                        $('#form_ci_entry').show();
                    } else {
                        showEnergyModel();
                    }
                }
            }
        });
    }
}

/*
 * Toggle energy model fields
 */
var showEnergyModel = function() {
    $('#form_yes_entry').hide();
    $('#form_sqft_entry').hide();

    if (leedType) {
        switch (leedType) {
            case 'CS':
            case 'NC':
            case 'NC 2.2':
            case 'HC':
            case 'Schools':
            case 'Other':
                if ($('#form_energy_model_yes').prop('checked')) {
                    $('#form_yes_entry').show();
                } else if ($('#form_energy_model_no').prop('checked')) {
                    $('#form_sqft_entry').show();
                }
                $('#form_energy_model_entry').show();
        }
    }
}

/*
 * Confirmation messages, currently referenced using inline Javascript
 */
var confirmClear = function() {
    return confirm('Are you sure you want to clear all entered data?');
}

/*
 * Field validation, used with TemplateParser class
 */
var alertError = function() {
    $(window).load(function() {
        alert('Please ensure all of the required fields, marked in red, are properly filled in.');
    });
}

