var cartNotify = Class.create({
	initialize: function(options) {
        this.options = Object.extend({
            cart_box: 'cart-box',
            cart_items: 'cart-items',
            cart_link: 'cart-link',
            cart_qty_class: '.cart-qty',
            cart_message: 'cart-message',
		    add_message: this.wrapP(language_resource('The_following_added_to_cart_txt')),
		    delete_message: this.wrapP(language_resource('The_following_removed_from_cart_txt'))
        }, options || {});
		var self = this;
		document.observe('txn:altercart',function(evt){
			var data = new Array();
			evt.memo.each(function(item){
				var hacked = self.hackKeys(item);
	    		hacked.CALC = {
	    			QTY: item.ITEM_QUANTITY,
	    			formattedPrice: Number(item.APPLIED_PRICE).toCurrency()
	    		};
				data.push(hacked);
			});
			$(self.options.cart_message).innerHTML = self.options[data[0].action+'_message'];
			self.fillin(data).show();
		});
		document.observe('txn:error',function(evt){
                    // Only interested in cart quantity limit error returned from a json rpc call
                    if (typeof evt.memo.getMessages == 'function') {
                        evt.memo.getMessages().each(function(msg){
                            if (msg.key == 'cart.qty_limit') {
                                $(self.options.cart_message).innerHTML = msg.text + '<br /><br />';
                                $('cart-content').hide();
                                self.show();
                            }
                        });
                    }
		});
	},
	hackKeys: function(cartItem) {
		/* because somebody thought it was a good idea
		 	to use a period in the keys of a ajax return */
		for ( var key in cartItem) {
			if(key.indexOf('.')>0){
				var o = key.split('.');
				if (typeof(cartItem[o[0]])=='undefined'){
					cartItem[o[0]] = {};
				}
				cartItem[o[0]][o[1]]=cartItem[key];
			}
		}
		return cartItem;
	},
	fillin: function(data) {
		$(this.options.cart_items).fillin({
            template: templatefactory.get('/templates/dropcart-items.tmpl'),
			position: 'replace',
            object: data
		});
		return this;
	},
	show: function() {
		$(this.options.cart_box).show();
        var reset = function(){
            $(this.options.cart_link).removeClassName('active');
            $(this.options.cart_box).hide();
        };

        if (this.timeout){
            clearTimeout(this.timeout);
        }
        this.timeout = setTimeout(reset.bind(this),20000);
	},
	hide: function() {
		$(this.options.cart_box).hide();		
	},
	wrapP: function(string){
		// wrap in a p tag
		return '<p>#{str}</p>'.interpolate({'str': string});
	}
});

txn.notify = new cartNotify();

