var Invoice = Class.create({
  
    line_item_number: 1,
    
    initialize: function(html, item) {
       this.line_item_html = html
       this.line_item_number = item
    },
    
    is_valid: function() {
      return ($F('InvoiceClientId') != '' && this.total() > 0)
    },
    
    validate: function() {
      
   
      if(this.is_valid())
      {
        Field.enable('save');
        $('note').style.display = 'none'
        return true
      }
      else
      {
         Field.disable('save')
         $('note').style.display = ''
         return false
      }
      
    },
    

    indexed_line_item_html: function() {
      return this.line_item_html.replace(/INDEX_ID/g, this.line_item_number)
    },
    
    add_line_item: function() {
      $('priser').insert(this.indexed_line_item_html())
      //$('Item'+String(this.line_item_number)+'Qty').focus()
      this.line_item_number++
      
    },
    
    remove_line_item: function(index) {
      Element.remove(index)
      this.refresh()
    },
    
    
    
    to_money: function(amount) {
      return Number(amount).toFixed(2) 
    },
    
    
    sub_total: function() {
     var In = this
     return $$('.item').inject(0, function(sum, row) {
      var qty = Number($F('Item' + row.id + 'Qty'))
      var price = Number($F('Item' + row.id + 'Price'))
      var line_total = qty * price
      $('Item' + row.id + 'Qty').value = In.to_money(qty)
      $('Item' + row.id + 'Price').value = In.to_money(price)
      $('Item' + row.id + 'Total').update('$' + In.to_money(line_total))
      return sum + line_total 
     })
    },
    
    tax: function() {
     var tax_rate = Number($F('InvoiceTaxRate')) 
     var taxable_amount = this.sub_total()
     tax_total = Math.round((tax_rate * 0.01 * taxable_amount) * 1000) / 1000
     return Math.round(tax_total * 100) / 100
    },
    
    total: function() {
       return this.sub_total() + this.tax()
    },
    
    refresh: function() {
     $('subtotal').update('$' + this.to_money(this.sub_total())) 
     $('total').update('$' + this.to_money(this.total())) 
     $('tax').update('$' + this.to_money(this.tax())) 
     this.validate();
    }
    
  
});

