// NEEDS jquery-jsonp
// http://code.google.com/p/jquery-jsonp/source/browse/trunk/core/jquery.jsonp.js

//////////////////////////////////////////////////////////////////////
////////// Generic helpers
function regenerateSelects() {
	// Destroy and re-generate the selects.
	jQuery.each(selects, function(index, item) {
		selects[index].replaced = false;
		jQuery(selects[index]).removeClass('outtaHere');

		jQuery('#sarea'+index).remove();
		jQuery('#optionsDiv'+index).remove();
	});
	replaceSelects();
}

function htmlescape(val) {
	if (jQuery('#escaper').length == 0) {
		jQuery('body').append(
			jQuery('<div>', {id: 'escaper'}).hide()
		);
	}

	return jQuery('#escaper').text(val).html();
}

//////////////////////////////////////////////////////////////////////
////////// Routines specific to /domains/
function domreg_updateTldList(data) {
	jQuery('#domreg_tld').empty();
	jQuery.each(data['result'], function (index, tld_record) {
		var tld = tld_record['tld'];
		jQuery('#domreg_tld').append(
			jQuery('<option>', { value: tld }).text('.' + tld)
		)
	});
	regenerateSelects();
}

function domreg_showCheckError(error, reason, domain) {
	var head, msg;
	switch(error) {
	// First, a couple JS-passed errors
	case 'still_loading':
		head = 'Please wait...';
		msg  = 'Please hang on for just a moment, we are currently loading the TLD list for you.';
		break;
	case 'missing_domain':
		head = 'Missing Domain';
		msg  = 'Please enter a domain name that you would like to have.';
		break;

	// Now, for errors returned via JSONP
	case 'invalid_domain':
		head = 'Invalid Domain';
		msg  = reason;
		break;
	case 'domain_taken':
		head = 'That name is already taken!';
		msg  = domain + ' is already registered! Please try something else!';
		break;

	default:
		head = 'Yikes!';
		msg  = 'We were unable to check the status of this domain. Please try again later.';
		break;
	}

	jQuery('#domreg_error_head').text(head);
	jQuery('#domreg_error_msg').text(msg);
	jQuery('#domreg_errorbox').show();
}

function domreg_showCheckSuccess(domain, price) {
	var domain_escaped = htmlescape(domain);

	jQuery('#domreg_success_head').html('<span>Congratulations!</span>' + domain_escaped + ' is available for registration!');
	jQuery('#domreg_success_price').html('You can register this domain right now for just $' + price.toFixed(2) + '!');

	jQuery('#domreg_success_btn')
		.attr('href', 'https://signup.dreamhost.com/?fqdn=' + escape(domain))
		.html('<span>Register ' + domain_escaped + '</span>');

	jQuery('#domreg_successbox').show();
}


//////////////////////////////////////////////////////////////////////
////////// Routines specific to /affiliates/
function affiliate_showSignupErrors(error_data) {
	// Now go through all error keys and show the errors.
	for (err_key in error_data) {
		var method='text', field, msg;
		switch (err_key) {
		// First, a couple JS-passed errors
		case 'missing_name':
			field = 'affiliate_name_err';
			msg   = 'Please enter both your first and last name.';
			break;
		case 'missing_email':
			field = 'affiliate_email_err';
			msg   = 'Please enter your email.';
			break;
		case 'missing_password':
			field = 'affiliate_password_err';
			msg   = 'Please enter a password.';
			break;
		case 'missing_agreed':
			field = 'affiliate_agreed_err';
			msg   = 'Please read the Terms of Service.'
			break;

		// Now, for errors returned via JSONP
		case 'invalid_email':
			field = 'affiliate_email_err';
			msg   = error_data[err_key];
			break;
		case 'invalid_password':
			field = 'affiliate_password_err'
			msg   = error_data[err_key];
			break;
		case 'already_have_account':
			method = 'html';
			field  = 'affiliate_name_err';
			msg    = 'It appears you already have an account with us. Go login to the <a href="https://panel.dreamhost.com/?tree=home.rew">management area</a>!';
			break;
		case 'wrong_password':
			method = 'html';
			field  = 'affiliate_password_err';
			msg    = 'A login already exists for this email. Please enter the correct password for it. If you do not remember the password, use our <a href="https://panel.dreamhost.com/login/forgot.cgi">forgot password</a> system.';
			break;

		// For other errors, we'll use the very top error field.
		default:
			field = 'affiliate_name_err';
			msg   = 'Yikes! We were unable to process your request at this time. Please try again later.';
			break;
		}

		if (method == 'html') {
			jQuery('#'+field).html(msg).show();
		} else {
			jQuery('#'+field).text(msg).show();
		}
	}
}

