var widgets = {
    // Add a product to the shop cart
    addToCart: function(shop_id, product_id, price, obj) {//{{{
        var amount = 1;
		
        // Cast
        product_id 	= Number(product_id);
        price		= Number(price);

		// Get price dynamically
		$.post('/my/s3/export/shop/product.php',
			{
				'mode' 			: 'json', 
				'action' 		: 'get-product',
				'shop_id' 		: shop_id, 
				'product_id' 	: product_id
			},
			function (data) {//{{{
				if (data && data.product_price != undefined) { 
					price = Number(data.product_price);
				};

				// Input is valid?
				if (!isNaN(shop_id)&&(shop_id>0) && !isNaN(product_id) && (product_id>0)
					&&!isNaN(price)&&!isNaN(amount)&&(amount>0)) {      
					// Temporary variables
					var cart_new = "", cart_item_split, found = false, total_amount = 0, ta, e;

					// Read cookies	
					var total = readCookie('CART_TOTAL_'+shop_id);
					var cart = unescape(readCookie('CART_'+shop_id));

					// Split cart cookie into product_id=amount chunks
					var cart_split = cart.split(';');

					// Ensure total is of number data type 
					if (isNaN(total)) total = Number(total);

					// Loop though cart item chunks	
					for (var i=0; i < cart_split.length; i++){
						// Split chunk into product_id and amount
						cart_item_split = cart_split[i].split("=");

						// Valid chunk?
						if (cart_item_split.length == 2){
							if (!found && cart_item_split[0] == product_id) {			// Already have such product in the cart?
								total = Number(total) + price * amount;
								ta = amount + Number(cart_item_split[1]);
								found = true;

								if (cart_new!="") cart_new = cart_new + ";";                     
								cart_new = cart_new + product_id + "=" + ta;

								// Update total amount
								total_amount += ta;
							} else {													// This is another product_id. So keep it without modifications
								if (cart_new!="") cart_new = cart_new + ";";                     
								cart_new = cart_new + cart_item_split[0] + "=" + cart_item_split[1];

								// Update total amount
								total_amount += Number(cart_item_split[1]);
							}
						} // ## if valid chunk
					} // ## for

					// The product_id is not found in the cart	
					if (!found) {
						if (cart_new!="") cart_new = cart_new + ";";                     
						cart_new = cart_new + product_id + "=" + amount;
						total = Number(total) + price * amount; 

						// Update total amount
						total_amount += amount;
					}    

					// Round total price           
					total = Math.round(total*100)/100;           

					// Write cookies          
					createCookie('CART_'+shop_id,cart_new,10); 
					createCookie('CART_TOTAL_'+shop_id,total,10);
					createCookie('CART_TOTAL_AMOUNT_'+shop_id,total_amount,10);

					// Update DOM nodes
					e = document.getElementById('cart_total'); 	 
					if (e) e.innerHTML = total;
					e = document.getElementById('cart_total_amount'); 	 
					if (e) e.innerHTML = total_amount;

					// Show 'added' message
					var pos = findPos(obj);
					var d = document.createElement("DIV");
					if (d) {
						d.style.position = 'absolute';
						d.innerHTML = 'добавлено...';
						d.style.display = 'block';
						d.className = 'added-to-cart';
						d.style.left = (pos.x+obj.offsetWidth) + 'px';
						d.style.top = (pos.y+obj.offsetHeight) + 'px';
						document.body.appendChild(d);

						window.setTimeout(function(){
							if (d&&d.parentNode)d.parentNode.removeChild(d); delete d;
						},1500);
					}	

					// Success
					return true;  
				} // if ## input variables are valid


			},//}}}
			'json'
		);
		
		// Failure
        return false;     
   },//}}}
   
   /**
   * Format price
   * @param str Mixed
   * @param ts String Thousands separator
   * @param dot String Dot symbol
   */ 
   formatPrice : function(str, ts, dot) {
   		if (typeof str!='string') str = String(str);
   		if (ts == null) ts = ' ';
   		if (dot == null) dot = '.';
		if (dot != '.') str = str.replace('.', dot);
   		
   		var parts = str.split(dot), res = [], i;
		
		if (parts[0].length >= 4) {
		    for (i = (parts[0].length - 1), j=1; i>=0; --i, ++j) {
		        res.unshift(parts[0].charAt(i));
		        if (j % 3 == 0 && i>0)
		            res.unshift(ts);
		    }
		    
		    return res.join('') + (parts[1] ? dot + parts[1] : '');
		}
		return str;
	}, 

	/**
	* @brief Add window.onload function 
	* @author Ruslan Osmanov
	*
	* @param func
	*
	* @return 
	*/
	addOnloadEvent : function (func) {
		var oldonload = window.onload;
		if (typeof window.onload != 'function') {
			window.onload = func;
		} else {
			window.onload = function() {
				if (oldonload) {
					oldonload();
				}
				func();
			}
		}
	
	}
};

function findPos(obj){
    var result = {};

    result.x = 0;
    result.y = 0;

    if (obj.offsetParent) {
		
        while (obj.offsetParent) {
            result.y += obj.offsetTop;
            result.x += obj.offsetLeft;
            obj = obj.offsetParent;
        }
			
    } else {
        if (obj.x) result.x += obj.x;
        if (obj.y) result.y += obj.y;
    }

    return result;

}

// vim: noet fdm=marker

