var _shop_ts = ' ', _shop_dot = ',';        // Thousands separator and dot symbol in prices 

if (navigator&&navigator.cookieEnabled==false){
    document.write(no_cookies_message);
}

/**
* Add list of products to the cart
* Used with shop.shop_type = `price`
*/
function addListToCart(shop_id) {//{{{
	if (isNaN(shop_id) || !document.f.elements['product_ids[]']) {
		return false;
	}

	var but = document.getElementById('submit_button');
	if (but) but.disabled = true;

	var total 			= Number(readCookie('CART_TOTAL_'+shop_id));
	var total_amount 	= Number(readCookie('CART_TOTAL_AMOUNT_'+shop_id));
	var cart 			= unescape(readCookie('CART_'+shop_id));
	var cart_split 		= cart.split(';');
	var cart_item_split, cart_hash = {}, found = false, product_id, price,
		amount, amount_limit, e, delta;

	for (var i = 0; i < cart_split.length; i++) { 		          
		cart_item_split = cart_split[i].split("=");
		cart_hash[cart_item_split[0]] = cart_item_split[1];				
	}	

	cart = "";

	var has_prod_info = (window._shop != undefined && window._shop.products != undefined);
	var getAmountLimit = function(product_id) {
		return (has_prod_info && window._shop.products[product_id] != undefined
				? window._shop.products[product_id].amount : false);
	};

	if (document.f.elements['product_ids[]']) { // Multiple INPUTs?
		if (document.f.elements['product_ids[]'].nodeName!="INPUT")  {					
			for (var i=0;i<document.f.elements['product_ids[]'].length;i++) {
				if (document.f.elements['product_ids[]'][i]) {
					product_id  	= document.f.elements['product_ids[]'][i].value;
					price       	= Number(document.f.elements['prices[]'][i].value);
					amount      	= Number(document.f.elements['amounts[]'][i].value);  
					amount_limit	= getAmountLimit(product_id);

					if (amount_limit) {
						if (amount_limit < amount) { 
							// Notify about amount limit
							widgets.msg(window._s3Lang['JS_SHOP_PRODUCT_AMOUNT_TOTAL']
										+ ': ' + amount_limit,
										document.f.elements['amounts[]'][i]);
							amount = amount_limit;
							//document.f.elements['amounts[]'][i].value = amount;
						}

						if (cart_hash[product_id] > amount_limit) {
							/* The limit is somehow exceeded. Correct totals */
							delta = Number(cart_hash[product_id]) - amount_limit;
							total -= price * delta;
							total_amount -= delta;
							cart_hash[product_id] = amount_limit;
							continue;
						}
					};

					if (amount > 0) {
						if (amount_limit && cart_hash[product_id]) { 
							delta = Number(cart_hash[product_id]) - amount;
						} else {
							delta = amount;	
						}

						total += price * delta;
						total_amount += delta;

						if (cart_hash[product_id])
							cart_hash[product_id] = Number(cart_hash[product_id]) + delta;
						else
							cart_hash[product_id] = delta;
					}                 			
				}
			}
		} else {   // Single product in the list 
			product_id		= document.f.elements['product_ids[]'].value;
			price			= Number(document.f.elements['prices[]'].value);
			amount			= Number(document.f.elements['amounts[]'].value);
			amount_limit	= getAmountLimit(product_id);

			if (amount_limit) {
				if (amount > amount_limit) {
					// Notify about amount limit
					widgets.msg(window._s3Lang['JS_SHOP_PRODUCT_AMOUNT_TOTAL']
								+ ': ' + amount_limit,
								document.f.elements['amounts[]']);
					amount = amount_limit;
					// document.f.elements['amounts[]'].value = amount;
				}

				if (cart_hash[product_id] > amount_limit) {
					/* The limit is somehow exceeded. Correct totals */
					delta = Number(cart_hash[product_id]) - amount_limit;
					total -= price * delta;
					total_amount -= delta;
					cart_hash[product_id] = amount_limit;
				}
			}

			if (amount > 0) {
				if (amount_limit && cart_hash[product_id]) 
					delta = amount_limit - Number(cart_hash[product_id]);
				else 
					delta = amount;	

				total += price * delta;
				total_amount += delta;

				if (cart_hash[product_id])
					cart_hash[product_id] = Number(cart_hash[product_id]) + delta;
				else
					cart_hash[product_id] = delta;
			}                 			
		}
	}	

	cart="";

	for (var i in cart_hash) {
		if (cart_hash[i]){			
			if (cart!="") cart = cart + ";";                     
			cart = cart + i+ "=" + cart_hash[i];
		}					
	}

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

	// Write cookies 
	createCookie('CART_'+shop_id,cart,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 = formatPrice(total);
	e = document.getElementById('cart_total_amount');
	if (e) e.innerHTML = total_amount;

	resetOrderList();

	return false;  
}//}}}


/**
* Add a product to the cart 
* @param Integer shop_id Shop ID
* @param Integer product_id Product ID
* @param Variant amount amount of product items to put into the cart 
* @param Variant amount amount of product items to put into the cart 
* @param Node f
*/
function addToCart(shop_id, product_id, price, amount, f){
    // Cast input
    product_id 	= Number(product_id);
    amount 		= Number(amount);
    price		= Number(price);

	var result = true, amount_limit = amount;

	/* If window._shop.products.PRODUCT_ID.amount is set, then we must limit
	* amount to that value */
	var has_amount_limit = (window._shop != undefined &&
							window._shop.products && 
							window._shop.products[product_id] != undefined ? true : false);
	if (has_amount_limit) { 
		amount_limit = window._shop.products[product_id].amount;
		if (amount_limit < amount) 
			amount = amount_limit;
	};
	  
    // All is valid? 
	if (!isNaN(shop_id) && shop_id > 0 && !isNaN(product_id) && product_id > 0
		&& !isNaN(price) && !isNaN(amount) && amount > 0) {      
        // Temp variables 
        var e;
		  
        // Read cookies 	
        var total 			= readCookie('CART_TOTAL_'+shop_id);
        var cart			 	= unescape(readCookie('CART_'+shop_id));
        var total_amount 		= 0; //Number(readCookie('CART_TOTAL_AMOUNT_'+shop_id));
          
        // Split cart string into `product_id=amount` chunks
        var cart_split = cart.split(';');
        var cart_new = "", cart_item_split, found = false, ta;
		  
        // Ensure total is of number data type 
        if (isNaN(total)) total = Number(total);
          
        // Loop though cart chunks
        for (var i=0; i < cart_split.length; i++){
            // Split product item chunk 			 
            cart_item_split = cart_split[i].split("=");
			 
            // Valid chunk? 
            if (cart_item_split.length == 2){
                if (!found && cart_item_split[0] == product_id) {			// Aleady in the cart? 
					if (! (has_amount_limit && cart_item_split[1] >= amount_limit))
						total = Number(total) + price * amount;
					ta = amount + Number(cart_item_split[1]);
					if (has_amount_limit && ta > amount_limit) {
						ta = amount_limit;
						result = false;
						if (widgets != undefined) {
							widgets.msg(window._s3Lang['JS_SHOP_PRODUCT_AMOUNT_TOTAL']
										+ ': ' + amount_limit, f);
						}
					}

                    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 a chunk with another product ID
                    // Keep it in the cart 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]);
                }
            }
        }
		  
        // Product is new to 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           
        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 = formatPrice(total);
        e = document.getElementById('cart_total_amount');
        if (e) e.innerHTML = total_amount;                          
          
        // Success
        return result; 
    }
     
    // Failure 
    return false;        
} // ## addToCart()

/**
* Return DOM node parent having provided tag name 
* @param obj Node Leverage node
* @param tagName String Tag name of the parent 
*/
function getParent(obj,tagName) {
    if (obj){ 	
        var par = obj.parentNode;
        while (par&&(par.nodeName!=tagName))
            par = par.parentNode; 

        return par; 
    }
    return null;
} // ## getParent()


function deleteRaw(o){
    v = getParent(o,"TR");
    if (v)
        v.parentNode.removeChild(v);             
}

// Dot
var dot = true;
var ttt = "2.23";
if (isNaN(ttt)) {
    dot = false;		
}


function getEventTarget(e){
    if (!e) e = window.event;

    if (e.target) {
        if (e.target.nodeType == 3) e.target = e.target.parentNode;
        return e.target;

    }	
    else if (e.srcElement)
        return e.srcElement;

}


function inputOnlyRealNumber(obj,e){

    var target = getEventTarget(e);
    
    if (target&&target.nodeName=="INPUT"&&target.type=="text"){

        var valueBefore = target.value;
        var value=""; 
         
        if (dot){ 	

            value = valueBefore.replace(",",".");

        } else {

            value = valueBefore.replace(".",",");

        } 
                   
        value = value.replace(/[^\d\.,]+/,"");         
         
        if (value.length>1)
            value = value.replace(/[0]*(\d*[\.,]?\d*).*/,"$1");
                                    
        if (value!=valueBefore){
         
            target.value =  value;                  
				         
        }                  
		 		                                           
        if (value != ""&&valueBefore==value) {
                                                   
            return true;

        }                 
                                                          
    }
   
    return false;

}

/**
* Reassign cart items according to the cart table. Used on the cart page
* @param shop_id int Shop ID
* @return void
*/
function recountCart(shop_id) {// {{{
	/* The function could be called very frequently, each keypress! Thus, we
	* wait for some user activity decrease */
	if (!window._shop) { 
		window._shop = {};
	};
	if (window._shop.timerCart)
		window.clearTimeout(window._shop.timerCart);
	window._shop.timerCart = window.setTimeout((function() {
		var total = 0, cart="", product_id, price, amount, total_amount = 0, amount_limit, e; 

		var has_prod_info = (window._shop != undefined && window._shop.products != undefined);
		var getAmountLimit = function(product_id) {
			return (has_prod_info && window._shop.products[product_id] != undefined
					? window._shop.products[product_id].amount : false);
		};

		// Any product IDs?                         
		if (document.f.elements['product_ids[]']) {
			// Multiple INPUTs?
			if (document.f.elements['product_ids[]'].nodeName!="INPUT")  {
				// Loop though product ID fields(leverage)
				for (var i=0;i<document.f.elements['product_ids[]'].length;i++){
					// The INPUT really exists?
					if (document.f.elements['product_ids[]'][i]) {
						product_id		= document.f.elements['product_ids[]'][i].value;
						price			= document.f.elements['prices[]'][i].value;
						amount_limit	= getAmountLimit(product_id);
						amount			= Number(document.f.elements['amounts[]'][i].value);
						if (amount_limit && amount > amount_limit) {
							// Notify about amount limit
							widgets.msg(window._s3Lang['JS_SHOP_PRODUCT_AMOUNT_TOTAL']
										+ ': ' + amount_limit,
										document.f.elements['amounts[]'][i]);
							amount = amount_limit;
							document.f.elements['amounts[]'][i].value = amount;
						}

						if (amount > 0) {
							total += price * amount;

							if (cart!="") cart = cart + ";";
							cart = cart + product_id + "=" + amount;            

							total_amount += amount;
						}

						e = document.getElementById('res_' + product_id);
						// Try to get shop4.js-style element
						if (!e) e = document.getElementById('res_' + product_id + i);
						if (e) e.innerHTML =
								formatPrice(Math.round((price * amount) * 100) / 100);
					}
				}
			} else { 	// Single INPUT 
				product_id		= document.f.elements['product_ids[]'].value;
				price			= document.f.elements['prices[]'].value;
				amount_limit	= getAmountLimit(product_id);
				amount			= Number(document.f.elements['amounts[]'].value);
				if (amount_limit && amount > amount_limit) {
					// Notify about amount limit
					widgets.msg(window._s3Lang['JS_SHOP_PRODUCT_AMOUNT_TOTAL']
								+ ': ' + amount_limit,
								document.f.elements['amounts[]']);
					amount = amount_limit;
					document.f.elements['amounts[]'].value = amount;
				}

				total += price * amount;
				cart = product_id + "=" + amount;            
				total_amount += amount;

				e = document.getElementById('res_'+product_id);
				// Try to get shop4.js-style element
				if (!e) e = document.getElementById('res_' + product_id + '0');
				if (e) e.innerHTML =
						formatPrice(Math.round((price * amount) * 100) / 100);
			}
		} else {					// No product IDs in the form
			// Clear cart DOM node contents
			e = document.getElementById('cart_div');	
			if (e) e.innerHTML = "";
		}

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

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

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

/* {{{ resetOrderList()
* Reset values in the order list
*/
function resetOrderList(){
    var but = document.getElementById('submit_button'), e;
    if (but) but.disabled = true;
    
    if (document.f.elements['amounts[]']) {
        if (document.f.elements['amounts[]'].nodeName!="INPUT")  {
            for (var i=0;i<document.f.elements['amounts[]'].length;i++){
               if (document.f.elements['amounts[]'][i])
                   document.f.elements['amounts[]'][i].value = 0;
            }

        } else {         
            document.f.elements['amounts[]'].value = 0;			
        }
    } 
	
	// Reset DOM node values just for the cart table
    e = document.getElementById('total');	
    if (e) e.innerHTML = 0;
}//}}}

/**
* Recount values in the order list
* @obsolete
*/
function recountOrderList(){
    var total = 0, total_amount = 0, price, product_id, amount, e; 
                                      
    if (document.f.elements['product_ids[]']) {
        if (document.f.elements['product_ids[]'].nodeName!="INPUT")  {						// Multiple INPUTs
            for (var i=0;i<document.f.elements['product_ids[]'].length;i++){

                if (document.f.elements['product_ids[]'][i]) {
                	// Read product info
                    product_id 	= document.f.elements['product_ids[]'][i].value;                               
                    price 		= document.f.elements['prices[]'][i].value;
                    amount 		= Number(document.f.elements['amounts[]'][i].value);
                	
                	// Update total price
                    total += price * amount;
                    
                    // Update total amount
                    total_amount += amount;
                	
                	// Update result DOM node
                    document.getElementById('res_'+product_id).innerHTML = formatPrice(Math.round((price*amount)*100)/100);
                }
            }
        } else {         																	// Single INPUT		
            // Read product info    		
            product_id 	= document.f.elements['product_ids[]'].value;                               
            price 		= document.f.elements['prices[]'].value;
            amount		= Number(document.f.elements['amounts[]'].value);
			
			// Update total price
            total += price * amount;
            
            // Update total amount
            total_amount += amount;
            
            // Update result DOM nodes                             
            document.getElementById('res_'+product_id).innerHTML = formatPrice(Math.round((price*amount)*100)/100);
        }
    } 
	
	
	// Round total price 
	if (isNaN(total)||total==0||total=='') total = 0;
    else total = Math.round(total*100)/100;
	
	// Update DOM nodes	
    e = document.getElementById('total');
    if (e) e.innerHTML = formatPrice(total);
	
	// Handle submit button availability
    var but = document.getElementById('submit_button');
    if (but) {
        if (total==0) but.disabled = true;
        else but.disabled = false;
    }			                                  
} // ## recountOrderList()

/**
* Find position of the DOM node
* @param obj Node DOM node which position is calculated
*/
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;
} 

function emptyInputBlur(obj,e){

    var target = getEventTarget(e);
   
    if (target&&target.nodeName=="INPUT"&&target.type=="text"){
   
        if (target.value=="") target.value = 0;
        return true;
   
    }
   
    return false;
   
}

function showAddMessage(obj) {

    var pos = findPos(obj);
		
    var d = document.getElementById("shop-added");

    if (d) {
	
        d = d.cloneNode(true);
        d.style.display = 'block';
        d.style.left = (pos.x+10)+ 'px';
        d.style.top = (pos.y + obj.offsetHeight - d.offsetHeight) + 'px';
        document.body.appendChild(d);
        d.style.top = (parseInt(d.style.top)- d.offsetHeight-10) + 'px';
		
	
        window.setTimeout(function(){
            if (d&&d.parentNode)d.parentNode.removeChild(d); delete d;
        },500);
    }	
}

/**
* Add a list of products into the cart
* @return boolean
*/
function addList(f,shop_id,func){
    if (addListToCart(shop_id)){
        if (func) func(f);
        else showAddMessage(f); 
    }  
    return false;
} // ## addList()

/**
* Add a product of the given amount to the cart
* @param shop_id int Shop ID
* @param product_id int Product ID
* @param product_price float Product price
* @param f Node form node
* @param func[optional] callback function
*/
function addProductForm(shop_id,product_id,product_price,f,func){
    if (addToCart(shop_id,product_id,product_price,f.product_amount.value,f)){
        if (func) func(f);
        else showAddMessage(f); 
    }  
	
	// Failed adding product to the cart 
    f.product_amount.value = "1";  
    return false;
} // ## addProductForm()

/**
* Format price
* @param str Mixed
*/ 
function formatPrice(str){
	if (typeof widgets != "undefined")
		return widgets.formatPrice(str, _shop_ts, _shop_dot);

	if (typeof str!='string') str = String(str);
	if (_shop_ts  == null) _shop_ts = ' ';
	if (_shop_dot== null) _shop_dot= '.';
	if (_shop_dot!= '.') str = str.replace('.', _shop_dot);

	var parts = str.split(_shop_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(_shop_ts);
		}

		return res.join('') + (parts[1] ? _shop_dot+ parts[1] : '');
	}
	return str;
}
// vim: noet fdm=marker

