// Collected form handling scripts for Aspect

// This function will remove a previously uploaded image or file from the
// form. it will empty the text fields, remove the preview  and the
// "delete button" and then add a "file upload" button.
function removeItem (form, item) {

    // set the text fields to empty
    form[item + '_id'].value = "";
    form[item + '_name'].value = "";
    form[item + '_description'].value = "";
    
    // get the fieldset
    document.getElementById("li_"+item).style.display = 'none';
}

// throw up an delete confirmation alert box
function deleteConfirm(type, id) {
    if (confirm("Are you sure you want to delete this " + type + "?")) {
		var currentPage = document.URL;
		if (currentPage.indexOf('?', 0) == -1) {
			window.location=document.URL + "?id=" + id + "&action=delete";
		} else {
	        window.location=document.URL + "&action=delete";
	    }
    }
}

// change the contents/disabledness of the custom email field, based on the use_email dropdown
function changeUserEmailField() {
	var useEmail = document.getElementById('use_email').value;
	if (useEmail == 'home') {
		document.getElementById('custom_email').value = document.getElementById('home_email_js_hack').value;
		document.getElementById('custom_email').disabled = true;
	} else if (useEmail == 'work') {
		document.getElementById('custom_email').value = document.getElementById('work_email_js_hack').value;
		document.getElementById('custom_email').disabled = true;
	} else {
		document.getElementById('custom_email').value = '';
		document.getElementById('custom_email').disabled = false;
	}
} 

function setSelectedFile() {
	var selectName = this.name;
	var names = selectName.split('_');
	var name = names[0];
	//alert(name);
	var fileId = getFormElementValue('objext', selectName);
	//alert('setting name');
	setFormElementValue('objext', name+'_name', files[fileId][0]);
	//alert('setting id');
	setFormElementValue('objext', name+'_id', fileId);
	//alert('setting description');
	setFormElementValue('objext', name+'_description', files[fileId][1]);
	//setFormElementValue('objext', name+'_filename', files[fileId][2]);
	hideElement(name+'_row');
}

function createFileFieldset(obj) {
	createFileFieldset(obj, 0, false);
}

function createFileFieldset(obj, fileGroup) {
	createFileFieldset(obj, fileGroup, false);
}

