jQuery(document).ready(function($) {

	//on change of the area of qualification pull down list in the dialog box
	$('#area_subject0').change(function() {
		updateMainSubjects(this.value,0);
	});
	$('#area_subject1').change(function() {
		updateMainSubjects(this.value,1);
	});
	//on change of the main subject pull down list in the dialog box
	$('#main_subject').change(function() {
		updateSubSubjects(this.value);
	});
	
	//add the multiple select function from asmselect jquery plugin
	$('#bidding_subjects_table select[multiple]').asmSelect({
		addItemTarget: 'bottom',
		animate: true,
		highlight: false,
		sortable: false
	});
	
	// on click of a specialism box update the specialisms
	$('.edit_checkbox').click(function() {
		var data = this.value.split('-');
		var checked = "";
		if ($('#'+this.value).is(':checked')){
			checked = 1;
		}else{
			checked = 0;
		}
		updateSpecialisms(data[0],data[1],data[2],checked);
	});
	$('.edit_specialism').click(function() {
		var data = this.id.split('-');
		edit_specialism(data[0],data[1]);
	});
	
	var error_msg0 = $('#error_msg0'),
		area_field0 = $('#area_subject0'),
		subject_field0 = $('#main_subject0'),
		level_field0 = $('#level0'),
		all_fields0 = $([]).add(area_field0).add(subject_field0).add(level_field0);
		
	var error_msg1 = $('#error_msg1'),
		area_field1 = $('#area_subject1'),
		subject_field1 = $('#main_subject1'),
		level_field1 = $('#level1'),
		all_fields1 = $([]).add(area_field1).add(subject_field1).add(level_field1);

	/*
	* check if the user hasn't select either area of qualification - main subject - level
	* @param field_id - the id of the field
	* @param msg -  the message to be printed
	* @param staff - is 1 for staffwriter subjects and 0 for bidding subjects
	*/
	function checkFields(field_id,msg,staff) {
		if ( field_id.val() == '' ) {
			field_id.addClass('ui-state-error');
			if ( staff == 1){
				error_msg1.text(msg).effect('highlight',{},1500);
			}else{
				error_msg0.text(msg).effect('highlight',{},1500);
			}
			$('#level'+staff).change(function() {
				if($('#level'+staff).val() != '') {
					removeErrorMessage('level',staff);
				}
			});
			return false;
		} else {
			return true;
		}
	}
	//properties-functionality of the dialog box for request of bidding subjects  
	$('#dialog0').dialog({
		bgiframe: true,
		autoOpen: false,
		resizable: false,
		//height: auto,
		minHeight: 500,
		width: 400,
		modal: true,
		buttons: {
			'Submit request': function() {
				var no_error = true;
				subject_field0 = $('#main_subject0'),
				all_fields0.removeClass('ui-state-error');
				no_error = no_error && checkFields(area_field0,'Please select an area of qualification',0);
				no_error = no_error && checkFields(subject_field0,'Please select a subject',0);
				no_error = no_error && checkFields(level_field0,'Please select a level',0);

				var area = $('#area_subject0 :selected').text(),
					subject = $('#main_subject0 :selected').text(),
					subject_id = $('#main_subject0').val(),
					level = $('#level0 :selected').text(),
					level_id = $('#level0').val();
				
				if (no_error) {
					//submit the request
					add_bid_request(0);
					//change the source of ui_css to test.css
					setActiveStyleSheet('ui_css','test.css');
					//close the dialog when finishing with the functionality of Submit request button					
					$(this).dialog('close');
				}
			},
			Cancel: function() {
				setActiveStyleSheet('ui_css','test.css');
				$(this).dialog('close');
			}
		}
 	});	
	//properties-functionality of the dialog box for request of staffwriter subjects
	$('#dialog1').dialog({
		bgiframe: true,
		autoOpen: false,
		resizable: false,
		//height: auto,
		minHeight: 500,
		width: 400,
		modal: true,
		buttons: {
			'Submit request': function() {
				var no_error = true;
				subject_field1 = $('#main_subject1'),
				all_fields1.removeClass('ui-state-error');
				no_error = no_error && checkFields(area_field1,'Please select an area of qualification',1);
				no_error = no_error && checkFields(subject_field1,'Please select a subject',1);
				no_error = no_error && checkFields(level_field1,'Please select a level',1);				
			
				var area = $('#area_subject1 :selected').text(),
					subject = $('#main_subject1 :selected').text(),
					subject_id = $('#main_subject1').val(),
					level = $('#level1 :selected').text(),
					level_id = $('#level1').val();
				
				if (no_error) {
					//submit the request
					add_bid_request(1);
					//change the source of ui_css to test.css
					setActiveStyleSheet('ui_css','test.css');	
					//close the dialog when finishing with the functionality of Submit request button					
					$(this).dialog('close');
				}
			},
			Cancel: function() {
				setActiveStyleSheet('ui_css','test.css');
				$(this).dialog('close');
			}
		}
 	});
	$('#add_qualification0').click(function() {
		setActiveStyleSheet('ui_css','bidding_css.css');
		$('#dialog0').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');
	});
	$('#add_qualification1').click(function() {
		setActiveStyleSheet('ui_css','staffwriter_css.css');
		$('#dialog1').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');
	});
});

