/*=== JScart ===*/
/** Create a new JScart interactive shopping cart for Simpla CMS
 * @param numb  The initial number of items
 * @param summ  The initial summ of money
 * @param curr  The initial currency string
 */
function JScart(numb,summ,curr) {
	this.numb = numb;
	this.summ = summ;
	this.curr = curr;

	// measure units for the smartcart display
	this.units = ["вкуснятина","вкуснятины","вкуснятин"];
	//this.units = ["товар","товара","товаров"];
	//this.units = ["торт","торта","тортов"];

	/** Adds new items to the JScart
	 * @param price     An item's price
	 * @param qty       The quantity
	 */
	this.add = function(price, qty){
		jscart.numb += qty;
		jscart.summ += price*qty;
		};
	/** Display JScart current status visually
	 */
	this.display = function(){
		/* Russian */
		var ptext = this.units[2];
		var p1=this.numb%10, p2=this.numb%100;
		if (p1==1 && !(p2>=11 && p2<=19)) ptext=this.units[0];
		if (p1>=2 && p1<=4 && !(p2>=11 && p2<=19)) ptext=this.units[1];
		/* Display */
		$('#bask #baba .cart_status')
			.filter('.numb').text(this.numb+' '+ptext).end()
			.filter('.summ').text('на сумму '+this.summ+' '+this.curr).end()
			;
		};
	/** Purchase a product with an AJAX request
	 * @param product_id    Id of the product
	 * @param variant_id    Id of the variant
	 * @param quantity      Quantity of the product
	 * @param price         The price of the product
	 * @param callback      The function that jQuery calls when the request finishes
	 */
	this.purchase = function(product_id, variant_id, quantity, price, callback) {
		var ajax_purchase = false; // SET: Purchase: AJAX or redirect?

		if (ajax_purchase)
			$.get("/cart",
					{variant_id: variant_id, amount: quantity, smartcart: 1},
					callback
					);
			else
			window.location = "/cart/?variant_id="+variant_id+"&amount="+quantity;
		};
	};

/*=== Bind a new buy function ===*/
$(function(){
	var ask_qty=true; // SET: Ask for quantity or submit 'qty=1' immediately?

	// Replace all the 'buy' buttons with a script
	$('form.price').submit(function(){
		// Display everything that was hidden
		$('.smartcart-hidden').removeClass('smartcart-hidden');
		// Show new smartcart
		new smartcart(this, ask_qty, 'qty', undefined);
		return false; // Prevent the form from reloading the page
		})
		.find(':submit').removeAttr('onclick').unbind();

	// Display the cart status so it's units are right
	jscart.display();
	});

/*=== Popup box ===*/
/** Popup quantity request
 * @param product_form  Form object
 * @param ask_qty       Whether to ask the quantity or submit the 'qty=1' immediately
 * @param mode          The popup display mode: qty, mass
 * @param arg           An argument for the smartcart
 */
function smartcart(product_form, ask_qty, mode, arg){
	var hide_whole_form = false; // SET: hide the whole price form, or only the 'purchase' button?

	this.form = $(product_form); // '.price' form
	this.bt_purchase = this.form.find('input:submit'); // purchase button
	this.ra_variants = this.form.find('input:radio'); // variants radio buttons
	this.purchhide = (hide_whole_form?  this.form  :  this.bt_purchase  ); // what to hide?

	this.smartcart = $('#smartcart');
	/* Collect data */
	this.variant = this.form.find('input:radio:checked'); // the selected variant radio
	this.variant_id = this.variant.val(); // the selected variant id
	this.product_id = parseInt(this.variant.attr('data-product')); // id of the product
	this.price = parseFloat(this.variant.attr('data-price')); // price of the selected variant

	/* Move smartcart here, but do not yet display it */
	this.smartcart.remove().appendTo(this.form.parent());
	/* Store some useful variables */
	var smcart = this;
	var smpart = $('#smartcart #smartcart_'+mode);

	/* Function: onChange variant */
	this.ra_variants.click(function(){
			smcart.variant = $(this);
			smcart.variant_id = smcart.variant.val();
			smcart.price = parseFloat(smcart.variant.attr('data-price'));
			/* update price */
			smcart['upprice_'+mode](  smcart, smpart, arg  );
			});

	/* Function: OnPurchase AJAX */
	this.purhase = function(quantity){
			/* Show spinner */
			this.smartcart.removeClass().addClass("visible mode_spin");
			/* Send AJAX request */
			jscart.purchase(this.product_id, this.variant_id, quantity, this.price, function(){
					/* Update JScart */
					jscart.add(smcart.price, quantity);
					jscart.display();
					/* Hide smartcart */
					smcart.smartcart.removeClass();
					smcart.purchhide.removeClass('smartcart-hidden');
					});
				};

	/* Ask the quantity */
	smcart.purchhide.pos = smcart.purchhide.offset(); // add a new 'pos' property
	smcart.purchhide.addClass('smartcart-hidden');
	if (!ask_qty)
		this.purchase(1);
		else {
		// Configure smartcart
		this['popup_'+mode](  smcart, smpart, arg  );
		// Display smartcart
		this.smartcart.removeClass().addClass('visible mode_'+mode).css({left: smcart.purchhide.pos.left, top: smcart.purchhide.pos.top});
		}
	};

/** Quantity popup for the smartcart
 * @param smcart         Smartcart object
 * @param smpart         $(Subsmartcart) that belongs to this method
 * @param arg            An argument for the smartcart
 */
smartcart.prototype.popup_qty = function(smcart, smpart, arg){
	smpart
		// Restore the defaults
		.find('.qty').val(1)
		// Bind DisplayPrice function
			.keyup(function(){  smcart.upprice_qty(smcart, smpart, arg)  }).keyup()
				.end()
		// add OK event
		.find('.ok').unbind().click(function(){
			var qty = parseInt(  smpart.find('.qty').val()  );
			smcart.purhase(qty);
			return false; // prevent! (default action)
			});
	};

/** Updates the price when something external is changed
 */
smartcart.prototype.upprice_qty = function(smcart, smpart, arg) {
	smpart.find('.price').text(
			(smcart.price * smpart.find('.qty').val()) + ' ' + jscart.curr
			);
	};