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=?';

	// Add to the String prototype a bit, to make our lives a tad easier.
	String.prototype.startsWith = function (str) {
		return this.slice(0, str.length) == str;
	};

	function ccardIsAmex() {
		var v = jQuery.trim($('#cc_first').val());
		return (v.startsWith('34') || v.startsWith('37'));
	}

	function dhfee_showFormErrors(errors) {
		for (key in errors) {
			var field, field_msg;

			switch (key) {
			case 'captcha_response':
				field = 'recaptcha_err';
				field_msg = 'The text does not match what was in the image. Please try again.';
				break;

			default:
				field = key + '_err';
				field_msg = errors[key];

				var obj = $('#' + field);
				if (!obj.length) {
					field = 'generic_err';
					field_msg = 'Whoops, something went wrong sending your message. Please try again...';
				}
			}

			$('#' + field).text(field_msg).show();
		}

		Recaptcha.reload();
	}

	function dhfee_showFormSuccess(data) {
		var msg = '<h2>Sent successfully!</h2>';
	   	msg += '<p>Your ticket has been sent to our billing team successfully.</p>';
		msg += '<p>For reference, your ticket # is <b>' + data['sent'] + '</b>.</p>';

		$('#inquery_success').html(msg).show();
		$('#inquery_form').hide();
		$('body').animate({scrollTop: 0}, 300);
		Recaptcha.reload();
	}

	// If they're trying to use an AMEX card, we actually need to ask them for the last 5!
	$('#cc_first').change(function() {
		var n = ccardIsAmex() ? 5 : 4;
		$('#cc_last_label').text('Last ' + n + ' digits of credit card charged');
	}).change();

	$('#inquery_form').submit(function() {
		// A quick alias, since we're going to be doing this a lot.
		function gv(n) {
			var obj = $('#' + n);
			if (obj.length) {
				return jQuery.trim(obj.val());
			}
		}

		$('#inquery_form .error').hide();

		var errors = {};

		// First, a quick check that all required fields have a value.
		var req_fields = {
			'fname': 'Please enter your first name',
			'lname': 'Please enter your last name',
			'email': 'Please enter your email address',
			'email_conf': 'Please confirm your email address',
			'charge_date': 'Please enter the date of the charge',
			'charge_amount': 'Please enter the amount (in USD) of the charge',
			'comments': 'Please enter a brief message for us',
		};
		for (var fn in req_fields) {
			var v = gv(fn);
			if (!v.length) {
				errors[fn] = req_fields[fn];
			}
		}

		var fname     = gv('fname');
		var lname     = gv('lname');
		var email     = gv('email');
		var email_c   = gv('email_conf');
		var cc_first  = gv('cc_first');
		var cc_last   = gv('cc_last');
		var c_date    = gv('charge_date');
		var c_amount  = gv('charge_amount');
		var situation = gv('situation');
		var comments  = gv('comments');
		var rc_chalng = gv('recaptcha_challenge_field');
		var rc_resp   = gv('recaptcha_response_field');

		// Do some additional validation now, beyond what's above.
		if (email.length) {
			if (!email.match(/^.+@.+\..+$/)) {
				errors['email'] = 'Please enter a valid email address.';
			} else if (email_c.length && email != email_c) {
				errors['email'] = 'Please double check that you have entered your email correctly.';
			}
		}

		if (cc_first.length || cc_last.length) {
		   	if (cc_first.length != 4) {
				errors['cc_first'] = 'Please enter only the first 4 digits.';
			} else if (!cc_first.match(/^\d+$/)) {
				errors['cc_first'] = 'Please enter only digits.';
			}

			var n = ccardIsAmex() ? 5 : 4;
			if (cc_last.length != n) {
				errors['cc_last'] = 'Please enter only the last ' + n + ' digits.';
			} else if (!cc_last.match(/^\d+$/)) {
				errors['cc_last'] = 'Please enter only digits.';
			}
		}

		if (!rc_resp.length) {
			errors['recaptcha'] = 'Please answer the CAPTCHA.';
		}


		if (c_amount == 'In US dollars $') {
			errors['charge_amount'] = 'Please enter the amount (in USD) of the charge.';
		}

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

		// Send JSONP request, to create ticket.
		$('#inquery_submit').text('Please wait...').attr('disabled', 'disabled');
		jQuery.jsonp({
			url: DH_API_ROOT,
			data: {
				cmd: 'contact-send',
				origin: 'dh-fee',
				name: fname + " " + lname,
				email: email,
				regarding: 'Billing',
				subject: situation,
				message: comments,
				challenge: rc_chalng,
				response: rc_resp,
				ccard_first_four: cc_first,
				ccard_last_four: cc_last,
				ccard_date: c_date,
				ccard_value: c_amount,
			},
			success: function(data, textStatus) {
				if ('errors' in data) {
					dhfee_showFormErrors(data['errors']);
				} else if ('error' in data) {
					dhfee_showFormErrors({ error: data['error'] });
				} else {
					dhfee_showFormSuccess(data);
				}

				$('#inquery_submit').removeAttr('disabled').html('<span>Submit</span>');
			},
			error: function(xOpts, textStatus) {
				$('#inquery_submit').removeAttr('disabled').html('<span>Submit</span>');
				dhfee_showFormErrors({
					client_error: "An error occurred submitting your support request."
				});
			}
		});

		return false;
	}); // end: $('#inquery_form').submit(

});

