jQuery.extend({
	addBlock: function(element,blockId,addClass,removeClass) 
	{	
		var curNum = $.getNumber(element,blockId);
		var clone = $('#'+blockId+curNum).clone();		
		var nextNum = curNum+1;	
			
		//podmiana bieżącego numerka na kolejny w id, name, for 
		
		$(clone).find("img").each(function() {
			if ($(this).attr('id') != undefined) {
				$(this).attr('id',$(this).attr('id').replace(curNum,nextNum));
			}
		});
		
		$(clone).find("label").each(function() {
			if ($(this).attr('for') != undefined) {
				$(this).attr('for',$(this).attr('for').replace(curNum,nextNum));
			}
		});
			
		$(clone).find(":input").each(function() {
			if ($(this).attr('id') != undefined) {
				$(this).attr('id',$(this).attr('id').replace(curNum,nextNum));
			}
			if ($(this).attr('name') != undefined) {
				$(this).attr('name',$(this).attr('name').replace(curNum,nextNum));
			}
			if ($(this).attr('for') != undefined) {
				$(this).attr('for',$(this).attr('for').replace(curNum,nextNum));
			}
			if ($(this).attr('type') != 'hidden') {
				$(this).val('');
			}
		});	
			
		$(clone).attr('id',blockId+nextNum);
			
		//podpięcie funkcji do nowego dodaj
		$(clone).find('.'+addClass).click(function() {$.addBlock($(this),blockId,addClass,removeClass)});
		//usunięcie starego dodaj
		$('#'+blockId+curNum).find('.'+addClass).remove();
		if ($('#'+blockId+curNum).find('.'+removeClass).css('display') == 'none') {//jeśli poprzedni blok jest pierwszym -> odsłonięcie "usuń" i podpięcie funkcji
			$('.'+removeClass).css('display','').click(function() {$.removeBlock(blockId,curNum,addClass,removeClass)});	
		}
		//odsłonięcie bierzącego "usuń"
		$(clone).find('.'+removeClass).css('display','').click(function() {$.removeBlock($(this),blockId,addClass,removeClass)});
			
		$(clone).insertAfter('#'+blockId+curNum);
		$.addBlockEnd(nextNum);
	},
	
	removeBlock: function(element,blockId,addClass,removeClass) 
	{
		var curNum = $.getNumber(element,blockId);
		var dodaj = $('.'+addClass).clone(); 
		$('#'+blockId+curNum).remove();	
			
		if ($('.'+addClass).size() == 0) {//usunięcie ostatniego -> trzeba dorobić "dodaj" do poprzedniego
			var num = $.getNumber($('.'+removeClass+':last'),blockId);
			$(dodaj).insertAfter($('.'+removeClass+':last')).click(function() {$.addBlock($(this),blockId,addClass,removeClass)});
		}
		if ($('.'+removeClass).size() == 1) {//zostaje tylko jeden blok -> trzeba ukryć "usuń"
			$('.'+removeClass).css('display','none');
		}
	},
	
	getNumber: function(element,blockId) 
	{
		var regId = new RegExp("^"+blockId+"[0-9]{1,}$");
		var number = false;
		$(element).parents().each(function() {
			if (regId.test($(this).attr('id')) == true) {
				number =  parseInt($(this).attr('id').replace(blockId,''));			
			}
		});
		return number;
	},
	
	addBlockEnd: function(n)
	{

	}
});

