var text_fields = $('.option_text');

var ENDCAP_ERROR_LARGE_SIZE = 'Please contact us to special-order screens of this size.';
var ENDCAP_ERROR_SMALL_SIZE = 'Enter dimensions below';
var ENDCAP_ERROR_REQUIRE_MOTOR = 'Screens of this size require a motor. Please choose a drive option other than Manual.';

function get_dims() { // {{{
    var w = Number(text_fields[0].value);
    var h = Number(text_fields[1].value);
    if (isNaN(w) || isNaN(h) || w == 0 || h == 0) {
        w = 0;
        h = 0;
    }
    return [w, h];
} // }}}

function gromit_screen_price() { // {{{
    var dims = get_dims();
    w = dims[0]; h = dims[1];
    if (w > 0) w = qtr_inch(w) + 2.5;
    if (h > 0) h = qtr_inch(h) + 2.5;
    w /= 12; h /= 12;
    return w * h * unit_price;
} // }}}

function adjust_dims(dims) { // {{{
    // Dimensions input by the user must be rounded to the next quarter inch,
    // then adjusted based on which points the user measured from to attain
    // the final measurement
    w = dims[0]; h = dims[1];
    w = qtr_inch(w);
    h = qtr_inch(h);
    var width_dim = $('#po10')[0].value; // Width Dimension
    if (width_dim == 27) { // Inside of Track
        w = 3.25 + w + 3.25;
    }
    var height_dim = $('#po12')[0].value; // Height Dimension
    if (height_dim == 28) { // Daylight Opening
        var endcap_size = 0;
        if (w < 256.5) {
            if (h <= 91.5) endcap_size = 6.5;
            else if (h <= 163.5) endcap_size = 8;
            else if (h <= 233.5) endcap_size = 10;
            else if (h <= 310) endcap_size = 12;
        } else {
            if (h <= 207) endcap_size = 10;
            else if (h <= 285) endcap_size = 12;
        }
        h = h + 3.25 + endcap_size;
    }
    return [w, h]
} // }}}

function endcap_rolldown_price() { // {{{
    var dims = get_dims();
    dims = adjust_dims(dims);
    w = dims[0]; h = dims[1];
    // Screen price depends on adjusted dimensions rounded to the next 6 inches
    w = Math.ceil(w / 6) * 6;
    h = Math.ceil(h / 6) * 6;
    min_dims = endcap_rolldown_grid_minima();
    min_x = min_dims[0]; min_y = min_dims[1];
    if (w < min_x || h < min_y) {
        return [0, ENDCAP_ERROR_SMALL_SIZE];
    }
    if (grid[h] == undefined || grid[h][w] == undefined) {
        return [0, ENDCAP_ERROR_LARGE_SIZE];
    }
    var motor_required = grid[h][w].search(/\*/) > -1;
    var grid_price = Number(grid[h][w].replace('*',''));
    var motor_choice = $('#po15')[0].value; // Drive Option
    var motor = 0;
    switch(motor_choice) {
        case '34':
            motor = 0;
            if (motor_required) {
                return [0, ENDCAP_ERROR_REQUIRE_MOTOR];
            }
            break;
        case '37': motor = 515; break;
        case '38': motor = 590; break;
    }
    return grid_price + motor;
} // }}}

function endcap_rolldown_grid_minima() { // {{{
    var min_x = 32767;
    var min_y = 32767;
    for (var row in grid) {
        row = Number(row);
        if (row < min_y)
            min_y = row;
    }
    for (var col in grid[min_y]) {
        col = Number(col);
        if (col < min_x)
            min_x = col;
    }
    return [min_x, min_y];
} // }}}

function endcap_rolldown_grid_maxima() { // {{{
    max_x = 0;
    max_y = 0;
    for (row in grid) {
        row = Number(row);
        if (row > max_y)
            max_y = row;
    }
    for (col in grid[max_y]) {
        col = Number(col);
        if (col > max_x)
            max_x = col;
    }
    return [max_x, max_y];
} // }}}

function endcap_rolldown_read_grid() { // {{{
    var grid_div = $('#endcap_prices').text();
    var grid = {}
    var lines = grid_div.split(/(\r\n)+|\r+|\n+/);
    var header_line = lines.shift();
    var x_dims = header_line.replace(/^\t+/, '').split(/\t/);
    for (var y = 0; y < lines.length; y++) {
        if (lines[y] == undefined) {
            continue;
        }
        var row = lines[y].split(/\t/);
        var y_dim = row.shift();
        for (var x = 0; x < row.length; x++) {
            if (grid[y_dim] == undefined) {
                grid[y_dim] = {};
            }
            grid[y_dim][x_dims[x]] = row[x];
        }
    }
    return grid;
} // }}}

function qtr_inch(inches) {
    return Math.ceil(inches * 4) / 4;
}

function recalc_price() { // {{{
    formulas = {
        1: gromit_screen_price,
        2: endcap_rolldown_price
    }
    var result = formulas[product_id]();
    if (result instanceof Array) {
        var price = result[0];
        var message = result[1];
    } else {
        price = result;
    }
    if (price > 0) {
        var rounded_price = Math.round(price * 100) / 100
        if (String(rounded_price).replace(/^.*\./, '').length == 1)
            rounded_price = rounded_price + '0';
        $('.calc_price').text('$' + rounded_price);
    } else {
        if (message == undefined) {
            message = lbl_enter_dimensions;
        }
        $('.calc_price').text(message);
    }
} // }}}

function round_dims() { // {{{
    var w = Number(text_fields[0].value);
    var h = Number(text_fields[1].value);
    if (!isNaN(w)) text_fields[0].value = qtr_inch(w);
    if (!isNaN(h)) text_fields[1].value = qtr_inch(h);
    recalc_price();
} // }}}

var grid = {};
var endcap_check_options =  function() { // {{{
    var price_text = $('.calc_price').text();
    var has_price = price_text.match(/\$\d+/);
    if (FormValidation() && has_price) {
        document.orderform.submit();
    } else {
        if (price_text == ENDCAP_ERROR_LARGE_SIZE
                || price_text == ENDCAP_ERROR_SMALL_SIZE) {
            min = endcap_rolldown_grid_minima();
            max = endcap_rolldown_grid_maxima();
            alert(ENDCAP_ERROR_LARGE_SIZE + '\n'
                    + 'Screens smaller than ' + min[0] + '"x' + min[1] + '"'
                    + ' or larger than ' + max[0] + '"x' + max[1] + '"'
                    + ' are not available for online ordering.');
        } else if (price_text == ENDCAP_ERROR_REQUIRE_MOTOR) {
            alert(ENDCAP_ERROR_REQUIRE_MOTOR);
        } else {
            alert('You have chosen an invalid screen. Please check the size and try again.');
        }
    }
    return false;
} // }}}

$( function() {
    text_fields.after(' in.').keyup(recalc_price).change(round_dims);
    $('#po10').change(recalc_price); // Width Dimension
    $('#po12').change(recalc_price); // Height Dimension
    $('#po15').change(recalc_price); // Drive Option
    if (product_id == 2) {
        var submit_button = $('form[name=orderform] table.ButtonTable');
        submit_button.get(0).onclick = function() { return false; };
        submit_button.click(endcap_check_options);
        grid = endcap_rolldown_read_grid();
    }
});

