// Competiton Javascript
// By: David Rugendyke


window.addEvent('domready', function() {
		
	var Categories = new CompFormCategory();
	var FormSubmit = new CompFormSubmit();
	
	
});


// Competition Form Class
var CompFormCategory = new Class({
	
	// Class vars
	options: {
		catSelectCount: 0,
		studentCount: 0
	},
	
	// Initialise the class
    initialize: function(){
		
		var Ob = this;
		this.studentCount = 3;
		this.addCategoryEvents();
		// Add an event to the add student div
		$('student_add').addEvent('click', function(){
				Ob.studentCount++;
				Ob.addStudentEntry();		 
		});
    },
	
	// Adds events to all the category checkboxes
	addCategoryEvents: function(){

		var Ob = this;
		var compEl = $$('.comp_cat'); 
		// Attach an onlick event to each checkbox
		compEl.each(function(el) {
				
				$(el).addEvent('click', function(){
						// If they checked this one
						if($(el).get('checked')) { 
								Ob.CategoryCountToggle('add'); 
								Ob.CategoryUploadField(el);
							}
							else{ 
								Ob.CategoryCountToggle('del'); 
								Ob.CategoryUploadFieldRemove(el);
						}
				}.bind(this));
			
			});
	},
	
	// Adjust the count for many categories are selected
	CategoryCountToggle: function(action){
		
		if(action == 'add') { this.catSelectCount++; }
		if(action == 'del') { this.catSelectCount--; }
		
		if(this.catSelectCount < 0) { this.catSelectCount = 0; }	
	},
	
	// Add a new upload form for a selected category
	CategoryUploadField: function(el) {
		
		var text = $(el).get('value');
		var id = $(el).get('id');
		
		var formatDiv = '<div><b>MP3 Format</b><small> -  5MB size limit</small></div><div style="margin-left: 15px"><input class="fileMP3" type="file" name="fileUploadFormat_'+id+'" id="fileUploadFormat_'+id+'"></div>';
		var lyricsDiv = '<div><b>Lyrics</b><small> -  1MB size limit - Only Word, PDF</small></div><div style="margin-left: 15px"><input class="fileLyrics" type="file" name="fileUploadLyrics_'+id+'" id="fileUploadLyrics_'+id+'"></div>';
		
		// A few cats only have one option or the other
		if(id == 'cat_5') {	lyricsDiv = '';	 }
		if(id == 'cat_8') { formatDiv = ''; }
		
		var uploadDiv = '<div id="upload_div_'+id+'" style="padding: 3px;"><div style="margin-left: 12px;"><h5>'+text+'</h5></div><div style="padding-left: 40px;">'+formatDiv+lyricsDiv+'</div><input type="hidden" name="fileDesc_'+id+'" id="fileDesc_'+id+'" value="'+text+'"><br><hr width="70%"></div>';

		var currentHTML = $('mp3_upload').get('html');
		var newHTML = currentHTML+uploadDiv;
		$('mp3_upload').set('html', newHTML);
	},
	
	// Removes an upload field
	CategoryUploadFieldRemove: function(el) {
		
		var id = $(el).get('id');
		var upload_div = 'upload_div_'+id;
		
		if($(upload_div)) {
			$(upload_div).dispose();
		}
		
	},
	
	// Add a new student entry field
	addStudentEntry: function() {
		
		// Clone the first student entry
		var studentDiv = $('student[0]').clone(true, true);
		var studentHTML = $(studentDiv).get('html');
		studentHTML = studentHTML.replace(/\[0\]/g, '['+this.studentCount+']');
		studentHTML = studentHTML.replace(/0\_/g, ''+this.studentCount+'_');
		$(studentDiv).set('html', studentHTML);
		$(studentDiv).set('id', 'student['+this.studentCount+']');
		$(studentDiv).inject('student_block');
		//alert('Dave');
	}
	
	
});


