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[]']) {      
      
        var but = document.getElementById('submit_button');
				                                  
        if (but) {	 
            but.disabled = true;
        }	
		  	
        var total = 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, e;
	
        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];				

        }	
		
        // Clear cart			          
        cart="";
                             
        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]) {
                        // INPUT values                   
                        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);  
						
                        if (amount!="" && amount > 0){
                            // Update totals 
                            total = Number(total) + price*amount;
                            total_amount += amount;
							
                            // Update cart hash
                            if (cart_hash[product_id])
                                cart_hash[product_id] = Number(cart_hash[product_id]) + amount;
                            else
                                cart_hash[product_id] = amount;
                        }                 			
                    }
                } // ## for

            } else {         																// Single INPUT
                // INPUT values
                product_id	= document.f.elements['product_ids[]'].value;
                prices		= Number(document.f.elements['prices[]'].value);
                amount		= Number(document.f.elements['amounts[]'].value);
				
                if (amount!="" && amount > 0){
                    // Update totals
                    total = Number(total) + price * amount;
                    total_amount += amount;
					
                    // Update cart hash
                    if (cart_hash[product_id])
                        cart_hash[product_id] = Number(cart_hash[product_id]) + amount;
                    else
                        cart_hash[product_id] = amount;
                }                 			
				                	                                 
            }
			
        }	

        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 shop_id int Shop ID
* @param product_id int Product ID
* @param amount mixed amount of product items to put into the cart 
*/
function addToCart(shop_id,product_id,price,amount){
    // Cast input
    product_id 	= Number(product_id);
    amount 		= Number(amount);
    price			= Number(price);
	  
    // 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? 
                    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 a chunk with another product ID
                    // Keeo 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 true;  
    }
     
    // 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){
    var total = 0, cart="", product_id, price, amount, total_amount = 0, e; 
    
    // 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]) {
                	// 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);
                	
                    if (amount > 0){
                    	// Total price
	                    total += price * amount;
	                    
	                    // Cart string
                        if (cart!="") cart = cart + ";";
                        cart = cart + product_id + "=" + amount;            
                        
                        // 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);
			
			// Total price
            total += price * amount;
            
            // Cart string     
            cart = product_id + "=" + amount;            
            
            // Total amount 
            total_amount += amount;
            
            // Update result DOM node     
            document.getElementById('res_'+product_id).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 = "";
    }
	
	// Round total price
    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('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;
} // ## recountCart()


/**
* 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;
} // ## resetOrderList()

/**
* 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)){
        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){
    // Cast to string 
    if(typeof str!='string') str = String(str);
    str = str.replace('.', _shop_dot);

    // Split by dot symbol
    var parts = str.split(_shop_dot), res = [], i, pc;
    
    /*pc = parts[1];
    pc = (pc!=undefined && pc!=0 ? ((pc[0] + (pc[1]==undefined ? '0' : pc[1]))/10).toFixed(0) : '');
    */

    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];// + (pc ? _shop_dot + pc : '');
   }
   return parts[0] + '.' + parts[1];// + (pc ? _shop_dot + pc : '');
} // ## formatPrice()