function affiliate_showSignupSuccess(data) {
	var msg = '<h2>Account created!</h2>';
	msg += '<p>Your referral link is: <b>http://www.dreamhost.com/r.cgi?' + data['account_id'] + '</b></p>';
	msg += '<p>You can now login to the <a href="https://panel.dreamhost.com/?tree=home.rew">management panel</a>!</p>';
	msg += '<p>Or, go read our <a href="http://www.dreamhost.com/affiliates/">linking directions</a>!</p>';
	jQuery('#affiliate_signup_success').html(msg).show();
	jQuery('#affiliate_signup_form').hide(); // They won't need it anymore, anyways!
}

//////////////////////////////////////////////////////////////////////
////////// Routines specific to /contact/
function contact_showFormErrors(errors) {
	var msg = "";
	for (key in errors) {
		if(key == "general") continue;
		jQuery("#contact_" + key).css("background", "#fdb");
		msg += errors[key] + "\n";
	}
	if (!msg) {
		msg = "Whoops, something went wrong sending your message. Please try again...";
	}
	if ('general' in errors) {
		alert(errors.general);
	} else {
		alert(msg);
	}
}

////////////////////////////////////////////////////////////////////////////////
////////// The main worker, yay?
jQuery(document).ready(function () {

	// We'll probably need to change this to cgi.dreamhost.com in the future, but
	// since it does not have SSL yet, we'll point it to dreamhost.com
	var DH_API_ROOT = 'https://www.dreamhost.com/ajax.cgi?callback=?';

	// Goop for the domain form.
	if (jQuery('#domreg_form').length) {

		// Run the JSONP to get the TLD list.
		jQuery.jsonp({
			url: DH_API_ROOT,
			data: { cmd: 'domreg-tld_list' },
			success: function(data, textStatus) {
				domreg_updateTldList(data)
			}
		});

		// The domreg_submit pseudo-button should submit the form.
		jQuery('#domreg_submit').click(function(eventObject) {
			jQuery('#domreg_form').submit();
		})

		// On form submit, we need to dispatch a JSON+P request to check domain status.
		jQuery('#domreg_form').submit(function(eventObject) {
			var domain = jQuery('#domreg_domain').val().replace(/\s/g, '');
			var tld = jQuery('#domreg_tld').val();
			var sugg = jQuery('#domreg_suggestions').val();

			if (tld == 'LOADING') {
				domreg_showCheckError('still_loading');
				return false;
			}
			if (domain == '' || domain == 'yourdomain') {
				domreg_showCheckError('missing_domain');
				return false;
			}

			jQuery('#domreg_successbox, #domreg_errorbox').hide();
			jQuery('#domreg_submit').attr('disabled', 'disabled').html('<span>Please wait...</span>');

			jQuery.jsonp({
				url: DH_API_ROOT,
				data: {
					cmd: 'domreg-check_available',
					domain: domain,
					tld: tld,
					suggestions: sugg
				},
				success: function(data, textStatus) {
					if ('error' in data) {
						domreg_showCheckError(data['error'], data['reason']);
					} else if (data['status'] == 'available') {
						domreg_showCheckSuccess(data['domain'], data['price']);
					} else { // no errors, and domain is not available
						domreg_showCheckError('domain_taken', null, data['domain']);
					}
					jQuery('#domreg_submit').removeAttr('disabled').html('<span>Check Domain</span>');
				},
				error: function(xOptions, textStatus) {
					domreg_showCheckError('client_error');
					jQuery('#domreg_submit').removeAttr('disabled').html('<span>Check Domain</span>');
				}
			});

			return false;
		}); // end: jQuery('#domreg_form').submit(

	} // end: if jQuery('#domreg_form').length

	if (jQuery('#affiliate_form').length) {

		// The affiliate_submit pseudo-button should submit the form.
		jQuery('#affiliate_submit').click(function(eventObject) {
			jQuery('#affiliate_form').submit();
		})

		// On form submit, we need to dispatch a JSON+P request
		jQuery('#affiliate_form').submit(function(eventObject) {
			var fname  = jQuery.trim( jQuery('#affiliate_fname').val() );
			var lname  = jQuery.trim( jQuery('#affiliate_lname').val() );
			var email  = jQuery.trim( jQuery('#affiliate_email').val() );
			var passwd = jQuery.trim( jQuery('#affiliate_password').val() );
			var agreed = jQuery('#affiliate_agreed:checked').length;

			// Hide all signup errors first
			jQuery('div[id^=affiliate_]').filter(function() {
					return this.id.match(/^affiliate_.+_err/)
				}).hide();

			// Super primitive check inputs. We'll leave the meatier checks to the CGI,
			// since they have to be run anyways!
			var errors = {};
			if (!fname.length || !lname.length) {
				errors['missing_name'] = 1;
			}
			if (!email.length || !email.match(/^.+@.+\..+$/)) {
				errors['missing_email'] = 1;
			}
			if (!passwd.length) {
				errors['missing_password'] = 1;
			}
			if (!agreed) {
				errors['missing_agreed'] = 1;
			}
			if (!jQuery.isEmptyObject(errors)) {
				affiliate_showSignupErrors(errors);
				return false;
			}

			// Okay, so there's at least _something_ in each field, lets do this.
			jQuery('#affiliate_submit').attr('disabled', 'disabled').html('<span>Please wait...</span>');

			jQuery.jsonp({
				url: DH_API_ROOT,
				data: {
					cmd: 'affiliate-signup',
					fname: fname,
					lname: lname,
					email: email,
					password: passwd,
					agreed: agreed,
				},
				success: function(data, textStatus) {
					if ('errors' in data) {
						// This one returns errors (plural), rather than just error.
						affiliate_showSignupErrors(data['errors']);

					} else if ('error' in data) {
						// If it does return just error (singular), then use that as a dict
						var e = {};
						e[data['error']] = data['reason'];
						affiliate_showSignupErrors(e);

					} else {
						// No errors, so hip-hip-horray!
						affiliate_showSignupSuccess(data);

					}
					jQuery('#affiliate_submit').removeAttr('disabled').html('<span>Sign Up Now</span>');
				},
				error: function(xOptions, textStatus) {
					affiliate_showSignupErrors('client_error');
					jQuery('#affiliate_submit').removeAttr('disabled').html('<span>Sign Up Now</span>');
				}
			});

			return false;

		}); // end: jQuery('#affiliate_form').submit(

	} // end: if jQuery('#affiliate_form').length

	if (jQuery('#contact_form').length) {

		jQuery("#contact_regarding").change(function() {
			if (this.value.match(/^billing/)) {
				jQuery('.contact-form #credit-info').slideDown();
			} else {
				jQuery('.contact-form #credit-info').slideUp();
			}
		});

		// On form submit, we need to dispatch a JSON+P
		jQuery('#contact_form').submit(function() {
			jQuery("#contact_form input[type=text], #contact_form textarea").css("background", "#fff");

			var name  = jQuery.trim( jQuery('#contact_name').val() );
			var email  = jQuery.trim( jQuery('#contact_email').val() );
			var subject = jQuery.trim( jQuery('#contact_subject').val() );
			var regarding = jQuery.trim( jQuery('#contact_regarding').val() );
			var message = jQuery.trim( jQuery('#contact_message').val() );
			var credit_first_four = jQuery.trim( jQuery('#contact_credit_first_four').val() );
			var credit_last_four = jQuery.trim( jQuery('#contact_credit_last_four').val() );
			var recaptcha_challenge = jQuery.trim(jQuery('#recaptcha_challenge_field').val());
			var recaptcha_response = jQuery.trim(jQuery('#recaptcha_response_field').val());

			var errors = { };

			if (!name.length) {
				errors.name = "Please enter a name.";
			}
             
			if (!email.length) {
				errors.email = "Please enter an email address.";
			} else if(!email.match(/^.+@.+\..+$/)) {
				errors.email = "Please enter a valid email address.";
			}

			if (!subject.length) {
				errors.subject = "Please enter a subject.";
			}
			if (!message.length) {
				errors.message = "Please enter a message.";
			}
			if (!recaptcha_response.length) {
				errors.recaptcha_response = "Please complete the CAPTCHA at the bottom of the form.";
			}

			if (!jQuery.isEmptyObject(errors)) {
				contact_showFormErrors(errors);
				return false;
			}

			// Okay, so there's at least _something_ in each field, lets do this.
			// XXX UGH! The "Submit" button is sprited so we can't change its text.
			jQuery("#contact_submitting").text("Please wait...");

			jQuery.jsonp({
				url: DH_API_ROOT,
				data: {
					name: name,
					email: email,
					regarding: regarding,
					subject: subject,
					message: message,
					ccard_first_four: credit_first_four,
					ccard_last_four: credit_last_four,
					challenge: recaptcha_challenge,
					response: recaptcha_response,
					cmd: 'contact-send'
				},
				success: function(data, textStatus) {
					jQuery("#contact_submitting").text("");
					if ('error' in data) {
						contact_showFormErrors({ general: "ERROR: " + data.error });
					} else if ('errors' in data) {
						contact_showFormErrors(data.errors);
						jQuery("#contact_submitting").text("");
					} else {
						alert("Message sent! We'll get in touch with you shortly.");
						window.location.reload();
						return;
					}
					Recaptcha.reload();
				},
				error: function(xOptions, textStatus) {
					jQuery("#contact_submitting").text("");
					contact_showFormErrors({ general: "An error occurred submitting your support request." });
				}
			});

			return false;
		}); // end: jQuery('#contact_form').submit(

	} // end: if jQuery('#contact_form').length

	if (jQuery('#sales_chat_button').length) {

		jQuery.jsonp({
			url: DH_API_ROOT,
			data: {
				cmd: 'contact-get_chat_button',
			},
			success: function(data, textStatus) {
				if ('button_html' in data) {
					jQuery('#sales_chat_button').html(data['button_html']);
				}
			}
		});

	} // end: if jQuery('#sales_chat_button').length

});



