var cart = {
	config: {
		div: 'cart',
		formHighlight: '#569B21',
		formBackground: '#ffffff'
	},

	add: function( product, count, form ) {
		var t = this;
		if (undefined == count) count = 1;
		if (undefined != form) t.alertForm( form );

		new Ajax.Updater( this.config.div, '/cart/add/ajax/', {
			parameters: { product: product, c: count },
			method: "POST",
			onComplete: function() {
				t.alert();
			},
			asynchronous:true,
			evalScripts:true
		});
	},

	refresh: function() {
		new Ajax.Updater( this.config.div, '/cart/block/ajax/', {
			onComplete: this.alert,
			asynchronous:true,
			evalScripts:true
		});
	},

	submit: function( form ) {
		this.add( form.product.value, form.c.value , form );
	},

	calc: function ( price, count )	{
		return this.format( parseFloat(price) * count );
	},

	calc_item: function( id, price ) {
		var t = this;
		new Form.Element.Observer(
  			$(id),
  			0.2,
  			function(el, value){
    			$(id + '_sum').style.display="inline";
  				$(id + '_sum').innerHTML = "на " + t.calc( price, value);
  			}
		)
	},

	format: function( summa ) {
		summa += '';
		x = summa.split('.');
		x1 = x[0];
		x2 = x.length > 1 ? '.' + x[1].truncate(2, '') : '';

		if (x2.length > 0 && x2.length < 3) x2 += '0';

		var rgx = /(\d+)(\d{3})/;
		while (rgx.test(x1)) {
			x1 = x1.replace(rgx, '$1' + ',' + '$2');
		}
		return x1 + x2;
	},

	alertForm: function( form ) {
		this.showPopup();

//		new Effect.Highlight( form, {endcolor: this.config.formHighlight, restorecolor: this.config.formHighlight});
//		new Effect.Highlight( form, {startcolor:this.config.formHighlight, endcolor: this.config.formBackground, restorecolor: this.config.formBackground, duration: 1, queue: 'end'});
	},

	showPopup: function() {
        var div = new Element('div').update('Товар добавлен');
        div.addClassName('cart_popup').addClassName('shadow');

		div.hide();
		document.body.appendChild( div );
		div.absolutize();

		var dw = 200;
		var dh = 20;

		var h = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
		if (!h) h = 0;

		div.setStyle( {
			'width': dw + 'px',
			'height': dh + 'px',
			'left': ( document.body.clientWidth - dw ) / 2 + 'px',
			'top': (h + ( document.documentElement.clientHeight - dh ) / 2) + 'px'
		} );

		div.show();

		setTimeout( div.remove.bind(div), 3000 );
	},

	alerting: false,
	alert: function() {
		if (this.alerting) return;

		this.alerting = true;
//		var f = $('cart_content');
//		if (f) window.location.reload();

		new Effect.Pulsate( this.config.div, { duration: .5, pulses: 3 } );

		var t = this;
		setTimeout( function() {t.alerting = false;}, 1000 );
	}
}