/*
* set active css in order to change some attributes from the ui all theme css
* @param title - the title attribute of the link tag to be updated
* @param css_href -  the href of the link tag
*/
function setActiveStyleSheet(title,css_file) {
	var i, a, main;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++){
		if(a.getAttribute("title") == title) {
			document.getElementsByTagName('link')[i].href = css_file;
		}
	}
}

/*
* update the researchers' specialisms
* @param rid - the researchers' id
* @param sub_id - the specialism id
* @param parent_sub_id - the main subject id
* @param checked - this parameter specifies if either the checkbox is checked or unchecked
*/
function updateSpecialisms(rid,sub_id,parent_sub_id,checked){
	if (checked == 1){
 		$.post('ajax.php?req=add_specialisms', {rid: ''+rid+'',sub_id: ''+sub_id+'',parent_id:''+parent_sub_id+''}, function(data){
			if(data.length >0) {
				//show the msg
				$('#'+rid+'-'+sub_id+'-msg').fadeIn(300).html('Specialism added');
				//hide the msg
				$('#'+rid+'-'+sub_id+'-msg').fadeOut(1000);
			}else{
				//show the msg
				$('#'+rid+'-'+sub_id+'-msg').fadeIn(300).html('Unable to add the specialism');
				//hide the msg
				$('#'+rid+'-'+sub_id+'-msg').fadeOut(1000);
			}
		});
	}else{
		$.post('ajax.php?req=remove_specialisms', {rid: ''+rid+'',sub_id: ''+sub_id+'',parent_id:''+parent_sub_id+''}, function(data){
			if(data.length >0) {
				$('#'+rid+'-'+sub_id+'-msg').fadeIn(300).html('Specialism removed');
				$('#'+rid+'-'+sub_id+'-msg').fadeOut(1000);
			}else{
				$('#'+rid+'-'+sub_id+'-msg').fadeIn(300).html('Unable to remove the specialism');
				$('#'+rid+'-'+sub_id+'-msg').fadeOut(1000);
			}
		});
	}
}

/*
* make the specialisms field editable
* @param rid - the researchers' id
* @param spec_id - the specialism id
*/
function edit_specialism(rid,spec_id){
	$('#'+rid+spec_id).fadeIn(500);
	$('#'+rid+'-'+spec_id).hide();
}

/*
* submit the request new subject form using the jquery form plugin 
* @param staff - is 1 for staffwriter subjects and 0 for bidding subjects
*/
function add_bid_request(staff){
	var options = {  beforeSubmit:  showRequest,
					success:showResponse };
	//submit the form using the jquery form plugin
	$('#my-form'+staff).ajaxSubmit(options); 
	return false; 
}

