function add_underlines() {
    // Input text fields share a class through all the application
    // except the ones in table cells, which have class TableUnderline.
    // We put the class in the code for those, and assign the class
    // dynamically for the rest to DRY the HTML.
    var fine_border_bottom = function (input) {
        var re = /underline/i; // underline, TableUnderline, TableUnderlineR
        if (!re.test(input.className)) {
            input.addClassName("underline");
        }
    };
    $$('input[type="text"]').each(fine_border_bottom);
    $$('input[type="password"]').each(fine_border_bottom);
}
Event.observe(window, 'load', add_underlines);

/*
  We turn autocompletion off in all text fields so that numbers,
  dates, invoice numbers, etc. do not interfere. This gives a clean
  data entry experience. Nevertheless, some text fields do want to
  have autocompletion on, and in that case they say so adding a class
  "autocomplete".

  We do not use the "autocomplete" attribute in source code because
  it is not in the standard and gives warnings in HTML validators.
*/
function turn_autocomplete_off() {
    $$('input[type="text"]').each(function (e) {
        if (!e.hasClassName('autocomplete'))
            e.setAttribute("autocomplete", "off");
    });
}
Event.observe(window, 'load', turn_autocomplete_off);

function set_default_maxlength() {
    var set_maxlength = function (input) {
        if (input.maxLength == -1)
            input.maxLength = 255;
    }
    $$('input[type="text"]').each(set_maxlength);
    $$('input[type="password"]').each(set_maxlength);
}
Event.observe(window, 'load', set_default_maxlength);

function ignore_newline(event) {
    var e = event || window.event;
    return e.keyCode == Event.KEY_RETURN ? false : true;
}

function add_new_line_to_invoice_on_return(e) {
    e = e || window.event;
    if (e.keyCode == Event.KEY_RETURN) {
        new Ajax.Request('/invoices/add_new_line', {asynchronous:true, evalScripts:true, parameters:Form.serialize('invoice-form')});
        return false;
    }
    return true;
}

function edit_invoice_header() {
    Effect.Fade('header-edition-switcher');
    Effect.Fade('invoice-header-left-show');
    Effect.Fade('invoice-header-right-show');
    Effect.Appear('invoice-header-left-edit', {queue: 'end'});
    Effect.Appear('invoice-header-right-edit', {queue: 'end'});
}

function register_checks(f, alert_plan, alert_terms) {
    if ( !plan_selected(f) ) {
        alert(alert_plan);
        return false;
    }

    if ( !acceptance_of_terms_of_service_checked(f) ) {
        alert(alert_terms);
        return false;
    }

    return true;
}


function acceptance_of_terms_of_service_checked(f) {
    return f.account_owner_accept_terms_of_service.checked;
}

function plan_selected(f) {
    var radios = $(f).select("input[id^='account_register_plan']");
    var radios_checked = radios.select(function(el){ return el.checked; });
    return (radios_checked.size() > 0);
}

/* Dynamically adjusts the size of a text-field to more or less fit its content, minimum size 3. */
function autofit(input) {
    input.size = Math.max(input.value.length+2, 5);
}

function check_availability_of_short_name(input) {
    new Ajax.Request('/public/check_availability_of_short_name', {asynchronous:true, evalScripts:true, parameters:"short_name=" + input.value});
}

/*
  If the users cancels creation errors shouldn't be there if he
  decides to pop up the form again later.
*/
function clean_errors_in_redbox(re) {
    $$('span.error').each(function (span) {
       if (span.id && re.test(span.id))
         span.update('');
    });
}

/* This test has been copied from prototype.js */
function explorer() {
    return (/MSIE/.test(navigator.userAgent) && !window.opera);
}

/* To be triggered when the date picker is shown. */
function hide_customer_selector_if_explorer() {
    if (explorer())
        $('invoice_customer_id').hide();
}

/* To be triggered when the date picker gets closed. */
function show_customer_selector_if_explorer() {
    if (explorer())
        $('invoice_customer_id').show();
}

/* To be triggered when the user choose to save an invoice draft */
function change_form_action_to(formAction, methodValue) {
    $('invoice-form').action = formAction;
    if (methodValue == 'put'){
        change_form_method_to(methodValue);
    }
    return true;
}

