vanilla.namespace('biknok.panier');

biknok.panier.etapes =
{
    properties : null,

    init : function(properties)
    {
	this.properties = properties;
	this.view = $("#view-" + properties.viewId);

	var _this = this;

	$("div.panier table td.action div.delete a", this.view).click
	(
	    function()
	    {
		_this.removeLigne($(this).parents("tr"));
	    }
	);

	biknok.common.field.country($("div.livraison", this.view));
    },

    removeLigne : function(ligne)
    {
	var table = ligne.parents("table");
	if ( table.is(".loading") )
	{
	    return;
	}

	table.toggleClass("loading", true);

	var id = new RegExp("panier-ligne-([0-9A-Z]+)").exec(ligne.attr("id"))[1];
	var button = $("td.action div.button", ligne);
	var cols = ligne.find("td");

	var _this = this;
	biknok.panier.deamon.removeLigne
	(
	    id, 
	    // success
	    function(json, top)
	    {
		if ( json.result.type == "success" )
		{
		    if ( json.nbLignes > 0 )
		    {
			// suppression de la ligne
			ligne.animate
			(
			    {value:1},
			    {
				step : function(value)
				{
				    cols.css("opacity", 1-value);
				},
				
				complete : function()
				{
				    cols.not(cols.eq(0).attr("colspan", cols.length)).remove();
				    ligne.css("visibility", "hidden").slideUp
				    (
					function()
					{
					    ligne.parents("table").find("tfoot td.total").text(json.total);
					    ligne.remove();
					}
				    );
				}
			    }
			);
		    }
		    else
		    {
			// suppression de la table
			table.parents("div.recap").slideUp
			(
			    function()
			    {
				$(this).empty().html(json.empty).slideDown();
			    }
			);
		    }
		}
		else
		{
		    biknok.common.message.draw(button, json.result);
		}
	    },

	    // error
	    function(request, textStatus, error)
	    {
		biknok.common.message.draw(button, {type:"error", message:"Une erreur est survenue"});
	    },

	    // complete
	    function()
	    {
		table.toggleClass("loading", false);
	    }
	);
    }
};
