$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

var app = {

    URL: {
        path: ''
    }
    
};


var Superbo = {

    URL: {
        path: ''
    }

};



var ShoppingCart = {


    init: function(el, opts) {

        this.opts = $.extend({},this.opts,opts);
        this.el = el;
        this.$el = $(el);

        this.initEventListeners();

        return this;

    },


    initEventListeners: function() {

        $('.cart-item input:text').change(function() {

            if($(this).val().match(/[0-9]+/)) {

                var itemid = $(this).attr('id').match(/[0-9]+/);

                ShoppingCart.updateItemQuantity(itemid, $(this).val());

            }

        });

        $('.increment').click(function() {

            var itemid = $(this).attr('id').match(/[0-9]+/);
            ShoppingCart.updateItemQuantity(itemid, ShoppingCart.getItemQuantity(itemid)+1);
            return false;

        });

        $('.decrement').click(function() {

            var itemid = $(this).attr('id').match(/[0-9]+/);
            ShoppingCart.updateItemQuantity(itemid, ShoppingCart.getItemQuantity(itemid)-1);
            return false;

        });

        $('.remove-item').click(function() {

            var itemid = $(this).attr('id').match(/[0-9]+/);
            ShoppingCart.removeItem(itemid);

        });


    },

    opts: {},

    getItemPrice: function(itemid) {

        return ShoppingCart.opts.items[itemid].price;

    },

    getItemQuantity: function(itemid) {

        return ShoppingCart.opts.items[itemid].quantity;

    },

    getSubtotal: function() {

        var subtotal = 0;

        for(var item in this.opts.items) {

            subtotal += parseFloat(this.opts.items[item].price * this.opts.items[item].quantity);

        }

        return subtotal.toFixed(2);

    },


    updateItemQuantity: function(itemid, value) {

        if(value < 1) {

            ShoppingCart.removeItem(itemid);

        }
        else {

            // Set the quantity
            ShoppingCart.opts.items[itemid].quantity = parseInt(value);

            // Update everything else
            ShoppingCart.outputItemQuantity(itemid);
            ShoppingCart.outputItemPrice(itemid);
            ShoppingCart.outputPriceSummary();


        }

        return this;

    },


    outputItemQuantity: function(itemid) {

        $('#cart-item-quantity'+itemid).val(ShoppingCart.getItemQuantity(itemid));

    },

    outputItemPrice: function(itemid) {

        var linePrice = this.getItemQuantity(itemid) * this.getItemPrice(itemid);

        $('#cart-item-price'+itemid).html(linePrice.toFixed(2));

    },

    outputPriceSummary: function() {

        var subtotal      = this.getSubtotal();

        var taxrate       = parseFloat(this.opts.taxrate);
        var divisor       = parseFloat((taxrate)/100 + 1);
        var nettotal      = parseFloat(subtotal/divisor).toFixed(2);
        var tax           = parseFloat(subtotal - nettotal).toFixed(2);
        var shippingprice = parseFloat(this.opts.shippingprice).toFixed(2);


        var total = (parseFloat(subtotal) + parseFloat(shippingprice)).toFixed(2);

        $('#taxrate').html(taxrate);
        $('#cart-tax').html(tax);
        $('#cart-shipping').html(shippingprice);
        $('#cart-subtotal').html(subtotal);
        $('#cart-total').html(total);


        return this;

    },



    removeItem: function(itemid) {

        if(confirm('Are you sure you want to remove this item?')) {

            $.post(app.URL.path+'/checkout/delete?id='+itemid, function() {

                $('#cart-item'+itemid).fadeOut();
                delete ShoppingCart.opts.items[itemid];
                ShoppingCart.outputPriceSummary();

                var empty = true;

                for(var item in ShoppingCart.opts.items) {

                    empty = false;
                    break;

                }

                if(empty) {

                    $('#cart-is-empty').show();
                    $('#cart-is-not-empty').hide();

                }

            });

            return true;

        }
        else {

            return false;

        }

    }

}





