﻿var Brand = Class.create({
    initialize: function()
    {
        try {
            $$('input[id^=pack-]').each(function(e) {
                e.observe('click', function(event){
                    _form = event.target.form;
                    formId = _form.id.split('_')[1];
                    this.calculatePrice(formId, event.target);                    
                }.bind(this))
            }.bind(this))
        } catch(e) {return;}
        
        try {
            $$('input[id^=ship_method]').each(function(e) {
                e.observe('click', function(event){
                    _form = event.target.form;
                    formId = _form.id.split('_')[1];
                    target = this.getTargetElement(formId);                    
                    this.calculatePrice(formId, target);
                }.bind(this))
            }.bind(this))
        } catch(e) {return;}
    },

    getTargetElement: function(formId)
    {
        return $('form_' + formId).select("input[id^=pack-]:checked")[0];
    },

    getShippingMethod: function(formId)
    {
        return $('ship_method1_' + formId).checked ? 1 : 2;
    },

    calculatePrice : function(formId, target)
    {
        freeShippingAmount = parseFloat($('freeshippingamount_' + formId).value);
        price = parseFloat($('packprice-' + target.value).value);
        shippingMethod = this.getShippingMethod(formId);
        shippingPrice = shippingMethod == 1 ? parseFloat($('standard_price_' + formId).value) : parseFloat($('fast_price_' + formId).value);
                    
        if (price >= freeShippingAmount && shippingMethod == 1) {            
            shippingPrice = 'FREE';
        } else {
            price = parseFloat(price) + parseFloat(shippingPrice);
            shippingPrice = '$' + shippingPrice;
        }
        $('shipping_price_' + formId).update(shippingPrice);
        $('total_price_' + formId).update('$' + price);
    }
});
