/**
  * Changes the object for a text field
  */

function Changer(activator){
	activator.onclick=this.swap;
}  
Changer.prototype={
	swap:function (e){
		
	//Set the activator object;
	var activator=this;
	
	var parent=this.parentNode;
	
	try{
	//find the select of the parentNode
	var select=parent.getElementsByTagName('select')[0];
	
	//Create a new text field
	var text=document.createElement('input');
	text.name=select.name;
	text.type='text';
	text.className='form_field';
	
	//Replace the select with the text field
	parent.replaceChild(text,select);
	
	activator.select=select;
	
	activator.firstChild.nodeValue='Selection';
	}
	catch(e)
	{
		var text=parent.getElementsByTagName('input')[0];
		//Replace the select with the text field
		parent.replaceChild(activator.select,text);
		activator.firstChild.nodeValue='Custom';
	}
	
	
	
	return false;
}
}

/**
  * Checks all fields inside a form and spurs erros if some arent valid
  */
function form_verification(e){
	//Create the event abstractor
	var event=new EventAbstractor(e);
	
	var form=this.form;
	var result=document.getElementById('result');
	var errortext='Fields marked with red must be filled in order post the form.'
	clearResult=true;
	
	//chech all input field inside the form
	var input=form.getElementsByTagName('input');
	for(var i=0;i<input.length;i++)
	{
		if (input[i].type!='text' && input[i].type!='file') continue;
		if (input[i].value.length==0){
			input[i].style.border='1px solid red';
			event.preventDefault();
			result.innerHTML=errortext;
			clearResult=false;
			
		}
		else{
			input[i].style.border='';
		}
		
	}
	
	var textarea=form.getElementsByTagName('textarea')[0];
	if (textarea.value.length==0){
		textarea.style.border='1px solid red';
		event.preventDefault();
		result.innerHTML=errortext;
		clearResult=false;
	}
	else{
		textarea.style.border='';	
	}
	
	//Clear the result if no errors are found
	if(clearResult) result.innerHTML='';
	
	
}

//This function changes the selected carrer
function change_career(career_name){
	var subject=document.getElementById('subject');
	for(var i=0;i<subject.options.length;i++){
		if (subject.options[i].text==career_name){
			subject.options[i].selected=true;
			break;
		}
	}
}

window.onload=function(e){
	//attach event handlers
	var edit_title=document.getElementById('edit_title');
	var changer_title=new Changer(edit_title);
	
	var edit_subject=document.getElementById('edit_subject');
	var edit_subject=new Changer(edit_subject);
	
	//Add the submit conctroll handler
	var submit=document.getElementById('submit');
	submit.onclick=form_verification;
}