// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
$j(document).ready(function(){
    $j('li.headlink').hover(function(){
        $j('ul', this).css('display', 'block');
    }, function(){
        $j('ul', this).css('display', 'none');
    });
    //	Code to handle report section
    $j('#stock_movement_delivery_date').datepicker({
        dateFormat: 'dd/mm/y'
    });
    $j('#sales_summary_start_date').datepicker({
        dateFormat: 'dd/mm/y'
    });
    $j('#sales_summary_end_date').datepicker({
        dateFormat: 'dd/mm/y'
    });
    $j('#report_start_date').datepicker({
        dateFormat: 'dd/mm/y'
    });
    $j('#report_end_date').datepicker({
        dateFormat: 'dd/mm/y'
    });
    $j("#add_customer_dialog").dialog({
        autoOpen: false,
        closeOnEscape: true,
        dialogClass: 'dialog_form',
        resizable: false,
        draggable: false,
        modal: true,
        width: 900
    });
    $j("#search_customer_dialog").dialog({
        autoOpen: false,
        closeOnEscape: true,
        dialogClass: 'dialog_form',
        resizable: false,
        draggable: false,
        modal: true,
        width: 900
    });
    $j("#payment_dialog").dialog({
        autoOpen: false,
        closeOnEscape: true,
        dialogClass: 'dialog_form',
        resizable: false,
        draggable: false,
        modal: true,
        width: 900,
        position: 'top'
    });
    $j("#search_product_dialog").dialog({
        autoOpen: false,
        closeOnEscape: true,
        dialogClass: 'dialog_form',
        resizable: false,
        draggable: false,
        modal: true,
        width: 900
    });
    $j("#receipt_dialog").dialog({
        autoOpen: false,
        closeOnEscape: false,
        dialogClass: 'dialog_form',
        resizable: false,
        draggable: false,
        modal: true,
        width: 600,
        position: ['left', 'top']
    });
    $j("#search_invoice_dialog").dialog({
        autoOpen: false,
        closeOnEscape: true,
        dialogClass: 'dialog_form',
        resizable: false,
        draggable: false,
        modal: true,
        width: 900
    });
    $j("#search_inventory_dialog").dialog({
        autoOpen: false,
        closeOnEscape: true,
        dialogClass: 'dialog_form',
        resizable: false,
        draggable: false,
        modal: true,
        width: 900
    });
    $j("#add_stock_movement_dialog").dialog({
        autoOpen: false,
        closeOnEscape: true,
        dialogClass: 'dialog_form',
        resizable: false,
        draggable: false,
        modal: true,
        width: 500
    });
    $j("#change_dialog").dialog({
        autoOpen: false,
        closeOnEscape: true,
        resizable: false,
        draggable: false,
        modal: true,
        width: 900
    });
});

function update_row(request){
    row_to_update = $j('#row_to_update').val();
    if (row_to_update != null) {
        if ($j('#' + row_to_update) != null) {
            $j('#' + row_to_update).html(request.responseText);
            new Effect.Highlight(row_to_update, {});
        }
    }
}

function checkall(){
    if ($j('#checkall_box')[0].checked) {
        jQuery.each($j(":checkbox"), function(){
            this.checked = true
        });
    }
    else {
        jQuery.each($j(":checkbox"), function(){
            this.checked = false
        });
    }
}

function check(){
    all_check = true;
    $j(":checkbox").each(function(){
        if (!this.checked && this.id != 'checkall_box') {
            all_check = false
        }
    })
    if (all_check) {
        $j('#checkall_box')[0].checked = true
    }
    else {
        $j('#checkall_box')[0].checked = false
    }
}

function lock_users(){
    $j('form')[0].action = "lock";
    $j('form')[0].submit();
}

function remove_item(item_id){
    if ($j(item_id) != null) {
        $j(item_id).remove();
    }
}

function clear_message(item_id){
    if ($j(item_id) != null) {
        $j(item_id).empty();
    }
}

//	Payment processing

function tidy_amount(input_field)
{
    var amount = $F(input_field) || 0;
    amount = parseFloat(amount);
    amount = amount.toFixed(2);
    $(input_field).value = amount;
    return amount;
}

