jQuery(document).ready(function($) {
	$('#area_subject').change(function() {
		updateMainSubjects(this.value);
	});
	$('#main_subject').change(function() {
		updateSubSubjects(this.value);
	});
	
	//add the jquery validation engine plugin to the stage 2 form
	$("#researcher-form2").validationEngine({
		success :  function() { 
			//on success disable the submit button
			$("#submit_stage2").attr('disabled','true');
			//show the process bar 
			$('#process_bar').fadeIn(500);
			$('#researcher-form2').form.submit();
		},
		failure : function() { 
		}
	})

	//add the jquery validation engine plugin to the stage 1 form
	$("#researcher-form").validationEngine({
		success :  false,
		failure : function() { }
	})

	
	var error_msg = $('#error_msg'),
		area_field = $('#area_subject'),
		subject_field = $('#main_subject'),
		level_field = $('#level'),
		all_fields = $([]).add(area_field).add(subject_field).add(level_field);


	//add a function that checks if the user hasn't select either area of qualification - main subject - level
	function checkFields(field_id,msg) {
		if ( field_id.val() == '' ) {
			field_id.addClass('ui-state-error');
			error_msg.text(msg).effect('highlight',{},1500);
			$('#level').change(function() {
				if($('#level').val() != '') {
					removeErrorMessage('level');
				}
			});
			return false;
		} else {
			return true;
		}
	}

	//properties-functionality of the dialog box
	$('#dialog').dialog({
		bgiframe: true,
		autoOpen: false,
		resizable: false,
		//height: auto,
		minHeight: 400,
		width: 400,
		modal: true,
		buttons: {
			'Add Qualification': function() {
			
				var no_error = true;
				all_fields.removeClass('ui-state-error');
				subject_field = $('#main_subject'),
				no_error = no_error && checkFields(area_field,'Please select an area of qualification');
				no_error = no_error && checkFields(subject_field,'Please select a subject');
				no_error = no_error && checkFields(level_field,'Please select a level');
			
				var area = $('#area_subject :selected').text(),
					subject = $('#main_subject :selected').text(),
					subject_id = $('#main_subject').val(),
					//subjects = $('#sub_subjects :checkbox:checked').text(),
					level = $('#level :selected').text(),
					level_id = $('#level').val();
				
				if (no_error) {	
					// if area of qualification is Law then Loop through all the selected subjects
					if ( area == 'Law'){
						// go through all the selected subjects from the multiple drop down box 
						$('#main_subject :selected:selected').each(function(i, o){
							// create a random number which will go beside the subject id in order to distinguise the case
							// of rows with the same main subject
							var random_number=Math.floor(Math.random()*101);
							//show the table
							$('#qualifications_table thead').show();
							//insert the new row in the table
							$('#qualifications_table tbody').fadeIn(500).append('<tr id=row'+o.value+'-'+random_number+' name=row_name class=law_row>' + '<td>' + area + '</td>' + '<td>' + o.text + '</td>' + '<td style="width:270px;"><ul></ul></td>' + '<td>' + level + '</td><td style="width:50px;"><a id='+o.value+'-'+random_number+'>remove</a></td>'+'</tr>');
							//pass the ids of subject-level-sub subjects to a non displayed div as checked checkboxes
							$('#hidden_div').append('<input type="checkbox" name="subject-level[]" id="'+o.value+'-'+random_number+'" value="'+o.value+'|'+level_id+'| " checked/>');
							
							//add the remove button functionality
							$('#'+o.value+'-'+random_number+'').click(function() {
								//do a fade out effect before removing the row
								$('#qualifications_table tr:#row'+o.value+'-'+random_number+'').fadeOut(400,function(){
									//removeRow(this.id);
									$('#qualifications_table tr:#row'+o.value+'-'+random_number+'').remove();
									//remove also the checkbox
									$('#'+o.value+'-'+random_number+'').remove();
									update_error_msg_pos();
								});
							});
						});
					}else{
						var sub_subjects_names = '',
							sub_subjects_ids = '';
						//capture the sub subjects that have been checked
						$('#sub_subjects :checkbox:checked').each(function(i, o){
							sub_subjects_names += '<li>' + o.id + '</li>';
							sub_subjects_ids += o.value + ',';
						});
						//get rid of the last comma
						sub_subjects_ids = sub_subjects_ids.slice(0, -1);
						// create a random number which will go beside the subject id in order to distinguise the case
						// of rows with the same main subject
						var random_number=Math.floor(Math.random()*101);
						//show the table
						$('#qualifications_table thead').show();
						//insert the new row in the table
						$('#qualifications_table tbody').fadeIn(500).append('<tr id=row'+subject_id+'-'+random_number+'>' + '<td>' + area + '</td>' + '<td>' + subject + '</td>' + '<td style="width:270px;"><ul>' + sub_subjects_names + '</ul></td>' + '<td>' + level + '</td><td style="width:50px;"><a id='+subject_id+'-'+random_number+'>remove</a></td>'+'</tr>');
						//pass the ids of subject-level-sub subjects to a non displayed div as checked checkboxes
						$('#hidden_div').append('<input type="checkbox" name="subject-level[]" id="'+subject_id+'-'+random_number+'" value="'+subject_id+'|'+level_id+'|'+sub_subjects_ids+'" checked/>');
						
						//add the remove button functionality
						$('#'+subject_id+'-'+random_number+'').click(function() {
							//do a fade out effect before removing the row
							$('#qualifications_table tr:#row'+subject_id+'-'+random_number+'').fadeOut(400,function(){
								//removeRow(this.id);
								$('#qualifications_table tr:#row'+subject_id+'-'+random_number+'').remove();
								//remove also the checkbox
								$('#'+subject_id+'-'+random_number+'').remove();
								update_error_msg_pos();
							});
						});
					}
					//remove the error msg
					$('.hidden_fieldformError').fadeOut(500);
					$('#hidden_field_div').html("<input type='text' id='hidden_field' name='hidden_field' value='1' size='5' class='validate[custom[add_button]]' style='display:none;' /> ");
					
					//update the position of error messages
					update_error_msg_pos();
					
					//close the dialog when finishing with the functionality of add qualification button			
					$(this).dialog('close');
				}
			},
			Cancel: function() {
				$(this).dialog('close');
			}
		}
 	});
	$('#add_qualification').click(function() {
			$('#dialog').dialog('open');
	})
	//add styling to buttons
	.hover(
		function(){ 
			$(this).addClass('ui-state-hover'); 
		},
		function(){ 
			$(this).removeClass('ui-state-hover'); 
		}
	).mousedown(function(){
		$(this).addClass('ui-state-active'); 
	})
	.mouseup(function(){
		$(this).removeClass('ui-state-active');
	});
});