// khfForm
$.khfForm = function(el, opts){

    var base = this;

    base.$el = $(el);
    base.el = el;

    // Add a reverse reference to the DOM object
    base.$el.data("khfForm", base);

    base.init = function(){

        base.opts = $.extend({},$.khfForm.defaultOptions, opts);

        base.globalError = false;

        base.initEventListeners();

        return base;
    };


    base.initEventListeners = function() {

        base.$el.submit(function() {
            return base.onFormSubmit();
        });

        var fields = base.opts.fields;

        for(var f in fields) {

            var id = fields[f].id;

            base.$el.delegate('#'+id, 'change', function() {

                base.validateField(this);

            });

        }

    };


    base.addError = function(field) {

        var $el = $('#'+field.id);
        
        $el.parent()
            .addClass('error-field');

    };

    base.removeError = function(field) {

        var $el = $('#'+field.id);

        field.errortype = null;

        $el.parent()
            .removeClass('error-field');

    };

    base.renderErrors = function() {

        var fields  = base.opts.fields;
        var msg     = '';

        for(var f in fields) {

            var field = fields[f];

            if(field.errortype != undefined) {
                msg += '<li title="'+field.name+'">'+field.messages[field.errortype]+'</li>';
            }

        }

        msg = '<div class="box-error">There are few more bits of information we need:<br /><ul>'+msg+'</ul></div>';

        base.opts.hasOwnProperty('responseEl') ? base.$el.find(base.opts.responseEl).html(msg) : $('form-response').html(msg);

    };


    base.clearFields = function() {

        var fields = base.opts.fields;

        for(var f in fields) {

            base.$el.find('input[type=text]').val('');
            base.$el.find('select option:first-child').attr('selected', 'selected');

        }

    };


    base.onFormSubmit = function() {

        base.validateForm();

        var error = base.globalError;

        if(!error && base.opts.hasOwnProperty('submitMethod') && base.opts.submitMethod.toLowerCase() === 'ajax') {
            base.submitViaAjax();
            return false;
        }

        return !error;

    };

    base.submitViaAjax = function() {

        var $responseEl = $(base.opts.responseElement);

        $responseEl.html('<span class="loading">Submitting</span>');

        $.getJSON(Superbo.URL.path+base.opts.submitURL, base.$el.serialize(), function(j) {

            $responseEl.html(j.message);
            base.clearFields();

        });

    };


    base.validateField = function(elem) {

        var $elem       = $(elem);
        var id          = $elem.attr('id');
        var field       = base.opts.fields[id];


        if(field === undefined) {
            return;
        }

        var fieldValue  = $('#'+id).val();

        field.errortype = null;

        if(($elem).is(':visible')) {

            switch(field.type) {

                case 'email':
                    if(!fieldValue.match(/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i)) {
                        field.errortype = 'invalid';
                    }
                    break;

                case 'date':
                    if(!fieldValue.match(/^\d{1,2}\/\d{1,2}\/\d{4}/)) {
                        field.errortype = 'invalid';
                    }
                    break;

            }

            if(field.required && (!fieldValue.length || fieldValue === field.defaulvalue)) {
                field.errortype = 'required';
            }

        }


        if(field.errortype !== null) {

            base.addError(field);
            base.globalError = true;

        }
        else {

            base.removeError(field);

        }

    };

    base.validateForm = function() {

        var fields = base.opts.fields;

        base.globalError = false;

        for(var f in fields) {
            base.validateField($('#'+fields[f].id));

        }

        if(base.globalError) {
            base.renderErrors();
        }

        return base.globalError;

    };

    // Run initializer
    base.init();

};

$.khfForm.defaultOptions = {
    tipsyGravity: 'n'
};

$.fn.khfForm = function(opts){
    //return this.each(function(){
    return new $.khfForm(this, opts);
   // });
};
