function select_all_bales(size, id, top_box_id)
{
    if ($(top_box_id).checked) {
        for (i = 0; i < size; i++) {
            $("" + id + i).checked = true
        }
    }
    else {
        for (i = 0; i < size; i++) {
            $("" + id + i).checked = false
        }
    }
}
function set_yards_per_piece_to_yards()
{
    document.getElementById("bale_yards_per_piece").value = document.getElementById("bale_yards").value;
}

function set_carton_total_yards_to_yard_0()
{
    var carton_yards = document.getElementById("carton_total_yards").value;
    if (document.getElementById('carton_no_of_pieces').value == "1") {
        document.getElementById("yards_0").value = carton_yards;
    }
}

function on_select(e)
{
    if (e.target.id.indexOf('selectable') != -1)
        select = 'selectable'
    else
        select = 'selected'
    if (e.shiftKey)
    {
        if (min_checked_ids[select] == -1)
        {
            min_checked_ids[select] = e.target.id
        }
        else
        {
            max_checked_ids[select] = e.target.id
            select_range(min_checked_ids[select], max_checked_ids[select], all_checkbox_ids[select])
        }
    }
    else
    {
        min_checked_ids[select] = e.target.id
    }
}

function select_range(min_checked_id, max_checked_id, all_checkbox_ids)
{
    var min_loc = find_location(min_checked_id, all_checkbox_ids)
    var max_loc = find_location(max_checked_id, all_checkbox_ids)
    if (min_loc > max_loc)
    {
        var temp
        temp = min_loc
        min_loc = max_loc
        max_loc = temp
    }

    for (i = min_loc; i <= max_loc; ++i)
    {
        document.getElementById(all_checkbox_ids[i]).checked = true
    }
}
function find_location(checked_id, all_checkbox_ids)
{
    for (i in all_checkbox_ids)
    {
        if (all_checkbox_ids[i] == checked_id)
            return i
    }
    return -1
}

function total_amount()
{
    var total_amount = 0
    var amounts = document.getElementsByName('amount')
    for (var count = 0; count < amounts.length; count++)
        total_amount = total_amount + to_number(amounts[count].innerHTML)
    return total_amount

}

function overlay() {
    el = document.getElementById("overlay");
    e2 = document.getElementById("split_carton_dialog");
    el.style.display = (el.style.display == "block") ? "none" : "block";
    e2.style.visibility = (e2.style.visibility == "visible") ? "hidden" : "visible";
    if (el.style.display == "block")
    {
        document.getElementById("roll_info").cells[0].focus();
    }
}

function render_overlay() {
    if ((document.getElementById('errors_for_total_yards_and_pieces').childNodes.length <= 1) && document.getElementById('carton_no_of_pieces').value > 1)
        display_overlay()
    else
        hide_overlay()
}

function display_overlay() {
    el = document.getElementById("overlay");
    e2 = document.getElementById("roll_info_table");
    el.style.display = "block";
    e2.style.visibility = "visible";
    document.getElementById("piece_no_0").focus();
}

function splitCartonConfirm()
{
    var checkboxes = Form.getInputs(document.rolls, "checkbox")
    var checked_count = 0
    for (var i = 0; i < checkboxes.length; i++)
    {
        checked_count += checkboxes[i].checked
    }

    if (checked_count == 0)
    {
        alert("Please select at least one piece");
        return false;
    }
    if (checked_count == checkboxes.length)
    {
        alert("Please leave at least one piece unselected to split out");
        return false;
    }
    return true;
}

