// Javascript from Moodle modules
// Javascript from Moodle modules
// The maxattachment limit should be enforced both in javascript
// and in php.
// Taken from email sendmail.php js code with a few modifications
 
var upload_number = 1;

function addFileInput(txt,max) {
	
	if (upload_number != max ) {
    	var d = document.createElement("div");
    	d.setAttribute("id", "id_FILE_"+upload_number);
        d.setAttribute("class","file_attach");
    	var file = document.createElement("input");
    	file.setAttribute("type", "file");
    	file.setAttribute("name", "FILE_"+upload_number);
    	file.setAttribute("id", "FILE_"+upload_number);
        check_max(upload_number, max);
        
	if (upload_number < max) {
	    file.setAttribute("onchange", "addFileInput('"+txt+"','"+max+"')");
	}
    	d.appendChild(file);
    	var a = document.createElement("a");
        var s = document.createElement("span");
        var r_icon = document.createElement ("span")
        r_icon.setAttribute("class", "icon")
        a.setAttribute("class", "remove_file button")
    	a.setAttribute("href", "javascript:removeFileInput('id_FILE_"+upload_number+"');");
        s.appendChild(document.createTextNode(txt));
    	d.appendChild(a);
        a.appendChild(r_icon);
        a.appendChild(s);
    	document.getElementById("id_FILE_"+(upload_number-1)).parentNode.appendChild(d);
    	upload_number++;
        check_max(upload_number, max);
	} else {
		//alert("You are at your max attachment size of " + max);
        check_max(upload_number, max);
	}
}
 
function removeFileInput(i,max) {
   var elm = document.getElementById(i);
    document.getElementById(i).parentNode.removeChild(elm);
    upload_number--;
    
    check_max(upload_number, max);
    renumber_uploads();
    
}
 
function check_max(upload_number, max){
 
if(upload_number == max){
	$('#id_addinput').fadeOut('slow');
} 
else if (upload_number != max && $('#id_addinput:visible').length == 0){
    $('#id_addinput').fadeIn('slow');
    } 
}
 
function renumber_uploads(){
var n = 1;
$('.file_attach').each(function(){
	var removeScript = 'javascript:removeFileInput("id_FILE_'+ n + '");';
	$(this).attr('id','id_FILE_'+n)
	$(this).children('input[type="file"]:first').attr({name:'FILE_'+n, id:'FILE_'+n});
    $(this).children('a.remove_file:first').attr({href: removeScript});
    n++
	}
);
 
}