// Handles submission of the form
var CompFormSubmit = new Class({
	
	
	// Class vars
	options: {
		error: null,
		error_id: null
	},
	
	// Initialise the class
    initialize: function(){
		
		// Add an event onto the submit button and bind it to this object
		$('comp_submit').addEvent('click', this.processSubmit.bind(this));
    },
	
	// Process the submission
	processSubmit: function(){
		
		this.error = null;
		this.processValidate();
		
		if(this.error == null) {
			
			$('loading').setStyle('display', 'inline');
			// No errors? Submit away - leave a little delay for the loading image to kickin
			setTimeout("document.compForm.submit();", 1000);
			
		}else{
			alert(this.error);	
			// Now focus the field
			$(this.error_id).focus();
		}
	},
	
	// Check the form
	processValidate: function(){
		
		var Ob = this;
		var count = 0;
		var name_complete;
	
		// Get all the student names entered and check their data
		var studentNames = $$('.student_name'); 
		// Check each student name entered has its appropriate fields done too
		studentNames.each(function(el) {
					
					count++;
					
					var id = $(el).get('id');
					var name = $(el).get('value');
					// Get the row ID
					var idParts = id.split('_');
					var rowID = idParts[0]; 
						
					if(name) {
						
					 	// Now check for the other student fields
						var dob_d = $(rowID+'_dob_d').get('value').toInt();
						// If its not a number, its an error
						if(isNaN(dob_d)) { 
							Ob.error = 'Please enter your students day of birth.';	
							Ob.error_id = rowID+'_dob_d';
						}
						// Month
						var dob_m = $(rowID+'_dob_m').get('value').toInt();
						// If its not a number, its an error
						if(isNaN(dob_m)) { 
							Ob.error = 'Please enter your students month of birth.';	
							Ob.error_id = rowID+'_dob_m';
						}
						// Year
						var dob_y = $(rowID+'_dob_y').get('value').toInt();
						// If its not a number, its an error
						if(isNaN(dob_y)) { 
							Ob.error = 'Please enter your students year of birth.';	
							Ob.error_id = rowID+'_dob_y';
						}
						// Grade
						if(!$(rowID+'_grade').get('value')) {
							Ob.error = 'Please enter a grade for your student.';	
							Ob.error_id = rowID+'_grade';
						}
						
						name_complete = true;
							
					 }
			});
		
		if(!name_complete) {
			this.error = 'Please enter at least one students details.';	
			this.error_id = '0_name';
		}
		
		// Now check the rest of the form details 
		if(!$('school_name').get('value')) {
			Ob.error = 'Please enter a school name.';	
			Ob.error_id = 'school_name';
		}
		
		if(!$('school_postal_addr').get('value')) {
			Ob.error = 'Please enter a school postal address.';	
			Ob.error_id = 'school_postal_addr';
		}
		
		if(!$('school_city').get('value')) {
			Ob.error = 'Please enter the schools city.';	
			Ob.error_id = 'school_city';
		}
		
		if(!$('state').get('value')) {
			Ob.error = 'Please enter the school state.';	
			Ob.error_id = 'state';
		}
		
		if(!$('postcode').get('value')) {
			Ob.error = 'Please enter the school postcode.';	
			Ob.error_id = 'postcode';
		}
		
		if(!$('school_ph_no').get('value')) {
			Ob.error = 'Please enter the school phone number.';	
			Ob.error_id = 'school_ph_no';
		}
		
		if(!$('school_email').get('value')) {
			Ob.error = 'Please enter the school email address.';	
			Ob.error_id = 'school_email';
		}
		
		if(!$('teacher_name').get('value')) {
			Ob.error = 'Please enter the teachers name.';	
			Ob.error_id = 'teacher_name';
		}
		
		if(!$('guardian_name').get('value')) {
			Ob.error = 'Please enter the guardians name.';	
			Ob.error_id = 'guardian_name';
		}
		
		if(!$('guardian_email').get('value')) {
			Ob.error = 'Please enter the guardians email';	
			Ob.error_id = 'guardian_email';
		}
		
		if(!$('guardian_ph_no').get('value')) {
			Ob.error = 'Please enter the guardians phone number.';	
			Ob.error_id = 'guardian_ph_no';
		}
		
		if(!$('song_title').get('value')) {
			Ob.error = 'Please enter the song title.';	
			Ob.error_id = 'song_title';
		}
		
		// Count the file mp3 uploads
		var fileMP3s  = $$('.fileMP3');
		var fileMP3s_count = fileMP3s.length;
		// Count the lyric uploads
		var fileLyrics  = $$('.fileLyrics'); 
		var fileLyrics_count = fileLyrics.length;
		
		// Now loop through those and check they have a file entered 
		fileMP3s.each(function(el) {
				// Check for mp3 files only
				if(!$(el).get('value').test(".mp3", "i")) {
					Ob.error = 'Please enter only MP3 files for the song files.';	
					Ob.error_id = $(el).get('id');
				}
			
		});
		
		// Now loop through those and check they have a file entered 
		fileLyrics.each(function(el) {
				
				var lyricError;
				// Check for pdf, word files only
				if(!$(el).get('value').test(".pdf", "i") && !$(el).get('value').test(".doc", "i")) { lyricError = true;	}
				
				if(lyricError == true) {
					Ob.error = 'Please enter only Word (.doc) or PDF (.pdf) files for the song lyrics.';	
					Ob.error_id = $(el).get('id');
				}
			
		});
		
		var totalFiles = fileMP3s_count + fileLyrics_count;

		if(totalFiles <= 0) {
			Ob.error = 'Please select at least one category to enter.';	
			Ob.error_id = 'cat_1';
		}
		
		
		if (!$('howdidyouhear').get('value') == 'Other') {
			if (!$('other_how').get('value')) {
				Ob.error = 'Please specify how you heard about the Competition';
				Ob.error_id = 'other_how';
			}
		} else {
			if ($('howdidyouhear').get('value') == ""){ 
				Ob.error = 'Please select how you heard about the Competition';
				Ob.error_id = 'howdidyouhear';
			}
		}
		
		
		
		// Check they have checked the T&C box
		if(!$('accept_tc').get('checked')) {
			Ob.error = 'You must agree to our Terms and Conditions before entering.';	
			Ob.error_id = 'accept_tc';
		}
	}
	
 });
	