function calculate_payment_amounts(){
    tidy_amount('payment_credit_amount');
    tidy_amount('payment_cash_amount');
    tidy_amount('payment_nets_amount');
    verify_non_cash_amounts();
    var paid_by_credit = $F('payment_credit_amount') || 0;
    var paid_by_cash = $F('payment_cash_amount') || 0;
    var paid_by_nets = $F('payment_nets_amount') || 0;
    var paid_by_deposit = 0
    if( $('payment_deposit_invoice_amount') != null )
    {
        paid_by_deposit = $F('payment_deposit_invoice_amount') || 0;
    }
    var total_paid = parseFloat(paid_by_deposit) + parseFloat(paid_by_credit) + parseFloat(paid_by_cash) + parseFloat(paid_by_nets);
    var total_due = $F('invoice_final_amount') || 0;
    var balance = total_due - total_paid;
    if (balance <= 0) {
        balance = 0;
    }
    balance = balance.toFixed(2);
    $("balance").update("$" + balance);
    $("display_total_paid").update("$" + total_paid);
    calculate_change();
}

function verify_non_cash_amounts(){
    var verified = false;
    verified = verify_nets_amount() && verify_credit_amount() && verify_deposit_amount();
    var paid_by_credit = $F('payment_credit_amount') || 0;
    var paid_by_nets = $F('payment_nets_amount') || 0;
    var paid_by_deposit = 0;
    if( $('payment_deposit_invoice_amount') != null )
    {
        paid_by_deposit = $F('payment_deposit_invoice_amount') || 0;
    }
    var total_paid = parseFloat(paid_by_credit) + parseFloat(paid_by_nets) + parseFloat(paid_by_deposit);
    var total_due = $F('invoice_final_amount') || 0
    if (total_paid > total_due) {
        verified = false;
        alert('Credit Card + Nets Amount + Deposit Amount More Than Total Due!');
    }
    else {
        verified = true;
    }
    return verified;
}

function verify_credit_amount(){
    var verified = false;
    var paid_by_credit = $F('payment_credit_amount') || 0;
    var total_due = $F('invoice_final_amount') || 0;
    if (parseFloat(paid_by_credit) > total_due) {
        verified = false;
        alert('Credit Card Amount More Than Total Due!');
    }
    else {
        verified = true;
    }
    return verified;
}

function verify_nets_amount(){
    var verified = false;
    var paid_by_nets = $F('payment_nets_amount') || 0;
    var total_due = $F('invoice_final_amount') || 0;
    if (parseFloat(paid_by_nets) > total_due) {
        verified = false;
        alert('Nets Amount More Than Total Due!')
    }
    else {
        verified = true;
    }
    return verified;
}

function verify_deposit_amount(){
    var verified = false;
    var paid_by_deposit = 0;
    if( $('payment_deposit_invoice_amount') != null )
    {
        paid_by_deposit = $F('payment_deposit_invoice_amount') || 0;
    }
    var total_due = $F('invoice_final_amount') || 0;
    if (parseFloat(paid_by_deposit) > total_due) {
        verified = false;
        alert('Deposit Amount More Than Total Due!');
    }
    else {
        verified = true;
    }
    return verified;
}

//  Calculating change is the way to verify the cash amount.
function calculate_change(){
    var paid_by_credit = $F('payment_credit_amount') || 0;
    var paid_by_cash = $F('payment_cash_amount') || 0;
    var paid_by_nets = $F('payment_nets_amount') || 0;
    var paid_by_deposit = 0;
    if( $('payment_deposit_invoice_amount') != null )
    {
        paid_by_deposit = $F('payment_deposit_invoice_amount') || 0;
    }
    var total_due = $F('invoice_final_amount') || 0
    var total_paid = parseFloat(paid_by_credit) + parseFloat(paid_by_cash) + parseFloat(paid_by_nets) + parseFloat(paid_by_deposit);
    var change = total_paid - total_due;
    if (total_paid <= total_due) {
        change = 0;
    }
    change = parseFloat(change);
    change = change.toFixed(2);
    $("display_change").update("$" + change);
}

function verify_payment_amount()
{
    tidy_amount('payment_credit_amount');
    tidy_amount('payment_cash_amount');
    tidy_amount('payment_nets_amount');
    return verify_sufficient_payment_amount();
}

