/* ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
	Earn Money Contests
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: */

function contestInit() {
	// Checks to see if an element with the class 'conteststeps' exists
	if($('.conteststeps').length > 0){
	
		// Sets value of hidden input with the class 'register-redirect' to the current URL so the user will
		// be returned to the current contest after registering
		$('.register-redirect').val(window.location.href);
		
		// Binds functionality to each contest step
		// * this - the current contest step <li> (list item) DOM object
		$('.conteststeps ul.steps li').each(function(){
			
			// Make the step <li> DOM object more easily accessible to child functions that replace 'this'
			var step = this;
			
			// Hide all text fields with the class initHide and make sure they are hidden initially
			// This is used for "Other" text fields that should only be shown if "Other" is selected
			$(step).find('.initHide').hide();
			
			initStars();
			
			// Binds functionality to current step's 'next' button if it exists
			// * this - the current contest step's next button DOM object
			$(step).find('.next').click(function(){
				
				// Checks form for missing values. Current step <li> DOM object must be passed to it
				var formValid = contestStepValidation(step);
				
				// If form is invalid, display alertBox message
				if(!formValid) { alertBox('Incomplete','Please complete this step before continuing.'); }
				
				// If form is valid, do this instead
				else {
				
					// Hide step's question / response container
					$(step).children('.step').slideUp(250);
					
					// Add 'complete' class to step <li>
					$(step).addClass('complete');
					
					// Serialize step's form data
					var formData = $(step).find('.step-form').serialize();
					
					// Check if we should jump to a different question based on the current answer
					var nextStepJump = contestNextQuestionRedirect(step);
                    if ("" != nextStepJump) { 
                        // Get the next step to jump to
                    	nextStepJump = parseInt(nextStepJump);
                    	
                    	// Get the current step we're on
						var currentStep = parseInt($(step).find('input:hidden[name=sort_order]').val());
						if(nextStepJump > currentStep) {
							
							// Find out how many questions to jump ahead
							var jumps = nextStepJump - currentStep;
                            var i = 0;
							var nextStep = $(step).next();
							if (!$(nextStep).hasClass('register-step')) {
								for (i = 0; i < jumps; i++)
								{
									// Add completed and skipped to each of the questions we jump over
									$(nextStep).addClass('complete');
									$(nextStep).addClass('skipped');
									nextStep = $(nextStep).next();
									if ($(nextStep).hasClass('register-step')) {
										break;
									}
								}
							}
							
							// Display the step we jumped to
							if ($(nextStep).hasClass('register-step')) {
								$('.register-step').slideDown(250);
							} else {
								$(nextStep).children('.step').slideDown(250);
							}
						}
					
					} else {
						// Display next step's question / response container
						$(step).next().children('.step').slideDown(250);
					}
					
					// Check for redirect in current step
					var redirectURL = contestStepRedirect(step);
					
					// If redirect URL is not blank, open the URL in a new window
					if (redirectURL!="") { window.open(redirectURL); }
					
					// Submit step's form data via AJAX
					$.ajax({
						type: "POST",
						url: "/includes/earn-money-save-answer.php",
						data: formData,
						dataType: "html",
						success: function(data) {
							// Do something if form data submission is successful
						}
					});
				}
			});
			
			// Binds functionality to current step's 'register' button if it exists
			// * this - the current contest step's next button DOM object
			$(this).find('.register').click(function(){
				
				// Checks form for missing values. Current step <li> DOM object must be passed to it
				var formValid = contestStepValidation(step);
				
				// If form is invalid, display alertBox message
				if(!formValid) { alertBox('Incomplete','Please complete this step before continuing.'); }
				
				else {
					
					// Hide step's question / response container
					$(step).children('.step').slideUp(250);
					
					// Add 'complete' class to step <li>
					$(step).addClass('complete');
					
					// Display register step
					$('.register-step').slideDown(250);
					
					// Serialize step's form data
					var formData = $(step).find('.step-form').serialize();
					
					// Append engagement's entry ID to form data
					// I didn't add this, and I'm not actually sure if we need it anymore - I'm told
					// engagement IDs are handled using sessions now
					formData+="&engagement_entry_id="+$('#engagement_entry_id').val();
					
					// Submit step's form data via AJAX
					$.ajax({
						type: "POST",
						url: "/includes/earn-money-save-answer.php",
						data: formData,
						dataType: "html",
						success: function(data) {
							// Do something if form data submission is successful
							
							// I didn't add these, and I'm not actually sure if we need them anymore - I'm told
							// engagement IDs are handled using sessions now
							$('#engagement_entry_id').val(data);
							$('.register-engagement_entry_id').val(data);
						}
					});
				}
			});
			
			// Binds functionality to current step's 'previous' button if it exists
			// * this - the current contest step's next button DOM object
			$(this).find('.previous').click(function(){
			
				// Hide step's question / response container
				$(step).children('.step').slideUp(250);
				
				// Remove step's class of 'complete'
				$(step).removeClass('complete');
				
				// Show previous step's question / response container
				var previousStep = $(step).prev();
				while ($(previousStep).hasClass('skipped')) {
                    $(previousStep).removeClass('complete');
                    $(previousStep).removeClass('skipped');
					previousStep = $(previousStep).prev();
				}
				$(previousStep).children('.step').slideDown(250);
			});
			
		});
	}
}



