// Set up the theme for the captcha
// its a decent amount of work to build our own theme
// but something to consider at some point

var RecaptchaOptions = {
   theme : 'white'
};

// On DOM ready
$(function (){

	// set up the options for the screen wizard
	var wizOpts = {
		size: 365
	};
	
	// initialize the screen wizard using signup_frames
	var signUpWizard = $("#signup_frames").screenWizard(wizOpts);

	// set up the gender interface. Probably want to look into doing skinnable radio buttons at some point
	$("#gender_buttons li a").click(function(){
		if ($(this).hasClass("maleGender")) {
			$(this).removeClass("maleGender");
			$(this).addClass("maleGenderOn");
			$(this).closest("#gender_buttons").find(".femaleGenderOn").removeClass("femaleGenderOn").addClass("femaleGender");
			$(this).closest("#gender_buttons").find("input").val("male");
		}
		if ($(this).hasClass("femaleGender")) {
			$(this).removeClass("femaleGender");
			$(this).addClass("femaleGenderOn");
			$(this).closest("#gender_buttons").find(".maleGenderOn").removeClass("maleGenderOn").addClass("maleGender");
			$(this).closest("#gender_buttons").find("input").val("female");
		}
	});

	// advance the wizards on buttons that require no further logic
	$("#signupLink, #WR_Decline").click(function(){
		signUpWizard.screenWizard("advance");
		return false;
	});
	
	// Generic cancel button for moving back through the wizard.
	$(".signupCancel").click(function(){
		signUpWizard.screenWizard("back");
		return false;
	});
	
	// initialize the forgot password dialog
	$("#forgot_password_content").dialog({
		title: "Forgot Password", 
		dialogClass: "signup", 
		modal: true, 		autoOpen: false, width: 500, resizable: false, 
		buttons: { 
			'Submit': function() { $("#forgot_password_form").submit(); } 
			}
		});
	// initialize the email password reset sent dialog
	$("#password_email_sent").dialog({
		title: "Forgot Password", 
		dialogClass: "signup", 
		modal: true, autoOpen: false, width: 500, resizable: false, 
		buttons: { 
			'Ok / Close': function() { $(this).dialog("close"); } 
			}
		});
	// add some validation to the forgot password form
	$("#forgot_password_form").validate({
		submitHandler: function(form){
			// ajax submission
			$(form).ajaxSubmit({
				success: function(data) { 
					// standard check for data
					// throws an error modal window if there's a problem
					if($.FLCheckAjaxError(data)) {
						if(data.error_code == 2) {
							// could do some more here on error
							null;
						}
					} else {
						// success 
						// write in email addy on the email sent confirmation dialog
						$("#password_email_sent").find("h3 span").text($(form).find("input.email").val());
						// close old pop up
						$("#forgot_password_content").dialog("close");
						// open new pop up
						$("#password_email_sent").dialog('open');
					}
			    },
				// ajax connection error
				// close dialog and do standard ajax connection error
				error : function () {
					$("#forgot_password_content").dialog("close");
					$.FLAjaxConnectionError();
				}
			});
		}
	});
	
	// on link click, open the dialog that's already been initialized
	$("#forgot_password_link").click(function(){
		$("#forgot_password_content").dialog('open');
	});
	
	$("#verify_email_sent_signup").dialog({
        title: "Confirmation Email Sent", 
        dialogClass: "signup", 
        modal: true, autoOpen: false, width: 500, resizable: false, 
        buttons: { 
            'Continue': function() {
                $(this).dialog("close");
                window.location.href = Server.site_url + '/getting_started/one';
	        }
        }
	});
	
	
	// initialize the dialog for "why do we need this information"
	// "You can hide this information from your relatives when you enter the site."
	var whyInfo = $("<p>We collect this information to keep the integrity of the site and to protect children. Also, the month and day of your birthdate will be visible to your relatives.</p>").
		dialog({
				title: "Personal Information", autoOpen: false, resizable: false, width: 500,
		 		buttons: { 'Ok': function() { $(this).dialog("close"); } }
		});
	// open the dialog on click
	$(".whyInfo").click(function(){
		whyInfo.dialog("open");
		return false;
	});
	
	// on login submit, validate that email and password were supplied
	$("#fl_login").validate({
		submitHandler: function(form){
			// show the loading icon and submit
			var loading = $(form).find(".frameButtons").FLloading();
			form.submit();
		}
	});
	
	// on captcha form submit
	// validate the field isn't empty
	/*
	$("#captcha_form").validate({
		submitHandler: function(form){
			// lose the captchaRequired class and add captchaEntered
			$("#captcha_frame").removeClass("captchaRequired").addClass("captchaEntered");
			// show the loading icon
			var loading = $(form).find(".frameButtons").FLloading();
			// grab the inputs from the captcha form
			var inputs = $("#recaptcha_challenge_field, #recaptcha_response_field", form).clone();
			// create a container for them so we can grab them easily later
			var p = $("<p id='recaptcha_inputs'/>");
			// put the inputs in the container
			p.append(inputs);
			// copy inputs to the sign up form for submission
			$("#fl_register").append(p).submit();
		}
	});
    */

    jQuery.validator.addMethod("namevalidator", function(value, element) { 
            return this.optional(element) || /^[-' a-zA-Z]+$/i.test(value); 

            }, "Valid Names Only");
	
	// validation and submit logic for the sign up form
	$("#fl_register").validate({
		// add these requirements to the password field
		rules: {
			password: {
				minlength: 6,
				maxlength: 14,
				thisManyNumbers: 1,
				thisManyLetters: 1
			},
            name : {
                required: true,
                namevalidator: true
            },
            first_name : {
                required: true,
                namevalidator: true
            },
            last_name : {
                required: true,
                namevalidator: true
            }
		},
		// on valid submit
		submitHandler: function(form){
		    // Only allow the form to be submitted once.
		    if ($(form).attr('disabled') == 'disabled') {
		        return;
		    }
		    
			// show the loading icon, disable buttons
			$(form).find(".frameButtons").FLloading();
			$(form).attr('disabled', 'disabled'); 
			
			// ajax submit
			$(form).ajaxSubmit({
				success: function(data) { 		
				    // if there was an error, use standard error dialog
					if($.FLCheckAjaxError(data)) {
					    // if specific error, reload the recaptcha to try again
					    if(data.error_code == 2) {
					    	Recaptcha.reload();
					    }
					} 
					else {
						// if they weren't verified via a third party, hide the dialog close buttons and show the email verification dialog.
						if (data.verified !== true) {
							// Sets the email to to the dialog box
							$('.email_from_form').html($("input[name=email]").val());
                            
							// Sets the email value for resend
							$("input[name=email_resend_id]").val($("input[name=email]").val());
							$("#verify_email_sent_signup").dialog('open');
						}
						else {
						// otherwise creation and verification were successful
						// for now go to the add_relatives screen
						    window.location.href = Server.site_url + '/getting_started/one';
						}
					}
                    $(form).attr('disabled', ''); 
                    $(form).find(".frameButtons").FLloading('reset');

			    },
				// ajax connection error
				error : function () {
					$.FLAjaxConnectionError();
		            // Reenable the form and hide the we're related box
					$(form).attr('disabled', ''); 
		            $(form).find(".frameButtons").FLloading('reset');
				}
			    
			});
            return;
		}
	});
	
  	// since we don't control the markup for the captcha, add the rule dynamically
    // Only add rule if element exists
    if ($("#recaptcha_response_field").length === 1) {
        $("#recaptcha_response_field").rules("add", {
                required: true,
                messages: {
                    required: "Captcha required"
                }
        });
    }

	$('#signup_info_fl_submit').click(function() {
	    if ($("#fl_register").valid()) {
        	$('#fl_register').submit();
	    }
		return false;
	});

    // Signup button submit 
    $('#signupFormSubmit').click(function() {
        if ($("#fl_register").valid()) {
            $('#WR_frame').show();
            $('#fl_register').hide();
        }
    	return false;
    });

    $('#WR_Decline').click(function() {
        $('#WR_frame').hide();
        $('#fl_register').show();
        $('#fl_register').submit();
    });
    
    // Try to log the user in automatically
    fb_auto_login();
    
    $('#fbconnect_login_button').click(function() {
    	
    	// Cancel the auto login so that we can submit the Familylink registration form first.
    	fb_auto_login_cancel();
    	
        FB.Connect.requireSession(
        // This function connects the Facebook user with a FamilyLink account when they accept FB.
        function() {
            var api = FB.Facebook.apiClient;
            api.users_getInfo(api.get_session().uid, 'name', function(result) {
                var logged_in_as = result[0].name;
                var signing_up_as = $(".signup input[name='name']").val();
    
                if (signing_up_as.split(' ')[0].toLowerCase() == logged_in_as.split(' ')[0].toLowerCase()) {
                    // if first names match, submit form
                    if ($("#fl_register").valid()) {
                    	$('#WR_frame').hide();
                        $('#fl_register').show();
                        $('#fl_register #attach_network').val('2002.2');     
                        $('#fl_register').submit();
                    }
                }
                else {
                    // if not, warn the user
                    $('#signing_up_as').html(signing_up_as);
                    $('#logged_in_as').html(logged_in_as);
                    $('#warnNamesDiffer').dialog("open");
                }
            });
        },
        
        // The user clicked cancal on the connect dialog.  
        function() { 
            
        },
        true);
    });
    
	$('#fbconnect_button').click(function() {
	    FB.Connect.requireSession(function() {
	        window.location = Server.site_url+'/login/2002.2/'+Server.next_page;
	    });
	});

	
	/* 
	 * signup_info, "signup and find relatives" btn that brings the 
	 * focus back to the top portion of the page
	 */
	$('.backtotop').click(function(){
		$('html, body').animate({scrollTop:0}, 'slow');
		return false;
	});
    
    
    $("#warnNamesDiffer").dialog({
        title: "Are you sure?", 
        dialogClass: "signup", 
        modal: true, autoOpen: false, width: 500, resizable: false, 
        buttons: { 
            'No, Cancel': function() {
                $(this).dialog("close");
                $('#WR_frame').hide();
                $('#fl_register').show();
            },
            'Yes, Sign Up Anyway': function() { 
                $(this).dialog("close");
                if ($("#fl_register").valid()) {
                    $('#WR_frame').hide();
                    $('#fl_register').show();
                    $('#fl_register #attach_network').val('2002.2');     
                    $('#fl_register').submit();
                }
        }
        }
    });

});