/*
* update the position of error message
* for the error msg that are below the qualifications table
*/
function update_error_msg_pos(){
//update the position of error messages
	var error_position='';
	//for each error class place the error msg 30px above the field
	for(z = 1; z < 7; z++){
		error_position = $('#testanswer'+z).offset().top - 30;
		$('.testanswer'+z+'formError').css({
			top:error_position
		})
	}
	return true;
}

/*
* remove error message from a field
* @param field - the id of the field
*/
function removeErrorMessage(field){
	//remove class that makes the field red
	$('#'+field).removeClass('ui-state-error');
	//hide the error message
	$('#error_msg').html('');
	
	return true;
}

/*
* update the main subjects options on the drop down box 
* according to the selected area of qualification
* @param area_id - the id of the area of qualification
*/
function updateMainSubjects(area_id){
	$.get('xhr_proxy.php?req=main_subject', {sub_id: ''+area_id+''}, function(data){
		if(data.length >0) {
			//if area of qualification is law then load the multiple select plugin functionality
			if (area_id == 1009){
				//add the list options on the div outside
				$('#main_subjects_div').html(data);
				$('#main_subjects_div').append("<select name='main_subject[]' title='Please select Subjects' multiple='multiple' id='main_subject'></select>");
				
				//remove error message from area_subject field
				removeErrorMessage('area_subject');
				
				//hide the label and the list for the sub subjects
				$('#label_for_sub_subjects').fadeOut(200);
				$('#sub_subjects').html('');
				
				// these all process is being done because IE do not accept the printed response of printed options from ajax
				//split the values of each id
				var values =$('#sub_ids_array').val().split(',');
				var options = $('#main_subjects_array').val().split(',');
				for(i = 1; i < values.length; i++){
					var newOption  = document.createElement('option');
					newOption.text = options[i];
					newOption.setAttribute('value', values[i]);
					
					//check if the user has already added subject-s of Law qualification
					//if he hasn't done then print all the list of law subject that all the Law student have been teached
					if ($('[name=row_name]').hasClass('law_row') == false){
						if( options[i]=='Constitutional/administrative Law' || options[i]=='Contract Law' || options[i]=='Criminal Law' || options[i]=='Equity Law' || options[i]=='European Law' || options[i]=='Human Rights' || options[i]=='International Law' || options[i]=='Land/property Law' || options[i]=='Landlord & Tenant Law' || options[i]=='Negligence Law' || options[i]=='Public Law' || options[i]=='Trusts Law' ){
							newOption.setAttribute('selected', 'selected');
						}
					}
					
					try {
						document.getElementById("main_subject").add(newOption, null); // standards compliant
					} catch(ex) {
						document.getElementById("main_subject").add(newOption); // IE only
					}
				}
				//add the multiple select function from asmselect jquery plugin
				$("select[multiple]").asmSelect({
					addItemTarget: 'bottom',
					animate: true,
					highlight: false,
					sortable: false
				});
			}else{
				//add the list options on the div outside
				$('#main_subjects_div').html(data);
				$('#main_subjects_div').append("<select name='main_subject[]' id='main_subject'></select>");
				//remove error message from area_subject field
				removeErrorMessage('area_subject');
				
				//hide the label and the list for the sub subjects
				$('#label_for_sub_subjects').fadeOut(200);
				$('#sub_subjects').html('');
				
				// these all process is being done because IE do not accept the printed response of printed options from ajax
				//split the values of each id
				var values =$('#sub_ids_array').val().split(',');
				var options = $('#main_subjects_array').val().split(',');
				for(i = 0; i < values.length; i++){
					var newOption  = document.createElement('option');
					newOption.text = options[i];
					newOption.setAttribute('value', values[i]);
					
					try {
						document.getElementById("main_subject").add(newOption, null); // standards compliant
					} catch(ex) {
						document.getElementById("main_subject").add(newOption); // IE only
					}
				}
				$('#main_subject').change(function() {
					updateSubSubjects(this.value);
				});
			} 
		}
	});
}
 
/*
* update the sub subjects checkboxes according to the selected main subject
* @param main_subject_id - the id of the main subject
*/
function updateSubSubjects(main_subject_id){
	$.get('xhr_proxy.php?req=sub_subject', {sub_id: ''+main_subject_id+''}, function(data){
		if(data.length >0) {
			//remove error message from main subject field
			removeErrorMessage('main_subject');
			//show the label of sub subjects
			$('#label_for_sub_subjects').fadeIn(200);
			//add the checkboxes
			$('#sub_subjects').fadeIn().html(data);
		}else{
			$('#label_for_sub_subjects').hide(200);
			$('#sub_subjects').html('');
		}
	});
}
