
/*
 * file: help/create-simple-gps.js
 *
 * Adding helpers to add remove attachments to the simple gps form
 */

(function($){
$(document).ready(function(){
	/*
	if (!($.site.isModule("help") && $.site.isAction("extraAssistance"))) {
		// Verify correct page
		return;
	}
	*/
	
	var nrAttachments = 1; // Keep track of the number of active attachment fields
	var nextId = 1; // Used to increment the id counter

	// Attach a listener to the remove attachment buttons
	$("#attachments .remove-attachment").live("click", function(e){
		e.preventDefault();
		if ( nrAttachments === 1 ) {
			// hide and clear the remainging field
			$(this).parents(".attach").hide().find(":file").val("");
		} else {
			// remove it
			$(this).parents(".attach").remove();
		}
		nrAttachments--;
	});
	
	$(".addattachment .bfhButton").click(function(e){
		e.preventDefault();
		if ( nrAttachments === 0 ) {
			// show hidden field
			$('div.attach').show();
			nrAttachments++;
		} else if (nrAttachments < 5) {
			// add new field
			$('div.attach').eq(0).clone()
				.appendTo($("#attachments"))
				.attr("id", "attach_"+nextId)
				.find(":file")
					.attr("id", "file_"+nextId)
					.attr("name", "file_"+nextId)
					.val("");
			nextId++;
			nrAttachments++;
		}
	});

	// index active attached files before submitted
	$("#create-simple-gps-form").submit(function(e){
		var id = 0;
		$(this).find(":file").each(function(){
			if ($(this).val() != ""){
				$(this).attr("name", "file_"+id++);
			} else {
				$(this).remove();
			}
		});
		return true;
	});
});
})(jQuery);

