// **************************
//	QUIZZES
// **************************

/* ajax func to submit send to friend form */
function loadAjaxUrl(url, htmlElementToReplaceId, loadingType){
	var myAjax = new Ajax(url, {
		method: 'get',
		evalScripts: true,
		getHeader: true,
    	update: htmlElementToReplaceId,
		onRequest: function() {
						var loadinghtml = '<div style="height:110px;padding-top:80px;"><span id="mlLoading">Loading</span></div>';
						$('quizSendFormHolder').setHTML(loadinghtml);
					},
		onComplete:	function(){
						setDefaultSearchText();
						hijaxSendForm();
					}
	});	
	myAjax.request();
};


function hijaxSendForm() {	

		$('quizSendForm').addEvent('submit', function(e){
			e = new Event(e).stop();
			var action = this.getProperty('action');
			var yname = this.yourName.value;
			var yemail = this.yourEmail.value;
			var fname = this.friendName.value;
			var femail = this.friendEmail.value;
			url = 'http://'+servername+action+'?yourName='+yname+'&yourEmail='+yemail+'&friendName='+fname+'&friendEmail='+femail;
			// http://local.take40.com/artists/quizzes/sendToFriend?yourName=vic&yourEmail=vic.nguyen%40gmail.com&friendName=victor&friendEmail=vnguyen%40mcmentertainment.com
			// alert(url);
			loadAjaxUrl(url, 'quizSendFormHolder', 'send');
			
		});
}




/* Validate Quiz */
function validateQuiz() {
	
	var answersprovided = 0;
	
	var quizarray = $$('div.quizQuestion');
	
	quizarray.each(function(question){
		var answers = question.getElements('input');
		var questionvalid = false;
		answers.each(function(choice){
			if (choice.checked) {
				answersprovided = answersprovided + 1
				questionvalid = true;
			}
		});
		if (questionvalid == false) {
			question.addClass('quizQuestionError');
		} else {
			question.removeClass('quizQuestionError');
		}
	});
	
	var quizlength = quizarray.length;
	
	if (answersprovided < quizlength) {
		return false;
	} else {
		return true;
	}

	
}



// **************************
//	DOM READY	
// **************************
window.addEvent('domready', function() {

	if ($('quizSendForm')) hijaxSendForm();

	/* If quiz form exists, add submit listener */
	if ($('quizForm')) {
		$('quizForm').addEvent('submit', function(e){
			validateQuiz();
			if (validateQuiz()) {
				$('quizError').setHTML('')
			} else {
				e = new Event(e).stop();
				$('quizError').setHTML('<p class="quizMessage">You haven\'t answered all the questions!</p>')
			}

		});
	}
	
	/* If quiz questions exists, add click listeners to them */
	if ($$('input.quizOption')) {
		$$('input.quizOption').each(function(option){
			option.addEvent('click', function(e){
				// remove error question-specific messages/styling when question is answered
				var info = $(option.parentNode);
				var inner = $(info.parentNode);
				var question = $(inner.parentNode);
				question.removeClass('quizQuestionError');
			});
		});
	}
});