/**
 * JS for Mail Chimp signup form.
 * Date: 2011-07-13
 * Author: ybrunet
 */
$(document).ready(function() {
	/* Clicked from Home page */
	$('#news-overlay-open').click(function () {
		// Clear error
		$('#mc-error').html('');
		$('#id_email').parent().removeClass('error');
		
		$('#signup-overlay').toggle();
		return false;
	});
	
	/* Clicked from all other pages than Home page. */
	$('#overlay-open').click(function () {
		// Copy email field value to the signup form
		if ($(this).prev().val() != 'your@email.com') {
			$('#id_email').val($(this).prev().val());
		}

		// Clear error
		$('#mc-error').html('');
		$('#id_email').parent().removeClass('error');
		
		$('#signup-overlay').toggle();
		return false;
	});
	
	$('#overlay-close').click(function() {
		$('#signup-overlay').toggle();
		window.location.reload();
	});
	
	$('#mc_signup').submit(function () {
		//alert("form submitted");
		var emailError = 'Please fill your email address.';
		var emailVal = $('#id_email').val();
		var platformVal = $('input[name="platform"]:radio:checked').val();
		var genderVal = $('input[name="gender"]:radio:checked').val();
		var countryVal = $('select[name="country"] option:selected').val();
		var interestArr = new Array();
		var interestsVal = $("input:checkbox:checked").each(function() {
			interestArr.push($(this).val()); 
		});
		
		var result = validateEmail(emailVal);
		//alert(result);
		if (result.length > 0) {
			$('#mc-error').html(emailError);
			$('#id_email').parent().addClass('error');
		} else {
//			alert('email '+emailVal);
//			alert('platform '+platformVal);
//			alert('gender '+genderVal);
//			alert('country '+countryVal);
//			alert(interestArr);
			var platform = (platformVal==undefined) ? '' : platformVal;
			var gender = (genderVal==undefined) ? '' : genderVal;
			var country = (countryVal==undefined) ? '' : countryVal;
			
			// Target url is relative to where (the page) it is called
			// So the path must adjust for each folder where it is called.
			var targeturi = getMcapiUri(document.location.href);
			
			$(this).css('cursor', 'progress');
			$.ajax({
				type: 'POST',
				url: targeturi,
				data: {
					email : emailVal,
					platform: platform,
					gender: gender,
					country: country,
					'interest[]': interestArr			
					},		
				dataType: 'json',
				success: function(data){
					//alert(data.status);
					printSubscribeStatus(data.status);
				},
				error: function(data) {
					//alert(data.status);
					printSubscribeStatus(data.status);
				},
				complete: function() {
					$(this).css('cursor', 'default');
				}
			});
		}
		return false;
	});
	
	$('#mc_unsubscribe').submit(function () {
		//alert("form submitted");
		var emailError = 'Please fill your email address.';
		var emailVal = $('#id_email').val();
		var result = validateEmail(emailVal);
		
		if (result.length > 0) {
			$('#mc-error').html(emailError);
			$('#id_email').parent().addClass('error');
		} else {
			// process request
			$.ajax({
				type: 'POST',
				url: 'mcapi/mcapi_listUnsubscribe.php',
				data: {
					email: emailVal
				},		
				dataType: 'json',
				success: function(data){
					//alert(data.status);
					if (data.status == 'success') {
						window.location = 'unsubscribestatus.php';
					} else {
						//alert(data.message);
						window.location = 'unsubscribeerror.php';
					}
				},
				error: function() {
					//alert('error');
					window.location = 'unsubscribeerror.php';
				}
			});			
		}
		return false;
	});	
});

function validateEmail(inputval) {
	var error = "";
	var regex = new RegExp("^[0-9a-z\\._]+@[0-9a-z]+\\..+$","i");
	
	var emailval = jQuery.trim(inputval);
	if (emailval.length == 0) {
		error = "email field must be filled in.";
	} else {
		// pattern match
		if (!regex.test(emailval)) {
			error = emailval+" is an invalide email address.";
		}
	}
	
	return error;
}

function printSubscribeStatus(result) {
	title = (result == 'success') ? 'Almost Finished...' : 'Newsletter Subscription Failed';
	msg = (result == 'success') ? 'We need to confirm your email address.<br />To complete the subscrition, please click the link in the email we just sent you.' : 'We can not process your subscription at the moment.<br />Please try again later.';
	$('#mc-title').html(title);
	$('#mc_signup').remove();
	outstring = 
	'<div class="field"><p>' + msg + '</p></div>' +
	'<div class="field">' +
		'<div class="mc-btn" style="text-align:center;">' +
			'<a class="gray-dk" href="" onclick="window.location.reload()">OK</a>' +
		'</div>' +
	'</div>';
	$(outstring).insertAfter('#mc-title');
}

/**
 * getMcapiUri
 * 
 * Removes 'http://' and trailing 'filename.php' and trailing '/'
 * and calculate the relative location of mcapi php file
 * 
 * @param origUri -- current page url (pass in document.location.href)
 * @returns string -- relative location of mcapi list subscribe php file
 */
function getMcapiUri(origUri) {
	var urlstripped = origUri.replace('http://', '').replace(
			/\/([a-zA-Z0-9_]+)\.php$|\/$/, '');
	var tokenizedStr = (urlstripped).split('/');
	if (tokenizedStr.length == 1) {
		mcapi_uri = 'mc/mcapi/mcapi_listSubscribe.php';
	} else if (tokenizedStr.length == 2) {
		mcapi_uri = '../mc/mcapi/mcapi_listSubscribe.php';
	} else {
		mcapi_uri = '../../mc/mcapi/mcapi_listSubscribe.php';
	}
//	alert(tokenizedStr.toString());
//	alert(tokenizedStr.length);
//	alert(mcapi_uri);

	return mcapi_uri;
}