// creates a new file "formlet" - set of form elements required to add new files to objexts
// files are always part of a filegroup
// so this function is called by the "add a new file to this group" link in Objext forms
// or by the JobAdvert forms
function createFileFieldset(obj, fileGroup, hideFilePermissions) {

	// if we have an array of all existing filenames/ids (a var called files), then build a dropdown out of them
	// this is done for all Branches, but not for eg JobAdverts, where we assume that the application form is a new file
	var showFileDropdown = (window.files != null);

	if (document.getElementById) {
		// find out the current file index
		var i = getFormElementValue('objext', 'file_index');
		
		var li = document.createElement("li");
		li.setAttribute('id', 'li_file'+i);
		li.setAttribute('class', 'filelist');
		
		var fieldset = document.createElement("fieldset");
		fieldset.setAttribute('id', 'file'+i+'_fieldset');
		fieldset.setAttribute('class', 'fileUpload');
		li.appendChild(fieldset);
		
		if (showFileDropdown) {
			var fr1 = createFormRow();
			var l1 = document.createElement('label');
			l1.setAttribute('for', 'file'+i+'_select');
			l1.innerHTML = 'EITHER select an existing file:';
			var r1 = document.createElement('select');
			addEvent(r1, "change", setSelectedFile);
			r1.setAttribute('name', 'file'+i+'_select');
			r1.setAttribute('id', 'file'+i+'_select');
			for (var j=0; j<window.files.length; j++) {
				if (undefined !== window.files[j]) {
					var option = document.createElement('option');
					option.setAttribute('value', j);
					option.innerHTML = window.files[j][0];
					r1.appendChild(option);
				}
			}
			fr1.childNodes[0].appendChild(l1);
			fr1.childNodes[1].appendChild(r1);
			fieldset.appendChild(fr1);
		}
				
		// id
		var hidden = document.createElement('input');
		hidden.setAttribute('type', 'hidden');
		hidden.setAttribute('name', 'file'+i+'_id');
		hidden.setAttribute('id', 'file'+i+'_id');
		hidden.setAttribute('value', '');
		fieldset.appendChild(hidden);
		
		// file
		var fr3 = createFormRow('file'+i+'_row');
		var l3 = document.createElement('label');
		l3.setAttribute('for', 'file'+i);
		if (showFileDropdown) {
			l3.innerHTML = 'OR upload a new one:';
		} else {
			l3.innerHTML = 'Choose a file to upload:';
		}
		var r3 = document.createElement('input');
		r3.setAttribute('id', 'file'+i);
		r3.setAttribute('name', 'file'+i);
		r3.setAttribute('type', 'file');
		fr3.childNodes[0].appendChild(l3);
		fr3.childNodes[1].appendChild(r3);
		fieldset.appendChild(fr3);
		
		// name
		var fr2 = createFormRow();
		var l2 = document.createElement('label');
		l2.setAttribute('for', 'file'+i+'_name');
		l2.innerHTML = 'File title:';
		var r2 = document.createElement('input');
		r2.setAttribute('size', '60');
		r2.setAttribute('id', 'file'+i+'_name');
		r2.setAttribute('name', 'file'+i+'_name');
		r2.setAttribute('type', 'text');
		fr2.childNodes[0].appendChild(l2);
		fr2.childNodes[1].appendChild(r2);
		fieldset.appendChild(fr2);
		
		// description
		var fr4 = createFormRow();
		var l4 = document.createElement('label');
		l4.setAttribute('for', 'file'+i+'_description');
		l4.innerHTML = 'File description:';
		var r4 = document.createElement('textarea');
		r4.setAttribute('cols', '60');
		r4.setAttribute('rows', '3');
		r4.setAttribute('id', 'file'+i+'_description');
		r4.setAttribute('name', 'file'+i+'_description');
		fr4.childNodes[0].appendChild(l4);
		fr4.childNodes[1].appendChild(r4);
		fieldset.appendChild(fr4);
		
		// members only
		if (!hideFilePermissions) {
			var fr5 = createFormRow();
			var l5 = document.createElement('label');
			l5.setAttribute('for', 'file'+i+'_members_only');
			l5.innerHTML = '';
			var r5 = document.createElement('input');
			r5.setAttribute('id', 'file'+i+'_members_only');
			r5.setAttribute('name', 'file'+i+'_members_only');
			r5.setAttribute('type', 'checkbox');
			var r5b = document.createElement('label');
			r5b.innerHTML = 'Members only';
			fr5.childNodes[0].appendChild(l5);
			fr5.childNodes[1].appendChild(r5);
			fr5.childNodes[1].appendChild(r5b);
			fieldset.appendChild(fr5);
		}
		
		// hidden entry for the filegroup
		var group = '';
		if (isANode(obj)) {
			group = obj.parentNode.id;
		} else {
			group = this.parentNode.id;
		}
		var splitted = group.split('_');
		var groupIndex = splitted[0].substring(9);
		var hidden = document.createElement('input');
		hidden.setAttribute('type', 'hidden');
		hidden.setAttribute('name', 'file'+i+'_filegroup');
		hidden.setAttribute('id', 'file'+i+'_filegroup');
//		hidden.setAttribute('value', groupIndex);
		hidden.setAttribute('value', fileGroup);
		fieldset.appendChild(hidden);
		
		var parent;
		if (isANode(obj)) {
			parent = obj.parentNode.parentNode;
		} else { 	
			parent = this.parentNode.parentNode;
		}
		
		// find the list element
		var children = parent.getElementsByTagName('ul');
		var fileList = children[0];
			
		// ...and append
		fileList.appendChild(li);
		ToolMan.dragsort().makeSortable(li);
		
		//make the inputs usable
		iniInput(r2);
		iniInput(r4);
		
		// increment the file index
		setFormElementValue('objext', 'file_index', ++i);
		
	}
}

function createFormRow(id) {
		var f = document.createElement('div');
		f.setAttribute('class', 'formRow');
		f.setAttribute('id', id);
		var fl = document.createElement('div');
		fl.setAttribute('class', 'formLeft');
		var fr = document.createElement('div');
		fr.setAttribute('class', 'formRight');
		f.appendChild(fl);
		f.appendChild(fr);
		return f;
}