// pre-submit callback 
function showRequest(formData, jqForm, options){
	// formData is an array; here we use $.param to convert it to a string to display it 
    // but the form plugin does this for you automatically when it submits the data 
    var queryString = $.param(formData); 
 
    // jqForm is a jQuery object encapsulating the form element.  To access the 
    // DOM element for the form do this: 
    // var formElement = jqForm[0]; 
 
   // alert('About to submit: \n\n' + queryString); 
 
    // here we could return false to prevent the form from being submitted; 
    // returning anything other than false will allow the form submit to continue 
    return true; 
}

/*
* post-submit callback 
* @param responseText - is the XMLHttpRequest object's responseText property  
* @param statusText -  
*/
function showResponse(responseText, statusText){
	if ( statusText == 'success' ){
		var row_elements = responseText.split('|');
		//if it is a bidding subject
		if (row_elements[3] == 0){
			$('#bidding_subjects_table tbody').fadeIn(500).append('<tr><td><b>' + row_elements[0] + '</b><br /><span style="color:red;font-size:9px;">This subject is awaiting verification</span></td>' + '<td style="width:270px;"><ul>' + row_elements[1] + '</ul></td>' + '<td>' + row_elements[2] + '</td></tr>');
		}else{
			$('#staffwriter_subjects_table tbody').fadeIn(500).append('<tr><td><b>' + row_elements[0] + '</b><br /><span style="color:red;font-size:9px;">This subject is awaiting verification</span></td>' + '<td style="width:270px;"><ul>' + row_elements[1] + '</ul></td>' + '<td>' + row_elements[2] + '</td></tr>');
		}
	}else{
		alert('There was a problem adding your request. Please try again');
	}
}

/*
* remove error message from a field
* @param field - the id of the field
* @param staff - is 1 for staffwriter subjects and 0 for bidding subjects
*/
function removeErrorMessage(field,staff){
	//remove class that makes the field red
	$('#'+field+staff).removeClass('ui-state-error');
	//hide the error message
	$('#error_msg'+staff).html('');
	
	return true;
}

/*
* update the main subjects options on the drop down box 
* according to the selected area of qualification on the dialog box
* @param area_id - the id of the area of qualification
* @param staff - is 1 for staffwriter subjects and 0 for bidding subjects
*/
function updateMainSubjects(area_id,staff){
	$.post('ajax.php?req=main_subject', {sub_id: ''+area_id+'',staff: ''+staff+''}, function(data){
		if(data.length >0) {
			//add the list options on the div outside
			$('#main_subjects_div'+staff).html(data);
			$('#main_subjects_div'+staff).append("<select name='main_subject' class='main_subject' id='main_subject"+staff+"'></select>");
			//remove error message from area_subject field
			removeErrorMessage('area_subject',staff);
			
			//hide the label and the list for the sub subjects
			$('#label_for_sub_subjects').fadeOut(200);
			$('#sub_subjects'+staff).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'+staff).val().split(',');
			var options = $('#main_subjects_array'+staff).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"+staff+"").add(newOption, null); // standards compliant
				} catch(ex) {
					document.getElementById("main_subject"+staff+"").add(newOption); // IE only
				}
			}
			$('#main_subject'+staff).change(function() {
				updateSubSubjects(this.value,staff);
			});
		}
	});
}

/*
* update the sub subjects checkboxes according to the selected main subject on the dialog box
* @param main_subject_id - the id of the main subject
* @param staff - is 1 for staffwriter subjects and 0 for bidding subjects
*/
function updateSubSubjects(main_subject_id,staff){
	$.post('ajax.php?req=sub_subject', {sub_id: ''+main_subject_id+'',staff: ''+staff+''}, function(data){
		if(data.length >0) {
			//remove error message from main subject field
			removeErrorMessage('main_subject',staff);
			//show the label of sub subjects
			$('#label_for_sub_subjects'+staff).fadeIn(200);
			//add the checkboxes
			$('#sub_subjects'+staff).fadeIn().html(data);
		}else{
			$('#label_for_sub_subjects'+staff).hide(200);
			$('#sub_subjects'+staff).html('');
		}
	});
}