//  This checks if payment amount is enough if payment is not a deposit.
function verify_sufficient_payment_amount(){
    var sufficient = false;
    deposit_checked = false;
    if($j('#payment_deposit')[0] != undefined)
    {
        deposit_checked = $j('#payment_deposit')[0].checked;
    }
    
    if (!deposit_checked) {
        var paid_by_deposit = 0;
        if( $('payment_deposit_invoice_amount') != null )
        {
            paid_by_deposit = $F('payment_deposit_invoice_amount') || 0;
        }
        var paid_by_credit = $F('payment_credit_amount') || 0;
        var paid_by_cash = $F('payment_cash_amount') || 0;
        var paid_by_nets = $F('payment_nets_amount') || 0;
        // paid_by_credit_note = $F('payment_nets_credit_note_amount') || 0;
        var total_paid = parseFloat(paid_by_credit) + parseFloat(paid_by_cash) + parseFloat(paid_by_nets) + parseFloat(paid_by_deposit);
        
        var invoice_final_amount = $F('invoice_final_amount');
        sufficient = (invoice_final_amount > total_paid) ? false : true;
        
        if (!sufficient) {
            alert('Payment Not Enough');
        }
        sufficient = sufficient && verify_non_cash_amounts();
    }
    else{
        var paid_by_credit = $F('payment_credit_amount') || 0;
        var paid_by_cash = $F('payment_cash_amount') || 0;
        var paid_by_nets = $F('payment_nets_amount') || 0;
        var total_paid = parseFloat(paid_by_credit) + parseFloat(paid_by_cash) + parseFloat(paid_by_nets);
        var invoice_final_amount = $F('invoice_final_amount');
        var overshoot = (invoice_final_amount <= total_paid) ? true : false;
        if(overshoot)
        {
            alert('Payment Is Equal Or Greater Than Invoice Final Amount! This is a DEPOSIT.');
            sufficient = false;
        }
        else
        {
            sufficient = true;
        }
    }
    return sufficient;
}

//    Once the payment screen is up, Issuing should be locked.
function lock_issuing(){
    // do something;
    return true;
}

function verify_if_added(product_code){
    added = false;
    // an assumption is made here.
    jQuery.each($j(".product_code"), function(){
        added = ((this.value == product_code) ? true : false) || added
    });
    if (added) {
        alert('This product has been added');
    }
    return !added;
}

//  Invoice Amounts

function calculate_invoice_amounts(){
    var final_amounts = [];
    var total_no_of_items = 0;
    var overall_discount = $F("invoice_overall_discount") || 0;
    var tax = $F("invoice_tax");
    var invoice_items = $$("tr.invoice_item"); //is this the best way to do this?
    invoice_items.each(function(item){
        // first step is to find the item number
        var item_number = null;
        var descendants = item.descendants();
        var new_final_amount = 0;
        
        var item_number_field = descendants.find(function(descendant){
            return (descendant.name == "item_number");
        })
        
        if (item_number_field != undefined) {
            item_number = $F(item_number_field);
            if (item_number != null) {
                // once we get the item_number, can find out if overall_discount is applied.
                // has_overall_discount = is_overall_discount(item_number);
                var has_overall_discount = true
                var final_amount = $F("invoice_item_" + item_number + "_final_amount");
                var quantity = parseInt($('invoice_item_' + item_number + '_quantity').value);
                total_no_of_items = total_no_of_items + quantity;
                if (has_overall_discount) {
                    new_final_amount = parseFloat(final_amount) * (100 - parseFloat(overall_discount)) / 100;
                }
                else {
                    new_final_amount = parseFloat(final_amount);
                }
                final_amounts.push(new_final_amount);
            }
        }
    }) // all the invoice items have been iterated through.
    var total_amount = final_amounts.inject(0, function(acc, n){
        return acc + n;
    })
    total_amount = total_amount.toFixed(2);
    total_amount = round_value_to_five(total_amount);
    $("display_total_amount").update("$" + total_amount);
    $("total_no_of_line_items").update(invoice_items.length);
    $("total_no_of_items").update(total_no_of_items);
    
    // Calculating tax amount.
    var total_amount_before_tax = (parseFloat(total_amount) * 100) / (100 + parseFloat(tax));
    var total_tax = total_amount - total_amount_before_tax.toFixed(2);
    $("display_tax_amount").update("$" + total_tax.toFixed(2));
    // End of section.   
}

function calculate_invoice_item_amount(item_number){
    // verify if item_number is an integer
    base_price = $('invoice_item_' + item_number + '_stated_price_per_item').value;
    actual_price_field = $('invoice_item_' + item_number + '_price_per_item');
    
    quantity = $('invoice_item_' + item_number + '_quantity').value;
	quantity = Math.round(quantity);
	$('invoice_item_' + item_number + '_quantity').value = quantity;
    // discount_type = $RF('invoice_item_' + item_number + '_discount_type_none', 'invoice_item[' + item_number + '][discount_type]');
    discount_type = $('invoice_item_' + item_number + '_discount_type');
    discount = $('invoice_item_' + item_number + '_discount');
    
    final_amount_field = $('invoice_item_' + item_number + '_final_amount');
    final_amount_field_shown = $('invoice_item_' + item_number + '_final_amount_shown');
    
    final_amount = 0;
    
    if (discount_type.value == "none") {
        final_amount = base_price * quantity;
        actual_price_field.value = base_price;
    }
    else {
        if (discount_type.value == "absolute") {
            final_amount = (base_price - discount.value) * quantity;
            actual_price_field.value = base_price - discount.value;
        }
        else 
            if (discount_type.value == "percent") {
                actual_price =  Math.round(base_price * (100 - discount.value));
                final_amount = Math.round(actual_price * quantity) / 100;
                actual_price_field.value = actual_price / 100;
            }
    }
    final_amount_field.value = final_amount;
    final_amount_field_shown.value = final_amount;
    calculate_invoice_amounts();
}

