﻿function doCCMPromoSignup(parametersJson) {
	$.getJSON($("#CCMPromo").attr("proxyserviceurl")
				, { ParametersJson: parametersJson, CacheBustDateTimeStamp: new Date().toString() }
				, function(json) {
					json = JSON.parse(json.d);
					if (json.Error) {
						alert(json.Message);
						$('#CCMPromo #email').focus();
					} else {
						window.location = $("#CCMPromo").attr("redirecturl");
					}
				}
		);
}

$('#CCMPromo').ready(function() {

	// if press enter in email click the button
	$('#CCMPromo #email').keypress(function(e) {
		if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			$('#CCMPromo #signupSubmit').click();
			return false;
		} else {
			return true;
		}
	});

	// clear keyword text box on enter if default email
	$('#CCMPromo #email').focus(function() {
		if ($.trim($(this).val()) == $(this).attr("default")) {
			$(this).val('');
		}
	});

	// set default keyword text box if empty
	$('#CCMPromo #email').blur(function() {
		if ($.trim($(this).val()) == '') {
			$(this).val($(this).attr("default"));
		}
	});

	$('#CCMPromo #signupSubmit').click(function() {
		var errorMessage = '';
		var hasError = false;
		var setFocus;

		$('#CCMPromo #email').val($.trim($('#CCMPromo #email').val()));
		if ($('#CCMPromo #email').val() == '') {
			$('#CCMPromo #email').focus();
			return false;
		} else if ($('#CCMPromo #email').val() == $('#CCMPromo #email').attr('default')) {
			errorMessage = errorMessage + '-Enter ' + $('#CCMPromo #email').attr('default') + '\n';
			setFocus = $('#CCMPromo #email');
			hasError = true;
		} else {
			// validate formats of data entered
			var inputControlsRegExp = $("#CCMPromo .signup input[regexmatch]");
			for (i = 0; i < inputControlsRegExp.size(); i++) {
				if (($(inputControlsRegExp[i]).val() != '') && ($(inputControlsRegExp[i]).val().match($(inputControlsRegExp[i]).attr("regexmatch")) == null)) {
					if (hasError == false) setFocus = inputControlsRegExp[i];
					hasError = true;
					errorMessage = errorMessage + ' - ' + $(inputControlsRegExp[i]).attr("label") + ' is not in a valid format\n';
				}
			}
		}

		if (hasError) {
			errorMessage = 'Please address the following:\n\n' + errorMessage + '\n';
			alert(errorMessage);
			$(setFocus).focus();
			return false;
		} else {
			var parametersJson = $("#CCMPromo").attr("proxyserviceparameters");
			parametersJson = parametersJson.replace("{email}", $('#CCMPromo #email').val());
			parametersJson = parametersJson.replace("{signupCodeCsv}", $('#NewsletterOption').val());
			parametersJson = parametersJson.replace("{url}", window.location);
			doCCMPromoSignup(parametersJson);
		}

	});

});