function strip_customer_name(field)
{
    if (field.value != "No mat") {
        field.value = field.value.replace(/\(.*/, "").strip();
    }
    else
        field.value = ""
}

function view_print_invoice_with_condition(ship_to_order_present, invoice_id)
{
    var print_url
    if (ship_to_order_present)
        print_url = "/ship_to_order/print_invoice/" + invoice_id;
    else
        print_url = "/manual_invoice/print/" + invoice_id;
    print_popup = window.open(print_url);
    return false;
}

function print_invoice(source, invoice_id) {
    print_url = "/" + source + "/print/" + invoice_id;
    window.open(print_url);
    return false;
}

function view_print_invoice(id)
{
    var print_url = "/ship_to_order/print_invoice/" + id;
    window.open(print_url);
    return false;
}

function view_print_greige_goods_invoice(id)
{
    var print_url = "/greige_goods_ship_to_order/print_invoice/" + id;
    window.open(print_url);
    return false;
}
no_of_pieces = 1

function close_popup() {
    var send_alert = check_for_negative_and_blank();
    document.getElementById("errorMessagesForRolls").innerHTML = ""
    document.getElementById("errorMessagesForRolls").style.visibility = "hidden"
    no_of_pieces = document.getElementById('carton_no_of_pieces').value
    total_piece_yards = 0

    for (i = 0; i < no_of_pieces; i++) {
        total_piece_yards += parseFloat(document.getElementById('yards_' + i).value)
    }

    total_yards = document.getElementById('carton_total_yards').value
    if (total_piece_yards != total_yards)
    {
        send_alert[2] = 1
    }

    if (send_alert.indexOf(1) != -1)
    {
        write_errors_for_cartons(send_alert)
    }
    else
    {
        hide_overlay()
        javascript:scroll(0, 0)
        document.getElementById('carton_putup').focus()
        return true
    }
}

function check_for_negative_and_blank() {
    var piece_no = new Array(parseInt(document.getElementById('carton_no_of_pieces').value));
    var send_alert = new Array(4);
    send_alert[0] = 0
    send_alert[1] = 0
    send_alert[2] = 0
    send_alert[3] = 0
    no_of_pieces = document.getElementById('carton_no_of_pieces').value

    for (i = 0; i < no_of_pieces; i++) {
        if (document.getElementById('yards_' + i).value == "" || parseFloat(document.getElementById('yards_' + i).value) <= 0) {
            send_alert[0] = 1;
            document.getElementById('div_piece_yards_' + i).className = "fieldWithErrors"
        }
        else {
            document.getElementById('div_piece_yards_' + i).className = ""
        }
        if (document.getElementById('piece_no_' + i).value == "" || parseFloat(document.getElementById('piece_no_' + i).value) <= 0)
        {
            send_alert[1] = 1;
            document.getElementById('div_piece_no_' + i).className = "fieldWithErrors"
        }
        else
        {
            piece_no[i] = document.getElementById('piece_no_' + i).value
        }
    }

    piece_no_uniq = piece_no.uniq()
    if (piece_no_uniq.length != piece_no.length) send_alert[3] = 1;
    return send_alert
}

function write_errors_for_cartons(send_alert) {
    if (send_alert[0] != 0 || send_alert[1] != 0 || send_alert[2] != 0 || send_alert[3] != 0)
    {
        document.getElementById("errorMessagesForRolls").style.visibility = "visible"
        document.getElementById("errorMessagesForRolls").innerHTML = "<h2>Errors were found on this page</h2><p>There were problems with the following fields:</p>"
    }
    if (send_alert[0] == 1) {
        document.getElementById("errorMessagesForRolls").innerHTML = document.getElementById("errorMessagesForRolls").innerHTML + "<ul><li>Yards must be an integer greater than zero</li></ul>"
    }
    if (send_alert[1] == 1) {
        document.getElementById("errorMessagesForRolls").innerHTML = document.getElementById("errorMessagesForRolls").innerHTML + "<ul><li>Piece no must be an integer greater than zero</li></ul>"
    }
    if (send_alert[2] == 1) {
        document.getElementById("errorMessagesForRolls").innerHTML = document.getElementById("errorMessagesForRolls").innerHTML + "<ul><li>Sum of yards on rolls not equal to Total yards</li></ul>"
    }
    if (send_alert[3] == 1) {
        document.getElementById("errorMessagesForRolls").innerHTML = document.getElementById("errorMessagesForRolls").innerHTML + "<ul><li>Piece No. can't be same</li></ul>"
    }
}

function check_before_calling() {
    if (no_of_pieces == document.getElementById('carton_no_of_pieces').value)
    {
        display_overlay();
        return false
    }
    else
        return true
}

function hide_overlay() {
    el = document.getElementById("overlay");
    e2 = document.getElementById("roll_info_table");
    el.style.display = "none";
    e2.style.visibility = "hidden";

}

var last = -1

function on_shift_select(event, me, chk_bx_id) {
    if (!event) {
        event = window.event
    }
    var re = new RegExp(chk_bx_id + '(\\d+)');
    var num = parseInt(re.exec(me.id)[1]);
    if (event.shiftKey && last != -1) {
        var di = num > last ? 1 : -1

        for (var i = last; i != num; i += di) {
            el_id = "" + chk_bx_id + i;
            if (box = document.getElementById(el_id))
                box.checked = true;
        }
    }

    last = num;
}

function getObjectClass(obj)
{
    if (obj && obj.constructor && obj.constructor.toString)
    {
        var arr = obj.constructor.toString().match(/function\s*(\w+)/);

        if (arr && arr.length == 2)
        {
            return arr[1];
        }
    }

    return undefined;
}

function checkMutualExclusivity(check_box1, check_box2)
{
   cb1=$(check_box1);
   cb2=$(check_box2);
   if(cb1.checked && cb2.checked)
    {
        alert('Only one of package or freight can be selected');
        cb1.checked=false;
    }
}

var BillingDetails = function(buttonIDs, unitPricesSelector, disableControlID) {
  this.buttonIDs = buttonIDs;
  this.unitPricesSelector = unitPricesSelector;
  this.disableControl = $(disableControlID);

  this.initialize();
};

BillingDetails.prototype = {
  initialize: function() {
    this.verifyUnitPrices();

    var self = this;
    $$(this.unitPricesSelector).each(function(element) {
      Event.observe(element, 'change', (self.verifyUnitPrices).bind(self));
    });

    Event.observe(this.disableControl, 'click', (self.enableButtons).bind(self));
  },

  verifyUnitPrices: function() {
    if ( this.verifyUnitPricesAreInvalid() )
      this.disableButtons();
    else
      this.enableButtons();
  },

  verifyUnitPricesAreInvalid: function() {
    var values = $$(this.unitPricesSelector).collect(function(element) { return element.value;} );
    return ( values.any(function(val) { return val == 0; }) );
  },

  disableButtons: function() {
    this.buttonIDs.each(function(buttonID) { $(buttonID)['disabled'] = true; });
    this.disableControl.show();
  },

  enableButtons: function() {
    this.buttonIDs.each(function(buttonID) { $(buttonID)['disabled'] = false; });
    this.disableControl.hide();
  }
}