function changed_final_price(item_number){
    base_price = parseFloat($('invoice_item_' + item_number + '_stated_price_per_item').value);
    actual_price = parseFloat($('invoice_item_' + item_number + '_price_per_item').value);
    discount = $('invoice_item_' + item_number + '_discount');
    discount_type = $('invoice_item_' + item_number + '_discount_type');
    discount_type_absolute_text_field = $('invoice_item_' + item_number + '_discount_type_absolute');
    discount_type_percent_text_field = $('invoice_item_' + item_number + '_discount_type_percent');
    discount_type_none_radio = $('invoice_item_' + item_number + '_discount_type_none');
    if (base_price > actual_price) {
        discount.value = base_price - actual_price;
        discount_type.value = "absolute";
        discount_type_none_radio.checked = false;
        discount_type_absolute_text_field.value = discount.value;
        discount_type_percent_text_field.value = 0;
    }
    else 
        if (base_price <= actual_price) {
            discount_type_none_radio.checked = true;
            discount_type_absolute_text_field.value = 0;
            discount_type_percent_text_field.value = 0;
            discount.value = 0;
            discount_type.value = "none";
        }
    calculate_invoice_item_amount(item_number);
}

function round_value_to_five(value){
    var converted = parseFloat(value);
    var converted_int = parseInt(value);
    var decimal = (converted - parseInt(converted, 10));
    decimal = Math.round(decimal*100)/100
    var decimal_one = decimal * 10;
    var decimal_two = (decimal_one - parseInt(decimal_one, 10));
    var first_decimal_place = (decimal_one - decimal_two) * 10;
    var rounded_value = Math.round(decimal_two);
    var second_decimal_place = 0;
    if (rounded_value == 0 && decimal_two != 0) {
        second_decimal_place = 5;
    }
    else 
        if (rounded_value == 1) {
            second_decimal_place = 10;
        }
    var final_value = ((converted_int * 100) + first_decimal_place + second_decimal_place) / 100;
    return final_value;
}

//    To manage discounts in invoices

function set_discounts(item_number, field){
    discount_type_absolute_text_field = $('invoice_item_' + item_number + '_discount_type_absolute');
    discount_type_percent_text_field = $('invoice_item_' + item_number + '_discount_type_percent');
    discount_type_none_radio = $('invoice_item_' + item_number + '_discount_type_none');
    discount = $('invoice_item_' + item_number + '_discount');
    discount_type = $('invoice_item_' + item_number + '_discount_type');
    
    if (discount_type_none_radio.checked && field == 'none') {
        discount_type_absolute_text_field.value = 0;
        discount_type_percent_text_field.value = 0;
        discount.value = 0;
        discount_type.value = "none";
    }
    else 
        if (discount_type_absolute_text_field.value > 0 && field == 'absolute') {
            discount_type_none_radio.checked = false;
            discount_type_percent_text_field.value = 0;
            discount.value = discount_type_absolute_text_field.value;
            discount_type.value = "absolute";
        }
        else 
            if (discount_type_percent_text_field.value > 0 && field == 'percent') {
                discount_type_none_radio.checked = false;
                discount_type_absolute_text_field.value = 0;
                discount.value = discount_type_percent_text_field.value;
                discount_type.value = "percent";
            }
            else {
                discount_type_none_radio.checked = true;
                discount.value = 0;
                discount_type.value = "none";
            }
    calculate_invoice_item_amount(item_number);
}


function remove_invoice_item(invoice_item_id){
    if ($j('#' + invoice_item_id) != null) {
        $j('#' + invoice_item_id).empty();
    }
    calculate_invoice_amounts();
}

//    Used by price management module.
function remove_inventory_discount(){
    radio = $('inventory_discount_type_none');
    inventory_discount = $('inventory_discount')
    if (radio != null && radio.checked && inventory_discount != null) {
        inventory_discount.value = 0
    }
}

