var DOMUtilities = {
	targetBlank: function(locality){
		// XHTML 1.0 Strict work around for external links
		$(locality+' a[rel*="external"]').attr("target","_blank");
	},
	inputAutoClear: function(locality){
		$(locality+' input.clearField').focus(function(){
			if(this.defaultValue == this.value){
				this.value='';
				$(this).addClass('entered');
			}
		}).blur(function(){
			if(this.value == ''){
				this.value = this.defaultValue;
				$(this).removeClass('entered');
			}
		});
	},
	imgRollover: function(locality){
		// Image roll-over setup
		$(locality+' img.rollOver, '+locality+' input[type="image"].rollOver')
			.mouseenter(function(){
				if (this.src.indexOf("_i.") != -1) {
					this.src = this.src.replace("_i.", "_o.");
				}
			}).mouseleave(function(){
				if (this.src.indexOf("_o.") != -1) {
					this.src = this.src.replace("_o.", "_i.");
				}
				if(this.src.indexOf("_a.")) {
					this.src = this.src.replace("_a.","_i.");
				}
			}).filter("input").mousedown(function(){
				this.src = this.src.replace("_o.","_a.");
			}).mouseup(function(){
				this.src = this.src.replace("_a.","_i.");
			});
	},
	init: function(locality){
		if(locality == null) {
			locality = "body";
		}
		this.targetBlank(locality);
		this.inputAutoClear(locality);
		this.imgRollover(locality);
	}
}


