var cont;
var btAddShop = ".addShop";
var btRemoveShop = ".removeShop";
var btRemoveShopGrid = ".removeShopGrid";
var contContainer = "#openContainer b";

$(document).ready(function(){ 
	cont = $(contContainer);
	startButtonShop();
});

$(document).ajaxSuccess(function(){ 
	startButtonShop();
});


/*
* ACTION CART
*/
function startButtonShop(){
	$(btAddShop).each(function(){ 
		$(this).unbind('click');
		$(this).click(function(){ 
			addShop(this);
			return false;
		});
	});

	$(btRemoveShop).each(function(){
		$(this).unbind('click');	
		$(this).click(function(){
			removeShop(this);
			return false;
		});
	});
	
	$(btRemoveShopGrid).each(function(){
		$(this).unbind('click');	
		$(this).click(function(){
			removeShopGrid(this);
			return false;
		});
	});
}


function addShop(bt){
	$.ajax({
			dataType: 'html',
			type: 'GET',
			url: $(bt).attr('href'),
			data: 'ajax=true',
			success: function(msg){
				var id = $(bt).attr('id'); 
				checked(bt);
				checked($('#'+id+btAddShop));
				cont.html(parseInt(cont.html())+1);
			}
		});
}

function removeShop(bt){
	$.ajax({
			dataType: 'html',
			type: 'GET',
			url: $(bt).attr('href'),
			data: 'ajax=true&action=remove',
			success: function(msg){
				var id = $(bt).attr('id'); 
				unchecked(bt);
				unchecked($('#'+id+btRemoveShop));
				cont.html(parseInt(cont.html())-1);
			}
		});
}

function removeShopGrid(bt){
	$.ajax({
			dataType: 'html',
			type: 'GET',
			url: $(bt).attr('href'),
			data: 'ajax=true&action=remove',
			success: function(msg){
				$(bt).parents('tr').fadeOut('fast',function(){
					tbody = this.parentNode;
					$(this).remove();
					zebrarTable('.shopGrid','#f6f6f6');
					renumerar();
					unchecked($("#bt"+$(bt).attr('id')+btRemoveShop));
					cont.html(parseInt(cont.html())-1);
					if(parseInt(cont.html()) == 0)
						$(tbody).html("<tr><td colspan='7' class='empty'>Nenhum item adicionado </td></tr>");
				});
				
			}
		});
}

function checked(bt){
	$(bt).html('remove').removeClass(btAddShop.substr(1)).addClass(btRemoveShop.substr(1)).unbind('click');
	$(bt).parents('li').addClass('checked');
	$(bt).click(function(){ removeShop(this); return false });
}

function unchecked(bt){
	$(bt).html('add to container').removeClass(btRemoveShop.substr(1)).addClass(btAddShop.substr(1)).unbind('click');
	$(bt).parents('li').removeClass('checked');
	$(bt).click(function(){ addShop(this); return false });
}

function renumerar(){
	$("table[class='shopGrid'] tbody tr td:first-child").each(function(i,e){
		$(e).html(i+1);
	});
}
