Product = Class.create();
Product.prototype = {

    unit_price: 0,
    quantity: 1,
    price: 0,
    vat: 0,
    total: 0,
    quantity: 1,
    unit: "buc",
    rate: 1,
    currency_convert: 'RON',

    initialize: function () {
        this.containers = {
            sidebar: $('invoice-products-sidebar'),
            invoice: $('invoice-products')
        }
        this.templates = {
            sidebar: new Template('\
                <div class="product"> \
                    <h3><a href="javascript:">Produs #{crt}</a></h3> \
                    <ul class="invoice"> \
                        <li> \
                            <label> \
                                <strong>Denumire produs / serviciu</strong> \
                                <input type="text" class="text" name="name[]" value="#{name}" /> \
                            </label> \
                        </li> \
                        <li class="clear"> \
                            <div class="col"> \
                                <label> \
                                    <strong>Unitate de masura</strong> \
                                    <input type="text" class="text small" name="unit[]" value="#{unit}" /> \
                                </label> \
                            </div>\
                            <div class="col last"> \
                                <label> \
                                    <strong>Cantitate</strong> \
                                    <input type="text" class="text small" name="quantity[]" value="#{quantity}" /> \
                                </label> \
                            </div> \
                        </li> \
                        <li> \
                            <label> \
                                <strong>Pret unitar fara TVA</strong> \
                                <strong class="currency">#{currency}</strong> \
                                <input type="text" class="text medium" name="unit_price[]" value="#{unit_price}" /> \
                            </label> \
                            <p class="info"></p> \
                        </li> \
                        <li> \
                            <label> \
                                <strong class="invoice-product-total-label">Valoare totala fara TVA</strong> \
                                <strong class="currency">#{currency}</strong> \
                                <input type="text" class="text medium" name="price[]" value="#{price}" /> \
                            </label> \
                            <p class="info"></p> \
                        </li> \
                        <li class="invoice-product-vat-container"> \
                            <label> \
                                <strong>TVA</strong> \
                                <strong class="currency">#{currency}</strong> \
                                <input type="text" class="text medium" name="vat[]" value="#{vat}" /> \
                            </label> \
                            <p class="info"></p> \
                        </li> \
                        <li class="invoice-product-vat-container"> \
                            <label> \
                                <strong>Valoare totala + TVA</strong> \
                                <strong class="currency">#{currency}</strong> \
                                <input type="text" class="text medium" name="total[]" value="#{total}" /> \
                            </label> \
                            <p class="info"></p> \
                        </li> \
                        <li class="last clear"> \
                            <a href="javascript:" title="Sterge produs" class="option delete" style="float: right;">Sterge produs</a> \
                        </li> \
                    </ul> \
                </div>'
            ),
            invoice: new Template('\
                <tr> \
                    <td class="product-crt center">#{crt}</td> \
                    <td class="product-name">#{name}</td> \
                    <td class="product-unit">#{unit}</td> \
                    <td class="product-quantity center">#{quantity}</td> \
                    <td class="product-unit_price">#{unit_price}</td> \
                    <td class="product-price">#{price}</td> \
                    <td class="product-vat last">#{vat}</td> \
                </tr>'
            )
        }
    },

    insert: function () {
        this.containers.invoice.insert(this.templates.invoice.evaluate(this));
        this.containers.sidebar.insert(this.templates.sidebar.evaluate(this));

        this.elements = {
            sidebar: this.containers.sidebar.select('.product').last(),
            invoice: this.containers.invoice.select('tr').last()
        };

        this.ids = {
            sidebar: this.elements.sidebar.identify(),
            invoice: this.elements.invoice.identify()
        }

        this.openElement();
        this.attachEvents();
    },

    remove: function () {
        this.elements.sidebar.remove();
        this.elements.invoice.remove();
    },

    attachEvents: function () {
        this.elements.sidebar.down('h3').down('a').observe('click', (function () {
            this.openElement();
        }).bind(this));

        this.elements.sidebar.down('a.delete').observe('click', (function () {
            if (confirm("Sunteti sigur(a) ca doriti sa stergeti acest produs ?")) {
                this.invoice.removeProduct(this.ids.invoice);
            }
        }).bind(this));

        var product = this;

        ["name", "unit", "quantity", "unit_price", "total"].each((function (field) {
            this.elements.sidebar.down('input[name="'+ field +'[]"]').observe('keyup', function (event) {
                var codes = [Event.KEY_LEFT, Event.KEY_RIGHT, Event.KEY_UP, Event.KEY_DOWN, Event.KEY_TAB, Event.KEY_HOME];
                if (codes.member(event.keyCode)) {
                    return true;
                }
                
                product[field] = this.value;

                if (field == 'unit_price' || field == 'total' || field == 'quantity') {
                    if (product[field] && product[field] != '-') {
                        var negative = false;
                        if (product[field].charAt(0) == '-') {
                            negative = true;
                        }
                        
                        product[field] = product[field].replace(',','.');
                        
                        var value = "";
                        
                        if (isNaN(parseFloat(product[field]))) {
                            product[field] = 0;
                        }
                        
                        value = parseFloat(product[field]);
                        
                        var lastchar = product[field].charAt(product[field].length -1);
                        if( lastchar != '.' && lastchar != '0') {
                        
                        product[field] = (negative ? -1 : 1) * value;
                  
                        this.value = product[field];
                        }
                    } else {
                        product[field] = 0;
                    }
                }

                var element = product.elements.invoice.down('.product-' + field);
                if (element) {
                    element.update(this.value);
                }

                product.updatePrice(field);
            });
        }).bind(this));
    },

    updatePrice: function (field) {
        var fields  = [];
        
        this.quantity   = parseFloat(this.quantity);
        this.unit_price = parseFloat(this.unit_price);
        this.price      = parseFloat(this.price);
        this.total      = parseFloat(this.total);

        switch (field) {
            case 'total':
                this.price      = this.invoice.round(this.total / (1 + (this.vatRate / 100)));
                this.vat        = this.invoice.round(this.total - this.price);
                this.unit_price = this.invoice.round(this.price / this.quantity);

                fields = ['price', 'vat', 'unit_price'];
            break;
            default:
            case 'unit_price':
                this.price  = this.invoice.round(this.quantity * this.unit_price);
                this.vat    = this.invoice.round(this.price * (this.vatRate / 100));
                this.total  = this.invoice.round(this.price + this.vat);

                fields = ['price', 'vat', 'total'];
            break;
        }

        fields.each((function (field) {
            this.elements.sidebar.down('input[name="'+ field +'[]"]').value = this[field];
            var td = this.elements.invoice.down('.product-' + field);
            if (td) {
                td.update(this[field]);
            }
        }).bind(this));

        this.convertCurrency();
        this.invoice.updatePrice();
    },

    openElement: function () {
        if (!this.elements.sidebar.hasClassName('open')) {
            this.containers.sidebar.select('.product').invoke('removeClassName', 'open').invoke('addClassName', 'closed');
            this.elements.sidebar.removeClassName('closed').addClassName('open').down('input[name="name[]"]').focus();
        }
    },

    convertCurrency: function () {

        this.elements.sidebar.select('p.info').invoke('show');

        ["unit_price", "price", "vat", "total"].each((function (field) {
            var value = this.invoice.round(this[field] * this.rate);
            this.elements.sidebar.down('input[name="'+ field +'[]"]').up('label').next('p.info').update(value + ' ' + this.currency_convert);

            if (field != 'total') {
                this.elements.invoice.down('.product-' + field).update(value);
            }
        }).bind(this));

        if (this.currency == this.currency_convert) {
            this.elements.sidebar.select('p.info').invoke('hide');
        }
    },

    /**
     * Sets currency, updates labels
     */
    setCurrency: function (currency) {
        this.currency = currency;
        this.elements.sidebar.select('strong.currency').invoke('update', currency)
        this.convertCurrency();
    },

    /**
     * Sets global invoice currency, for conversions
     */
    setCurrencyConvert: function (currency) {
        this.currency_convert = currency;
        this.convertCurrency();
    },

    setCrt: function (crt) {
        this.crt = crt;
        this.elements.invoice.down('.product-crt').update(this.crt);
        this.elements.sidebar.down('h3').down('a').update("Produs " + this.crt);
    },

    setVAT: function (vat) {
        this.vatRate = vat;

        if (this.vatRate) {
            this.elements.sidebar.down('.invoice-product-total-label').update("Valoare totala fara TVA");
            this.elements.sidebar.select('.invoice-product-vat-container').invoke('show');
            this.elements.invoice.down('.product-vat').show();
        } else {
            this.elements.sidebar.down('.invoice-product-total-label').update("Valoare totala");
            this.elements.sidebar.select('.invoice-product-vat-container').invoke('hide');
            this.elements.invoice.down('.product-vat').hide();
        }

        this.updatePrice();
    },

    /**
     * Sets the rate at which the conversions will be made
     */
    setRate: function (rate) {
        rate = parseFloat(rate);
        if (isNaN(rate) == false ) {
            this.rate = rate;
        }
    },

    isValid: function () {
        if (!this.name) {
            return false;
        }
        if (!this.price) {
            return false;
        }

        return true;
    }
};