$(document).ready(function(){

// Javascript is running, so remove the notice
$("#no_js_notice").remove()

// Auto-clear and refill default value for tab name field
$("#merp_tab_form input[name='merp_tab_name']").focus(function(){
    if ($(this).attr('value') == 'New Reading Set') {
        $(this).attr('value', '')
    }
})
$("#merp_tab_form input[name='merp_tab_name']").blur(function(){
    if (!$(this).attr('value')) {
        $(this).attr('value', 'New Reading Set')
    }
})

// Clicking the printable button should setup a printer-friendly page
$("#merp_printable_form input[name='merp_printable']").click(function(){
    $("#merp_tabs div").each(function(){

        // Hide add row inputs
        // TODO: setup better DOM or find better way to exclude table inputs
        $(this).find('.merp_form input').css('display', 'none')
        $(this).find('.merp_table input').css('display', 'inline')

        // Hide actions column of rows
        $(this).find('.merp_table th:first').css('display', 'none')
        $(this).find('.merp_table tr').each(function(){
            $(this).find('td:first').css('display', 'none')
        })

        // Show tab (ends up showing all)
        $(this).css('display', 'block')
    })

    // Hide tab buttons
    $("#merp_tabs ul").css('display', 'none')

    // Hide add tab inputs
    $("#merp_tab_form input").css('display', 'none')

    // Show the revert button
    $("#merp_printable_form input[name='merp_revert']").css('display', 'inline')

    // Hide self
    $(this).css('display', 'none')

    // Don't let the form take us anywhere
    return false
})

// Do the opposite of the printable button
$("#merp_printable_form input[name='merp_revert']").click(function(){

    // Show everything again in the tabs
    $("#merp_tabs div").each(function(){
        // Show all inputs
        $(this).find('.merp_form input').css('display', 'inline')

        // Hide actions column of rows
        $(this).find('.merp_table th:first').css('display', 'table-cell')
        $(this).find('.merp_table tr').each(function(){
            $(this).find('td:first').css('display', 'table-cell')
        })
    })

    // Show add tab inputs
    $("#merp_tab_form input").css('display', 'inline')

    // Show the printable button
    $("#merp_printable_form input[name='merp_printable']").css('display', 'inline')

    // Show tab buttons
    $("#merp_tabs ul").css('display', 'block')

    // Select first tab
    $("#merp_tabs ul li:first button:first").click()

    // Hide self
    $(this).css('display', 'none')

    // Don't let the form take us anywhere
    return false
})

// Have a New Reading Set appended when the "add tab" button is clicked
$("#merp_tab_form input[name='merp_add_tab']").click(function(){
    $("#merp_tabs").append(merp_build_tab())

    // The tab name is supplied by an input text field
    var button = merp_build_tab_button($("#merp_tab_form input[name='merp_tab_name']").val());
    $("#merp_tabs ul").append(button)

    // Show the tab automatically
    // TODO: don't be lazy on the button selection
    $("#merp_tabs ul li:last button:first").click()

    // Don't let the form take us anywhere
    return false
})

})

// Builds and returns a new set of tab select/delete buttons
// @args name_text - the tab name
function merp_build_tab_button(name_text) {
    var new_b = merp_tab_button.clone()

    // When the tab select button is clicked show the appropriate tab and hide the rest
    // Also adds/removes color styling to indicate which tab is selected
    new_b.find("button[class='merp_select_tab']").click(function(){
        var index = $("#merp_tabs ul li").index($(this).parents('li')[0])
        var tab = $("#merp_tabs div:eq(" + index + ")")
        $("#merp_tabs div").each(function(i){
            $(this).parents('#merp_tabs').find('ul li:eq(' + i + ') button').removeClass('merp_tab_select')
            $(this).css('display', 'none')
        })
        $(this).addClass('merp_tab_select')
        tab.css('display', 'block')
        return false
    })

    // Apply color styling to the select button when being clicked
    // TODO: when the user mousedown, mouseout, and mouseon again
    // without ever mouseup, the color does not reappear but the
    // button is still live.
    new_b.find("button[class='merp_select_tab']").mousedown(function(){
        $(this).addClass('merp_tab_click')
    })
    new_b.find("button[class='merp_select_tab']").mouseup(function(){
        $(this).removeClass('merp_tab_click')
    })
    new_b.find("button[class='merp_select_tab']").mouseout(function(){
        $(this).removeClass('merp_tab_click')
    })

    // Add the tab's name to the select button
    new_b.find("button[class='merp_select_tab']").text(name_text)

    // Setup the delete button to completely remove its parent li
    // and the appropriate tab. Confirm with the user first!
    // If the currently selected tab was deleted display the
    // last in the remaining tab list
    // TODO: the select button is not identified when it is in the 
    // currently selected tab. A quick fix was to use :first
    // to select the button, but this is not reliable.
    new_b.find("button[class='merp_delete_tab']").click(function(){
        if (confirm('Delete the entire "'
            + $(this).parents('li').find('button:first').text()
            + '" tab?')) {
            var index = $("#merp_tabs ul li").index($(this).parents('li')[0])
            var tab = $("#merp_tabs div:eq(" + index + ")")
            tab.remove()
            if ($(this).parents('li').find('button:first').hasClass('merp_tab_select')) {
                $(this).parents('li').remove()
                $("#merp_tabs ul li:last button:first").click()
            }
            else {
                $(this).parents('li').remove()
            }
        }
    })

    // Apply color styling to the delete button when being clicked
    // TODO: when the user mousedown, mouseout, and mouseon again
    // without ever mouseup, the color does not reappear but the
    // button is still live.
    new_b.find("button[class='merp_delete_tab']").mousedown(function(){
        $(this).addClass('merp_tab_delete')
    })
    new_b.find("button[class='merp_delete_tab']").mouseup(function(){
        $(this).removeClass('merp_tab_delete')
    })
    new_b.find("button[class='merp_delete_tab']").mouseout(function(){
        $(this).removeClass('merp_tab_delete')
    })
    return new_b
}

