$(document).ready(function(){
	redoButtons();
	
});

/**
* @desc:   Apply click events for adding and deleting rows
*/
function applyEventsToButtons()
{
	// assign click items to plus and minus signs
	$('.st_filter_row_add_abs').click(addRow);
	$('.st_filter_row_del_abs').click(delRow);
}

/**
* @desc:   Clone a hidden div wich contains search fields
*/
function addRow()
{
	var current_div = $(this).parent("div").clone(true);
	$(".stl", current_div).each(function() {
		$(this).val("");
	});
	
	$(this).parent("div").parent("div").append(current_div);
	
	redoButtons();
}


/**
* @desc:   Clone a hidden div wich contains search fields
*/
function delRow()
{
	$(this).parent("div").remove();
	redoButtons();
}

/**
* @desc:   Place add/delete buttons for newly cloned lines
*/
function redoButtons() 
{
	// First, delete all buttons, then apply new ones
	$('.filterType_row .st_filter_row_add_abs, .filterType_row .st_filter_row_del_abs').remove();

	
	// For each row, add the applicable buttons
	$('.rows').each(function()
	{
		// Now, fetch all rows we're trying to add buttons to
		var totalRows	=	$(this).children(".filterType_row").length;
		
		$('.filterType_row', this).each(function(i)
		{
			if (totalRows == 1)
			{
				// only one exist, so add a plus
				$(this).append( $("#tplBtnAdd > img").clone());
			}
			else
			{
				// more than one exist, so first gets a minus
				if (i != totalRows-1)
				{
					$(this).append( $("#tplBtnDel > img").clone());
				}
				else
				{
					$(this).append( $("#tplBtnDel > img").clone());
					$(this).append( $("#tplBtnAdd > img").clone());
				}
			}
		});
 	});
 	
 	applyEventsToButtons();

}