function createFileGroupDiv(parentNodeName) {
	if (document.getElementById && document.getElementById('filegroup_name').value != '') {
		var i = getFormElementValue('objext', 'filegroup_index');
	
		var div = document.createElement('div');
		div.setAttribute('name', 'div_filegroup'+i);
		div.setAttribute('id', 'div_filegroup'+i);
		var h2 = document.createElement('h2');
		h2.innerHTML = document.getElementById('filegroup_name').value;
		h2.setAttribute('style', 'font-size: 20px; margin-top: 2em;');
		var p = document.createElement('p');
		p.setAttribute('style', 'color: #b6bdc7; margin: 0em;');
		var a1 = document.createElement('a');
		a1.setAttribute('name', 'link_filegroup'+i);
		a1.setAttribute('href', '#link_filegroup'+i);
		a1.innerHTML = 'Add a new file';
		addEvent(a1, "click", createFileFieldset);
		var bar = document.createTextNode(' | ');
		var a2 = document.createElement('a');
		a2.setAttribute('name', 'link_deleteFilegroup'+i);
		a2.setAttribute('href', '#link_deleteFilegroup'+i);
		a2.innerHTML = 'Delete this file group';
		addEvent(a2, "click", deleteFilegroup);
		p.appendChild(a1);
		p.appendChild(bar);
		p.appendChild(a2);
		var input = document.createElement('input')
		input.setAttribute('type', 'hidden');
		input.setAttribute('name', 'filegroup'+i+'_name');
		input.setAttribute('value', document.getElementById('filegroup_name').value);
		var ul = document.createElement('ul');
		ul.setAttribute('id', 'ul_filegroup'+i);
		ul.setAttribute('class', 'filelist');
		
		div.appendChild(input);	
		div.appendChild(h2);	
		div.appendChild(p);	
		div.appendChild(ul);	
		
		document.getElementById(parentNodeName).appendChild(div);
	
		// increment the file group index
		setFormElementValue('objext', 'filegroup_index', ++i);
	}
}

function deleteFilegroup(index) {
    // set the text fields to empty
    form['filegroup' + index + '_id'].value = "";
    form[item + '_name'].value = "";
    form[item + '_description'].value = "";
    
    // get the fieldset
    document.getElementById("li_"+item).style.display = 'none';
}

// allows users to replace a file in a branch/advert/etc form
function replaceFile(fileIndex) {
	if (document.getElementById) {
		var oldFileDiv = document.getElementById('div_file'+fileIndex+'_file');

		var newFileDiv = document.createElement('div');
		newFileDiv.setAttribute('class', 'formRight');
		var l = document.createElement('label');
		l.setAttribute('for', 'file'+fileIndex);
		l.innerHTML = 'Choose a file to upload:';
		var i = document.createElement('input');
		i.setAttribute('id', 'file'+fileIndex);
		i.setAttribute('name', 'file'+fileIndex);
		i.setAttribute('type', 'file');
		newFileDiv.appendChild(l);
		newFileDiv.appendChild(document.createElement('br'));
		newFileDiv.appendChild(i);
		
		oldFileDiv.parentNode.insertBefore(newFileDiv, oldFileDiv);
		oldFileDiv.style.display = 'none';
	}	
}

// when an objext is submitted, the order of the associated files is written to a hidden form element
// this allows users to change the order by dragging and dropping
function setFileOrder() {
	if (document.getElementById) {
		var form = getElementsByTagName('form')[0];
		var fileGroups = getElementsByTagName('ul');
		for (var i=0; i<fileGroups.length; i++) {
			
			var files = fileGroups[i].getElementsByTagName('li');
		}
	}	
} 


function iniInput(element){
	var view = element;

	// Events functions
	function edit(){
		this.focus();
	}
	function select(){
		this.select();
	}
	
	// Events declarations
	view.ondblclick = select
	view.onclick = edit
}

function iniRemoveButton(element, fileNumber) {
	element.onclick = function() {
		removeItem(this.form, fileNumber); 
		hideElement('div_'+fileNumber); 
		return false;
	}
} 	

function verticalOnly(item) {
	item.toolManDragGroup.verticalOnly()
}

function speak(id, what) {
	var element = document.getElementById(id);
	element.innerHTML = 'Clicked ' + what;
}

function saveOrder(item) {
}

// swaps a div displaying a value for a hidden input element with roughly the same name
// (one should have the id <name>_show, the second <name>_edit)
// to allow inline editing
function editInline(element) {
	element.style.display = 'none';
	inputId = element.id.substring(0, element.id.length - 5);
	inputDivId = inputId + '_edit'; 
	document.getElementById(inputDivId).style.display = 'inline';
	document.getElementById(inputId).focus();
}

function calculateSubscription() {
	sub = 0;
	if (document.join.sub_income[0].checked) {
		sub = 135;
	} else if (document.join.sub_income[1].checked) {
		sub = 270;
	} else {
		sub = 318;
	}
	
	if (document.join.sub_part_time[0].checked && !document.join.self_employed[0].checked) {
		if (document.join.sub_income[0].checked) {
			sub = '67.50';
		} else {
			sub = sub / 2.0;
		}
	}
	document.getElementById('sub_fee').innerHTML = '&pound;'+sub;
	document.join.sub_fee.value = sub;
}

function limitInput(textbox, limit, nextTextbox) {
	if (textbox.value.length > limit) {
		textbox.value = textbox.value.substr(0, limit);
		if (nextTextbox != null) {
			focus(nextTextbox);
		}
	}
}