/* To be triggered when the user choose to save an invoice draft */
function change_form_method_to(methodValue){
    var form = $('invoice-form');
    var m = document.createElement('input');
    m.setAttribute('type', 'hidden');
    m.setAttribute('name', '_method');
    m.setAttribute('value', methodValue);
    form.appendChild(m);
}

var app = {
    /* Configuration variables first */
    spanish_taxes_date_change: '01/07/2010',
    check_spanish_taxes: true,

    validSpanishTaxes: function(){
        if (!this.check_spanish_taxes){
            return true;
        }

        var redbox_id = 'redbox-for-invalid-spanish-taxes';
        if (!$(redbox_id)){
            return true;
        }

        var invoice_date = $('invoice_date').value;
        if (invoice_date == undefined) {
            invoice_date = $('invoice_date').readAttribute('data-date');
        }

        var invoice_iva_name = $('invoice-iva-name').value;
        if (invoice_iva_name == undefined) {
            /* For show actions*/
            invoice_iva_name = $('invoice-iva-name').innerHTML;
        }

        var invoice_iva_percent = $('invoice-iva-percent').value;
        if (invoice_iva_percent == undefined) {
            /* For show actions*/
            invoice_iva_percent = $('invoice-iva-percent').innerHTML.gsub(/\D/, '');
        }
        
        if (!this.validateSpanishTaxes(invoice_date, invoice_iva_name, invoice_iva_percent)) {
            RedBox.showInline(redbox_id);
            RedBox.setWindowPositions();
            return false;
        }

        return true;
    },

    /* Depends on date.js */
    validateSpanishTaxes: function(date, ivaName, ivaPercent) {
        dateparsed = getDateFromFormat(date, "dd/MM/yyyy");
        deadline = getDateFromFormat(this.spanish_taxes_date_change, "dd/MM/yyyy");
        if (this.compareParsedDates(dateparsed, deadline) == 1) {
            if (ivaPercent == '18' || ivaPercent == '8' || ivaPercent == '4') {
                return true;
            } else {
                return !/^IVA$/i.test(ivaName);
            }
        } else {
            return true;
        }
    },

    compareParsedDates : function(date1, date2) {
        if (date1 == 0 || date2 == 0) {
            return -1;
        } else if (date1 >= date2) {
            return 1;
        }
        return 0;
    },

    /* Use in update customer to set the selected customer in the dropdown list*/
    setSelectedCustomer : function(customerId) {
        var selectField = $('invoice_customer_id');
        if (selectField){
            /* select the option with the customerId as value */
            var options = selectField.childElements();
            for (var index = 0; index < options.length; ++index) {
              var item = options[index];
              if(item.readAttribute('value') == customerId){
                  selectField.selectedIndex = index;
                  index = options.length;
              }
            }
        }
    }
};

document.observe("dom:loaded", function () {
    /* Validation of spanish taxes */
    $$('[rel=redbox]').each(function(elem) {
        if (elem.readAttribute('type') == 'submit') {
            elem.up('form').observe('submit', function(event) {
               if (!app.validSpanishTaxes()){
                   Event.stop(event);
               }
            });
        } else {
            elem.observe('click', function(event){
                if (!app.validSpanishTaxes()){
                   Event.stop(event); 
                }
            });
        }
    });

  // the element in which we will observe all clicks and capture ones originating from pagination links
  var container = $('list');

  if (container) {
    var img = new Image();
    img.src = '/images/spinner.gif';

    function createSpinner() {
        return new Element('img', { src: img.src, 'class': 'spinner' })
    }

    container.observe('click', function(e) {
        var el = e.element();

        /* pagination links */
        if (el.match('p.pagination.ajax a') || (el.up('a') && el.up('a').match('p.pagination.ajax a'))) {
            /* click in images */
            if (!el.match('a')) {
                el = el.up('a');
            }

            el.up('p.pagination.ajax').insert(createSpinner());
            new Ajax.Request(el.href, { method: 'get',
                asynchronous: true,
                onSuccess: function(response) {
                    scroll(0, 0);
                } 
            });
            e.stop();
        }

        /* table headers */
        if (el.match('a.ajax') || (el.up('a') && el.up('a').match('a.ajax'))) {
            /* click in images */
            if (!el.match('a')){
                el = el.up('a');
            }

            new Ajax.Request(el.href, { method: 'get',
                asynchronous: true,
                onSuccess: function(response) {
                    scroll(0, 0);
                }
            });
            e.stop();
        }
    })
  }
  /* end pagination links */  
});
