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(brand_resource('The_following_added_to_cart_txt')),
		    delete_message: this.wrapP(brand_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);
			});
			
			// WDR 3/10/11: Leslie says we should only show on an add.
			if ( data[0].action == 'add' ) {
				$(self.options.cart_message).innerHTML = self.options[data[0].action+'_message'];
				self.fillin(data).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();
		$(this.options.cart_box).scrollTo();
        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();