// Builds and returns a new tab
function merp_build_tab() {
    var new_merp_tab = merp_tab.clone()

    // When the "add row" button is clicked append a new row
    // The new row's type (name) is obtained from an input text field
    new_merp_tab.find(".merp_form input[name='merp_add_row']").click(function(){
        row_type = $(this).parents('.merp_form').find("input[name='merp_type']").val()
        var new_merp_row = merp_build_row(row_type)
        $(this).parents(".merp_tab").find(".merp_table").append(new_merp_row)
        return false
    })

    // Auto-clear and refill default value for row type (name) field
    new_merp_tab.find(".merp_form input[name='merp_type']").focus(function(){
        if ($(this).attr('value') == 'New Reading') {
            $(this).attr('value', '')
        }
    })
    new_merp_tab.find(".merp_form input[name='merp_type']").blur(function(){
        if (!$(this).attr('value')) {
            $(this).attr('value', 'New Reading')
        }
    })   

    // Add on some default rows
    new_merp_tab.find(".merp_table").append(merp_build_row('Affected'))
    new_merp_tab.find(".merp_table").append(merp_build_row('Non-Affected'))
    new_merp_tab.find(".merp_table").append(merp_build_row('Equipment'))

    // Add in the tab name as a heading
    new_merp_tab.find('h2').text($('#merp_tab_form input[name="merp_tab_name"]').val())

    return new_merp_tab
}

// Builds and returns a new row
// @args type - the name of the row
function merp_build_row(type) {
    var new_merp_row = merp_row.clone()

    // When both input fields contain content calculate the MERP
    new_merp_row.find('input[name="merp_temp"]').keyup(function(){
        if ($(this).val() &&
            $(this).parents(".merp_row").find("input[name='merp_rh']").val()) {
            merp_calculate($(this).parents(".merp_row"))
        }
    })
    new_merp_row.find('input[name="merp_rh"]').keyup(function(){
        if ($(this).val() &&
            $(this).parents(".merp_row").find("input[name='merp_temp']").val()) {
            merp_calculate($(this).parents(".merp_row"))
        }
    })

    // When the delete button is clicked remove the appropriate row
    new_merp_row.find("td[class='merp_delete'] button").click(function(){
        $(this).parents('.merp_row').remove()
        return false
    })

    // Apply the name of the row to the type column
    new_merp_row.find("td[class='merp_type']").text(type)
    return new_merp_row
}

// The DOM structure for a New Reading Set
var merp_tab = $('<div class="merp_tab">\
        <form class="merp_form" action="#" method="post">\
            <h2></h2>\
            <input type="text" name="merp_type" value="New Reading" />\
            <input type="submit" name="merp_add_row" value="Add Reading" />\
            <table class="merp_table" cellpadding="0" cellspacing="0">\
                <tr>\
                    <th>Del</th>\
                    <th>Type</th>\
                    <th>Temp (&#176;F)</th>\
                    <th>RH</th>\
                    <th>GPP</th>\
                    <th>Total (h)</th>\
                    <th>Latent E.</th>\
                    <th>Sensible E.</th>\
                    <th>MERP</th>\
                </tr>\
            </table>\
        </form>\
    </div>')

// The DOM structure for a new row
var merp_row = $('<tr class="merp_row">\
                        <td class="merp_delete"><button>X</button></td>\
                        <td class="merp_type">?</td>\
                        <td class="merp_temp"><input type="text" name="merp_temp" size="4" /></td>\
                        <td class="merp_rh"><input type="text" name="merp_rh" size="4" /></td>\
                        <td class="merp_gpp">?</td>\
                        <td class="merp_total_h">?</td>\
                        <td class="merp_latent_e">?</td>\
                        <td class="merp_sensible_e">?</td>\
                        <td class="merp_value">?</td>\
                    </tr>')

// The DOM structure for a new button
var merp_tab_button = $('<li><button class="merp_select_tab"></button><button class="merp_delete_tab">X</button></li>')

// Takes a row, reads the inputs, calculates the merp, and populates the
// appropriate columns with the calculations.
// @args row - the row to calculate and populate
function merp_calculate(row) {
    var temp = parseFloat($(row).find("input[name='merp_temp']").val())
    var rh = parseFloat($(row).find("input[name='merp_rh']").val())

    var c = 5.0/9.0 * (temp-32.0)
    var d = rh * 6.11 * Math.pow(10, 7.5 * c/(237.7+c))
    var g = 0.6219 * d/(101325.0-d)

    var gpp = g * 7000.0
    var total_h = 0.24 * temp+g * (1061.0+0.45 * temp)
    var latent_e = g * 1061.0
    var sensible_e = total_h-latent_e
    var merp = (sensible_e * sensible_e)/(latent_e * 1061.0) * 1000.0

    $(row).find(".merp_gpp").text(gpp.toFixed(2))
    $(row).find(".merp_total_h").text(total_h.toFixed(2))
    $(row).find(".merp_latent_e").text(latent_e.toFixed(2))
    $(row).find(".merp_sensible_e").text(sensible_e.toFixed(2))
    $(row).find(".merp_value").text(merp.toFixed(2))
}