function $RF(el, radioGroup){
    if ($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    }
    else 
        if ($(el).tagName.toLowerCase() != 'form') {
            return false;
        }
    var checked = $(el).getInputs('radio', radioGroup).find(function(re){
        return re.checked;
    });
    return (checked) ? $F(checked) : null;
}

//	This is for the filtering of invoices.
function toggle_filter_input(){
    if ($j('#filter_by').val() == "status") {
        $j('#filter_text_input').hide();
        $j('#filter_select_input').show();
    }
    else {
        $j('#filter_text_input').show();
        $j('#filter_select_input').hide();
    }
}

//    Global variable
var check_before_leaving = true;

// TODO Clear forms // Specific inputs ?

Event.observe(window, 'load', function(){
    if ($('payment_dialog') != null) {
        Event.observe('payment_dialog', 'keypress', function(event){
            if (event.keyCode == 13) {
                Event.stop(event)
            }
        });
    }
    if ($('new_invoice') != null) {
        // Ensure that pressing enter for form elements will not cause a submit.
        Event.observe('new_invoice', 'keypress', function(event){
            if (event.keyCode == 13) {
                Event.stop(event)
            }
        });
        //  Ensure that there are items for the invoice.
        Event.observe('new_invoice', 'submit', function(event){
            invoice_items = $$("tr.invoice_item"); //is this the best way to do this?
            if (invoice_items.size() == 0) {
                alert("No Items Have Been Added");
                Event.stop(event);
            }
        });
        //  Ensure that there are items for the invoice.
        window.onbeforeunload = function(event){
            if (check_before_leaving) {
                check_before_leaving = true;
                return "You Are In The Midst Of Generating An Invoice.";
            }
        };
    }
});

//  To deal with credit notes.

function calculate_credit_note_item_amount(item_number)
{
    // verify if item_number is an integer
    base_price = $('credit_note_item_' + item_number + '_stated_price_per_item').value;
    actual_price_field = $('credit_note_item_' + item_number + '_price_per_item');
    original_quantity = $(item_number + '_quantity').value;
    quantity = $('credit_note_item_' + item_number + '_quantity').value;
	quantity = Math.round(quantity);
	if (quantity > original_quantity){
        quantity = original_quantity;
        alert('Quantity must be less than original quantity.');
	}
	$('credit_note_item_' + item_number + '_quantity').value = quantity;

    final_amount_field = $('credit_note_item_' + item_number + '_final_amount');
    final_amount_field_shown = $('credit_note_item_' + item_number + '_final_amount_shown');
    
    final_amount = 0;

    final_amount = quantity * actual_price_field.value;
    
    final_amount_field.value = final_amount;
    final_amount_field_shown.value = final_amount;
    calculate_credit_note_amounts();
}

function calculate_credit_note_amounts(){
    var final_amounts = [];
    var total_no_of_items = 0;

    var credit_note_items = $$("tr.credit_note_item"); //is this the best way to do this?
    credit_note_items.each(function(item){
        // first step is to find the item number
        var item_number = null;
        var descendants = item.descendants();
        var new_final_amount = 0;
        
        var item_number_field = descendants.find(function(descendant){
            return (descendant.name == "item_number");
        })
        
        if (item_number_field != undefined) {
            item_number = $F(item_number_field);
            if (item_number != null) {
                var final_amount = $F("credit_note_item_" + item_number + "_final_amount");
                var quantity = parseInt($('credit_note_item_' + item_number + '_quantity').value);
                total_no_of_items = total_no_of_items + quantity;
                new_final_amount = parseFloat(final_amount);
                final_amounts.push(new_final_amount);
            }
        }
    }) // all the invoice items have been iterated through.
    var total_amount = final_amounts.inject(0, function(acc, n){
        return acc + n;
    })
    
    total_amount = total_amount.toFixed(2);
    total_amount = round_value_to_five(total_amount);
    $("display_total_amount").update("$" + total_amount);
    $("total_no_of_line_items").update(invoice_items.length);
    $("total_no_of_items").update(total_no_of_items);
    
    // Calculating tax amount.
    var total_amount_before_tax = (parseFloat(total_amount) * 100) / (100 + parseFloat(tax));
    var total_tax = total_amount - total_amount_before_tax.toFixed(2);
    $("display_tax_amount").update("$" + total_tax.toFixed(2));
    // End of section.   
}

//  Printing functions()
function printDiv(divId)
{
    $j('#'+divId).removeClass("non_print_area");
    $j('#'+divId).addClass("print_area");
    window.print();
    $j('#'+divId).removeClass("print_area");
    $j('#'+divId).addClass("non_print_area");
}

