
var cartForm;

var store;


$(document).ready(function(){
    checkOrderResultUrl();
    
    if (typeof simpleCart == 'object'){
        if (cartEnabled){
            $.getJSON("/store.json",function(data){
                if (data != null){
                    store = data;
                    initSimpleCart();
                    
                    //se il carrello non è coerente, allora lo svuoto
                    if (!checkCartContent()){
                        emptyCart();
                    }
                }else{
                    console.log("Error retrieving store.json, data is null");
                } 
            });
        }
        
        
        cartForm = $('#cartForm');
        
        
    }
    
});

function initSimpleCart(){
    simpleCart.cartHeaders = [ "Id_noHeader","Name" , "Price" , "decrement_noHeader" , "Quantity" , "increment_noHeader", "Remove_noHeader" ];
    CartItem.prototype.increment = function(){
        addToCart(this.id, this.name, this.price, 1, this.maxquantity);
    }
    
    simpleCart.load = function () {
            
        var me = this;
        /* initialize variables and items array */
        me.items = {};
        me.total = 0.00;
        me.quantity = 0;
		
        /* retrieve item data from cookie */
        if( readCookie('simpleCart') ){
            
            var data = unescape(readCookie('simpleCart')).split('+');
            for(var x=0, xlen=data.length;x<xlen;x++){
			
                var tmpinfo = data[x].split('|');
                var newItem = new CartItem();
                var info = new Array();
                info.push("id="+tmpinfo[0]);
                info.push("quantity="+tmpinfo[1]);
                if( newItem.parseValuesFromArray( info ) ){
                    if (store.products[newItem.id] != null){
                        newItem.price=parseFloat(store.products[newItem.id].product_price);
                        newItem.name=store.products[newItem.id].product_name;
                        newItem.checkQuantityAndPrice();
                        /* store the new item in the cart */
                        me.items[newItem.id] = newItem;
                    }
                    
                    
                }
            }
        }
        me.isLoaded = true;
    }
    simpleCart.save = function () {
        var dataString = "";
        for( var itemId in this.items ){
            
            var itemString = itemId+"|"+this.items[itemId].quantity;
                     
            //			dataString = dataString + "++" + this.items[item].print();
            dataString = dataString + "+" + itemString;
                   
        }
        
        createCookie('simpleCart', dataString.substring( 1 ), 0.5 );
    };
    simpleCart.initialize();
}

/** Funzione per il controllo della coerenza del carrello con i prodotti nello store
 **/

function checkCartContent(){
    var items = simpleCart.items;
    var products = store.products;
    for (var cartItemId in items){
        var item = items[cartItemId];
        if (products[cartItemId] != null){
            var product = products[cartItemId];
            if (parseFloat(item.price) == parseFloat(product.product_price) && 
                parseInt(item.quantity) <= parseInt(product.product_quantity)){
                continue;
            }
        }
        return false;
        
        
        
    }
    return true;
}




/**
 * Funzione che controlla la presenza di un risultato ordine nella url
 */
function checkOrderResultUrl(){
    var url = location.href;
    var matches = url.match(/order_result=(success|failed)/);
    if (matches != null && matches.length == 2){
        var result = matches[1];
        if (result == 'failed'){
            matches = url.match(/error=(.{1,})/);
            if (matches != null && matches.length > 1){
                var error = matches[1];
                $('#orderError').append("<div>"+unescape(error)+"</div>");
            }
            
            $('#orderError').dialog({
                modal:true,
                resizable:false,
                draggable:false,
                dialogClass:"ui-message-dialog",
                close:function(event,ui){
                    location.href = location.href.split("?")[0];
                }
                
            })
        }else{
           
            emptyCart();
            $("#orderSuccess").dialog(
            {
                modal:true,
                resizable:false,
                draggable:false,
                dialogClass:"ui-message-dialog",
                close:function(event,ui){
                    location.href = location.href.split("?")[0];
                }
           
            }
            );
        }
        
        
    }
}

function emptyCart(){
    eraseCookie('simpleCart');
    simpleCart.isLoaded = false;
    simpleCart.update();
            
}

function appendHiddenInput(name,val,form){
    var input = $('<input type="hidden"/>');
    input.attr("name",name);
    input.val(val);
    form.append(input);
}

function getCartItemById(id){
    var items = simpleCart.items;
    for (var cartItemId in items){
        var item = items[cartItemId];
        if (item.id == id){
            return item;
        }
    }
    return null;
}




function doPayment(form){
    var items = simpleCart.items;
    var cont = 1;
    var productsValue =  new Array();
    for (var itemId in items){
        var item = items[itemId];
        productsValue.push(item.id+'|'+item.name+'|'+item.quantity+'|'+item.price);
        cont++;
    }
    appendHiddenInput('fe_order_products',productsValue.join("#"),cartForm);
    var shippingFee = simpleCart.shipping();
    appendHiddenInput('fe_order_shipping',shippingFee,cartForm);
    appendHiddenInput('fe_order_total',simpleCart.finalTotal,cartForm);
    
    form.submit();
    
}


function openModalDialog(url,title){
    $('<div/>').dialog({
        draggable:false,
        resizable:false,
        modal:true,
        open:function(){
            $(this).load(url)
        },
        height:500,
        width:500,
        title:title
    }
        
    );
}