var Quiz = {
	current: 1,
	fields: {
		1: 'quiz[experience]',
		2: 'quiz[instrument_to_play][]',
		3: 'quiz[your_instrument]',
		4: 'quiz[amplifier]',
		5: 'quiz[hand]',
		6: 'quiz[genre][]',
		7: ['username','email','password','country','zipcode','birthday_month','birthday_year','gender','tandc'],
		8: ['quiz[commitment_per_session]','quiz[commitment_per_week]'],
		9: 'quiz[goals][]'
	},
	speed: 500,
	country: "",
	
	errorMsg: function(field_name, valid){
		switch(field_name){
			case "email":
				if(!$('#input_email_response').hasClass('unaccepted')){
					if(valid === false){
						$('#input_email').addClass('error');
						$('#input_email_response').show().removeClass('unaccepted').addClass('warning').attr('title', 'Valid email address required');
					} else {
						$('#input_email').removeClass('error');
						$('#input_email_response').show().removeClass('unaccepted').removeClass('warning').addClass('accepted').attr('title', 'Email address is valid');
					}
				}
			break;
			
			case "password":
				if(valid === false){
					$('#input_password').addClass('error');
					$('#input_password_response').show().addClass('warning').attr('title', 'A password at least 6 characters long is required');
				} else {
					$('#input_password').removeClass('error');
					$('#input_password_response').show().removeClass('warning').addClass('accepted').attr('title', 'Password is valid');
				}
			break;
			
			case "zipcode":
				if(valid === false){
					$('#input_zipcode').addClass('error');
					$('#input_zipcode_response').show().addClass('warning').attr('title', 'A valid zipcode is required');
				} else {
					$('#input_zipcode').removeClass('error');
					$('#input_zipcode_response').show().removeClass('warning');
				}
			break;
			
			case "birthday_month":
			case "birthday_year":
				if(valid == false){
					$('#input_birthday_month, #input_birthday_year').addClass('error');
					$('#input_birthday_response').show().addClass('unaccepted').attr('title', 'If you are under 13 years old, you must have a guardian register on your behalf.')
				} else {
					$('#input_birthday_month, #input_birthday_year').removeClass('error');
					$('#input_birthday_response').show().removeClass('unaccepted').addClass('accepted').attr('title', 'You are old enough to participate!')
				}
			break;
		}
	},
	
	validateField: function(field_name){
		var fields_arr=this.form.serializeArray(), valid=true, found=false;
		this.country = $('#input_country').val().toLowerCase();
		
		for(var i=0; i<fields_arr.length; i++){
			var field = fields_arr[i];
			
			if(field.name == field_name){
				found = true;
				if ($.trim(field.value) != "") {
					switch (field_name) {
						case "email":
							if (!field.value.match(/^\w+([\+\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/)) {
								valid = false;
							}
						break;
							
						case "password":
							if (field.value.length < 6) {
								valid = false;
							}
						break;
							
						case "quiz[goals][]":
							if (field.value.toLowerCase() == "other") {
								if ($('#input_goals_other_reason').val().trim() == "") {
									valid = false;
									$('#input_goals_other_reason').addClass('error');
									$('#input_other_goal_response').show().addClass('warning').attr('title', 'Please let us know your goal.')
								} else {
									$('#input_goals_other_reason').removeClass('error');
									$('#input_other_goal_response').hide();
								}
							}
						break;
							
						case "zipcode":
							if (this.country == "united states") {
								if (!field.value.match(/\d{5}/)) {
									valid = false;
								}
							}
						break;
						
						case "birthday_month":
						case "birthday_year":
							var month = $('#input_birthday_month').val().trim();
							var year = $('#input_birthday_year').val().trim();
							
							if(month != "" && year != ""){
								var today = new Date();
								var birthday = new Date(year, month-1);
								var min_date = new Date(today.getFullYear()-13, month-1);
								
								if(birthday > min_date){
									valid = false;
								}
							} else {
								valid = false;
							}
						break;
					}
				} else {
					valid = false;
					if(field_name == "zipcode" && this.country != "united states"){
						valid = true;
					}
				}
			}
		}
		
		if(found == false && field_name != "zipcode"){
			valid = false;
		}
		
		this.errorMsg(field_name,valid);

		return valid;
	},
	
	validateStep: function(step){
		var valid = true;

		var required = this.fields[step];
		if(typeof(required) == "string"){
			required = [this.fields[step]];
		}

		for(var i=0; i<required.length; i++){
			if(this.validateField(required[i]) === false){
				valid = false;
			}
		}
		
		if(valid === false){
			$(this.steps[step-1]).find('.step_error').slideDown(this.speed);
			QuizSlideDeck.updateControlTo(step);
		} else {
			$(this.steps[step-1]).find('.step_error').slideUp(this.speed);
		}
		
		return valid;
	},
	
	submitStep: function(ind){
		var self = this;
		var fields_arr = this.form.serializeArray();
		var this_step = ind + 1;
		var next_step = this_step + 1;
		
		switch(this_step){
			case 1:
				if(this.validateStep(this_step) === true){
					for(var i=0; i<fields_arr.length; i++){
						if(fields_arr[i].name == 'quiz[experience]'){
							if($.inArray(fields_arr[i].value,["Yes, but I'm looking for a way to improve","Yes, but I'm pretty good already, just looking for new tips and tricks"]) != -1){
								next_step = 3;
							}
						}
					}
					QuizSlideDeck.progressTo(next_step);
				}
			break;
			
			case 2:
				if(this.validateStep(this_step) === true){
					for(var i=0; i<fields_arr.length; i++){
						if(fields_arr[i].name == 'quiz[instrument_to_play][]'){
							if(fields_arr[i].value == "Don't know, I could use some guidance"){
								next_step = 5;
							}
						}
					}
					QuizSlideDeck.progressTo(next_step);
				}
			break;
			
			case 3:
				if(this.validateStep(this_step) === true){
					for(var i=0; i<fields_arr.length; i++){
						if(fields_arr[i].name == 'quiz[your_instrument]'){
							var step_4_choices = $('dd.slide_4 li');
								step_4_choices.show();

							switch(fields_arr[i].value){
								case "Yes, an acoustic guitar in decent shape":
									$(step_4_choices[0]).hide();
								break;
								
								case "Yes, an electric guitar good enough for my needs":
								case "Yes, a bass guitar that I like":
								case "Yes, several for my different needs":
									$(step_4_choices[1]).hide();
									$(step_4_choices[2]).hide();
								break;
								
								case "No":
									next_step = 5;
								break;
							}
						}
					}
					QuizSlideDeck.progressTo(next_step);
				}
			break;
			
			case 4:
			case 5:
			case 6:
				if(this.validateStep(this_step) === true){
					QuizSlideDeck.progressTo(next_step);
				}
			break;
			
			case 7:
				var valid=false;
				$.ajax({
					url: "/users/unique_user",
					type: "post",
					data: "username=" + $('#input_username').val() + "&email=" + $('#input_email').val(),
					beforeSend: function(){
						$('#submit_indicator').show();
					},
					complete: function(data){
						var response = $.parseJSON(data.responseText);
						if(response.username === true && $('#input_username').val() != ""){
							$('#input_username').removeClass('error');
							$('#input_username_response').show().removeClass('warning').removeClass('unaccepted').addClass('accepted').attr('title','Screen Name is unique');
						} else {
							$('#input_username').addClass('error');
							$('#input_username_response').show().removeClass('warning').removeClass('accepted').addClass('unaccepted').attr('title','Screen Name already taken');
						}
						
						if(response.email === true && $('#input_email').val() != ""){
							$('#input_email').removeClass('error');
							$('#input_email_response').show().removeClass('warning').removeClass('unaccepted').addClass('accepted').attr('title','Email is unique');
						} else {
							$('#input_email').addClass('error');
							$('#input_email_response').show().removeClass('warning').removeClass('accepted').addClass('unaccepted').attr('title','Email is already taken');
						}
						
						valid = (response.username == true && response.email == true);
						
						if(self.validateStep(this_step) === true && valid === true){
							$.ajax({
								url: "/users/register",
								type: "post",
								data: self.form.serialize(),
								complete: function(data){
									QuizSlideDeck.progressTo(next_step);
									$('#login_header').html('<a href="/users/logout">Logout</a>');
								}
							});
						}
						$('#submit_indicator').hide();
					}
				});
			break;
			
			case 8:
			case 9:
				if(this.validateStep(this_step) === true){
					$.ajax({
						url: "/quizes/update",
						type: "post",
						data: self.form.serialize(),
						complete: function(data){
							if(this_step == 8) {
								QuizSlideDeck.progressTo(next_step);
							} else {
								document.location.href = "/quizes/results";
							}
						}
					});
				}
			break;
		}
	},
	
	trackData: function(){
		var sep = data_str = "";
		
		for(var i=0; i<QuizSlideDeck.session.length; i++){
			data_str+= sep + "session[" + i + "][slide]=" + QuizSlideDeck.session[i].slide
			sep = "&";
			data_str+= sep + "session[" + i + "][timestamp]=" + QuizSlideDeck.session[i].timestamp;
		}
		
		$.ajax({
			url: "/quizes/stats",
			type: "post",
			data: data_str
		})
	},

	initialize: function(){
		var self = this;
		
		this.form = $('#quiz_slidedeck_form');
		this.steps = this.form.find('dd.slide');
		
		this.form.submit(function(event){
			event.preventDefault();
		});
		
		this.form.find('a.btn_next, #btn_submit_quiz').each(function(ind,e){
			$(e).click(function(event){
				event.preventDefault();
				self.submitStep(ind);
			});
		});
		
		this.form.find('.slide_2 ul li input').click(function(event){
			if(this.value == "Don't know, I could use some guidance"){
				if(this.checked == true){
					self.form.find('.slide_2 ul li input').not(this).removeAttr('checked');
				}
			} else {
				self.form.find('.slide_2 ul li.last input').removeAttr('checked');
			}
		});
		
		$(window).unload(function(event){
			self.trackData();
		});
	}
};


var FormValidators = [];
$(document).ready(function(){
	DOMUtilities.init();
	
	$('form.validate').each(function(ind,e){
		FormValidators.push(new FormValidator(e));
	});
	
	$('input.ui-datepicker').datepicker();
	
	$('.fancybox_login').each(function(ind,e){
		href = e.href.replace(document.location.protocol + '//' + document.location.host,"");
		$(e).fancybox({
			href: '/users/login?return=' + href,
			width: 780,
			height: 306,
			padding: 13,
			autoDimensions: false,
			autoScale: false,
			centerOnScroll: true,
			titleShow: false,
			showNavArrows: false,
			overlayColor: '#000',
			overlayOpacity: 0.8,
			onStart: function(){
				$('body object, body embed').css('visibility','hidden');
			},
			onComplete: function(){
				Cufon.replace(".modal .cufon", { autoDetect: true, hover: true })
				DOMUtilities.init('.modal');
			},
			onCleanup: function(){
				$('body object, body embed').css('visibility','visible');
			}
		});
	});
	
	$('a.fancybox').fancybox({
		padding: 20,
		autoDimensions: true,
		autoScale: true,
		centerOnScroll: true,
		showNavArrows: false,
		overlayColor: '#000',
		overlayOpacity: 0.8
	});
	
	$('a.scrollTo').click(function(event){
		event.preventDefault();
		
		var destination = this.href.split("#")[1];
		
		$.scrollTo('#' + destination, 1000, {
			easing: 'easeInOutCubic',
			offset: {
				top: -30
			}
		});
	});
	
	if($('#input_country').length){
		$('#input_country').change(function(event){
			if(this.value.toLowerCase() == "united states"){
				$('#input_zipcode').removeAttr('disabled','disabled').removeClass('disabled');
			} else {
				$('#input_zipcode').attr('disabled','disabled').addClass('disabled').val("");
			}
		});
		if($('#input_country').val().toLowerCase() != "united states"){
			$('#input_zipcode').attr('disabled','disabled').addClass('disabled');
		}
	}
	
	if(typeof(QuizSlideDeck) != "undefined"){
		Quiz.initialize();
	}
});
