var Misskha = {

    init: function()
    {
        MisskhaDragDropCart.init();
        MisskhaTooltip.init();
    }
}

var MisskhaTooltip = {
    init: function() {
		
        var tab = new Array();
        $$('.item-image').each( function(elmt) {
            var descendants = $(elmt).next('.no-display').descendants();
            tab.push(new Tooltip($(elmt), descendants[0], {
                'html': true,
                'classname': 'MisskhaTooltip'
            }));
        });
    }
}

var MisskhaDragDropCart = {
    init: function() {
        $$('.item-image').each( function(elmt) {
            new Draggable(elmt, {
                revert:true,
                ghosting:true
            });
        });
		
        Event.observe('pays', 'change', MisskhaDragDropCart.updateShippingPrice);
		
        Droppables.add('my_cart', {
            onDrop:MisskhaDragDropCart.droppingItem
        });
    },
	
    droppingItem: function(element, dropon, event)
    {
        MisskhaDragDropCart.disableAllButton();
        MisskhaDragDropCart.validate(element, dropon, event);
    },
	
    validate: function(element, dropon, event) {
		
        var ancestors = $(element).ancestors();
        var productForm = ancestors[0];
		
        if( productForm.readAttribute('action').search('checkout/cart/add') != -1 )
            MisskhaDragDropCart.addProduct(element, productForm);
        else
        {
            MisskhaDragDropCart.displayErrorMessage();
            MisskhaDragDropCart.enableAllButton();
        }
    },
	
    addProduct: function(element, productForm) {
        productForm.request({
            onLoading: function(){
                MisskhaDragDropCart.displayLoader()
            },
            onFailure: function(){
                MisskhaDragDropCart.displayErrorMessage();
            },
            onSuccess: function(transport){
                var response = transport.responseText || "error";
                var result = eval('(' + response + ')');
				
                var cart = result.cart;
                var cart_total = result.cart_total;
                var shipping_price = result.shipping_price;
                var item_nb = result.item_nb;
				
                $('cart_details').update(cart);
                $('cart_total').update(cart_total);
                $('frais_port').update(shipping_price);
				
                var finalHeight = item_nb * 10;
                if( finalHeight > 50 )
                    finalHeight = 50;
				
                $('simul_cart').setStyle({
                    display: "block"
                });
                $('simul_cart').morph('height:'+finalHeight+'px;');
				
                /* VIES debut */
                var cats_names = result.cats_names.split("/");
                var cats_qtys = result.cats_qtys.split("/");
                for(j=0;j<cats_names.length;j++)
                {
                    $('cart_degressif_name_'+j).innerHTML = cats_names[j];
                    $('cart_degressif_qty_'+j).innerHTML = cats_qtys[j];
                }
                doDisplayBullePanier("");
            /* VIES fin   */
            },
            onComplete: function(){
                MisskhaDragDropCart.hideLoader();
                MisskhaDragDropCart.enableAllButton();
            }
        });
    },
	
    moveImage: function(element)
    {
        MisskhaDragDropCart.disableAllButton();
		
        var objectPosition = $(element).previous('.item-image').positionedOffset();
        var xPos = objectPosition[0];
        var yPos = objectPosition[1];
        var test = Object.clone($(element).previous('.item-image'));
		
        new Effect.Parallel([
            new Effect.Move($(element).previous('.item-image'), {
                sync: true,
                x: 250-xPos,
                y: 340-yPos,
                mode: 'absolute'
            }),
            new Effect.Opacity($(element).previous('.item-image'), {
                sync: true,
                from: 1,
                to: 0
            })
            ], {
                duration: 0.8,
                delay: 0,
                afterFinish:MisskhaDragDropCart.replaceImage($(element).previous('.item-image'), xPos, yPos)
            });
    },
	
    replaceImage: function(element, xOldPos, yOldPos)
    {
        var objectPosition = $(element).positionedOffset();
        var xPos = objectPosition[0];
        var yPos = objectPosition[1];
		
        new Effect.Parallel([
            new Effect.Move($(element), {
                sync: true,
                x:xOldPos-xPos,
                y:yOldPos-yPos,
                mode: 'absolute'
            }),
            new Effect.Opacity($(element), {
                sync: true,
                from: 0,
                to: 1
            })
            ], {
                duration: 0.8,
                delay: 0.8,
                afterFinish:MisskhaDragDropCart.validate($(element), null, null)
            });
    },
	
    updateShippingPrice: function()
    {
        var countryId = $('pays').value;

        new Ajax.Request(
            //"http://www.misskha.fr/index.php/checkout/cart/estimatePost/country_id/"+countryId+"",
            "http://www.misskha.fr/index.php/checkout/cart/estimatePost/country_id/"+countryId+"",
            {
                method: 'get',
                onLoading: function(){
                    MisskhaDragDropCart.displayLoader();
                },
                onFailure: function(){
                    MisskhaDragDropCart.hideLoader();
                    MisskhaDragDropCart.displayErrorMessage();
                },
                onSuccess: function(transport){
                    MisskhaDragDropCart.displayShippingPrice();
                }
            }
            );
    },
	
    displayShippingPrice: function()
    {
        
        new Ajax.Request(
            //"http://www.misskha.fr/index.php/checkout/cart/calculTotal/",
            "http://www.misskha.fr/index.php/checkout/cart/calculTotal/",
            {
                method: 'get',
                onFailure: function() {
                    MisskhaDragDropCart.hideLoader();
                    MisskhaDragDropCart.displayErrorMessage();
                },
                onSuccess: function(transport){
                    MisskhaDragDropCart.hideLoader();

                    var response = transport.responseText || "error";
//                    console.log("Success : displayShippingPrice "+transport.responseText);
                    var result = eval('(' + response + ')');
						
                    var cart_total = result.cart_total;
                    var shipping_price = result.shipping_price;

                    $('cart_total').update(cart_total);
                    $('frais_port').update(shipping_price);
                }
            }
            );
    },
	
    displayErrorMessage: function()
    {
        alert('Notre serveur rencontre un souci. Si cela devait se reproduire, contactez votre administrateur.');
    },
	
    displayLoader: function()
    {
        $('update-loader').setStyle({
            visibility: "visible"
        });
    },
	
    hideLoader: function()
    {
        $('update-loader').setStyle({
            visibility: "hidden"
        });
    },
	
    disableAllButton: function()
    {
        $$('.add-cart-button').each( function(elmt) {
            $(elmt).disable();
            $(elmt).addClassName('disable');
            $(elmt).removeClassName('add-cart-button');
        });
    },
	
    enableAllButton: function()
    {
        $$('.disable').each( function(elmt) {
            $(elmt).enable();
            $(elmt).removeClassName('disable');
            $(elmt).addClassName('add-cart-button');
        });
    }
	
	
}

Event.observe(window, "load", function() {
    Misskha.init();
});