/* ================================================
	contestStepValidation(step)
	Checks provided step for invalid fields and returns true if all are valid
	* step - Step <li> DOM object
================================================ */

function contestStepValidation(step) {

	// Assume all fields are valid
	var formValid = true;
	
	
	if($(step).hasClass("multi-answer-star-ratings-w-other")) {
		if($(step).find('input:hidden.star-input[value!=0]').length > 0) {
			return true;
		}
		return false;
	}
	
	
	// Check if current step has radio buttons
	if($(step).find(':radio').length > 0){
	
		// If no radio buttons are selected, form is not valid
		if($(step).find(':checked').length < 1) formValid = false;
	}
	else if($(step).find('textarea').length > 0){
	
		// Check if current step has a textarea
		
		// CKEditor WYSIWYGs must have their parent textareas updated first
		for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement();
		
		// If textarea is blank, form is not valid
		if($(step).find('textarea').val() == '') formValid = false;
	}
	else if($(step).find(':text').length > 0){
	
		// Check if current step has a text input
		
		// If text input is blank, form is not valid
		if($(step).find(':text').val() == '') formValid = false;
	}
	
	// Return validation status
	return formValid;
}



/* ================================================
	contestStepRedirect(step)
	Checks provided step for conditional redirect
	* step - Step <li> DOM object
================================================ */

function contestStepRedirect(step) {
	var redirectURL = "";
					
	//Check for existence of redirect data in step
	if ($(step).find('.step-redirect-url').length > 0) {
		
		// Redirect data is a JSON encoded array of answers to the current question paired with a redirect URL
		var redirectData = jQuery.parseJSON($(step).find('.step-redirect-url').text());
		
		// Check current step has radio buttons
		// Note: This is currently the only type of redirect we have
		if($(step).find(':radio').length > 0){
		
			// Grab step's selected radio button value
			var selectedValue = $(step).find('input:radio[name=response]:checked').val();
			
			// Compare selected radio button's value against redirect data. If there is a match, define redirectURL as answer's paired URL
			for (var i = 0; i < redirectData.length; i++) {
				if (redirectData[i]['value']==selectedValue) {
					redirectURL = redirectData[i]['url'];
				}
			}
		}
	}
	
	return redirectURL;
}

function contestNextQuestionRedirect(step) {
	var redirectURL = "";
					
	//Check for existence of redirect data in step
	if ($(step).find('.next-question-url').length > 0) {
		
		// Redirect data is a JSON encoded array of answers to the current question paired with a redirect URL
		var redirectData = jQuery.parseJSON($(step).find('.next-question-url').text());
		
		// Check current step has radio buttons
		// Note: This is currently the only type of redirect we have
		if($(step).find(':radio').length > 0){
		
			// Grab step's selected radio button value
			var selectedValue = $(step).find('input:radio[name=response]:checked').val();
			
			// Compare selected radio button's value against redirect data. If there is a match, define redirectURL as answer's paired URL
			for (var i = 0; i < redirectData.length; i++) {
				if (redirectData[i]['value']==selectedValue) {
					redirectURL = redirectData[i]['url'];
				}
			}
		}
	}
	
	return redirectURL;
}

function showOther(otherNum) {
	$('#response_other' + otherNum).show();
}

function hideOther(otherNum) {
	$('#response_other' + otherNum).val("");
	$('#response_other' + otherNum).hide();
}

function initStars() {
	$('.conteststeps ul.steps fieldset.star-rating').each(function(){
		var rating = $(this).find('div.rating');
		var hiddenInputId = 'input_' + $(rating).attr('id');
		var startVal = $(this).find('input.star-input').attr('value');
		
		$(rating).rating(hiddenInputId, {maxvalue:5, curvalue:startVal});
	});
}

