// Front end for PHPList utilizing Dojo Toolkit
// PHPList is hidden from the user, presenting itself only in modal dialog boxes

dojo.require("dijit.Dialog");
dojo.require("dijit.form.TextBox");
dojo.require("dijit.form.Button");

dojo.addOnLoad(function() {
	initPHPListInput();
	var signupSubmit = dojo.byId("SignupSubmit");
	dojo.connect(signupSubmit, 'onclick', doSignupCheck);
	checkIntent();
});

var globalTextColor = '#666';

function initPHPListInput() {
	var signupEmail = dojo.byId("SignupEmail");
	dojo.connect(signupEmail, 'onfocus', function() {
		if(signupEmail.value == 'Enter your email address') {
			signupEmail.value = '';
			signupEmail.style.color = globalTextColor;
		}
	});
	dojo.connect(signupEmail, 'onblur', function() {
		if(signupEmail.value == '') {
			signupEmail.value = 'Enter your email address';
			signupEmail.style.color = globalTextColor;
		}
	});
}

function getUrlVars() {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

function checkIntent() {
	// If we are coming from a PHPList provided URL, decide what to do and do it
	var hash = getUrlVars();
	var intent = hash['p'];
	var userId = hash['uid'];
	switch(intent) {
		case 'confirm':
			confirmAddress(intent, userId);
			break;
		case 'unsubscribe':
			unsubscribeAddress(userId);
			break;
		case 'blacklist':
			blacklistAddress(userId);
			break;
		case 'preferences':
			userPrefs(userId);
			break;
		case 'forward':
			forwardMessage(userId);
			break;
		default:
			break;
	}
}

function confirmAddress(intent, userId) {
	dojo.xhrGet({
		url: '/signup/?p=' + intent + '&uid=' + userId,
		load: function(response, ioArgs) {
			startDialog();
			handleDialog(null, intent);
			return response;
		}
	});
}

function unsubscribeAddress(userId) {

}

function blacklistAddress(userId) {

}

function userPrefs(userId) {

}

function forwardMessage(userId) {

}

function doSignupCheck(evt, editedEmail) {
 	if(editedEmail) {
 		var submittedEmail = editedEmail;
 	} else {
 		dojo.stopEvent(evt);
 		var submittedEmail = dojo.byId("SignupEmail").value;
 		startDialog();
 	}
	checkAnimation();
	var addressOkay = checkAddress(submittedEmail).addCallback(function(addressOkay) {
		if(addressOkay) {
			// The email address is valid, now check the database
			var databaseOkay = checkDatabase(submittedEmail).addCallback(function(databaseOkay) {
				if(databaseOkay) {
					// The email is new and unique and can be subscribed to the newsletter
					doSignup(submittedEmail);
					resetInput();
				} else {
					// The email exists in the database already, just let the user know
					handleDialog(submittedEmail, 'duplicate');
					resetInput();
				}
			});
		} else {
			// The email address is not valid and must be edited
			handleDialog(submittedEmail, 'invalid');
			resetInput();
		}
	});
}

function resetInput() {
	// Reset the textarea input back to the default
	var signupEmail = dojo.byId("SignupEmail");
	signupEmail.value = 'Enter your email address';
	signupEmail.style.color = globalTextColor;
}

function startDialog() {
	// Build the empty modal dialog. All contents will be handled later at appropriate times
	var responseDialog = new dijit.Dialog({
		title: 'Empty Dialog',
		id: 'theDialog',
		content: 'Empty content',
		draggable: false,
		autofocus: false,
		style: "width: 500px; height: 300px;"
	});
	dojo.style(responseDialog.closeButtonNode, "display", "none");
	responseDialog.show();
}

function checkAnimation() {
	// Just present the Checking Address animation and on completion show appropriate content
	var responseDialog = dijit.byId('theDialog');
	responseDialog.attr('title', 'Verifying Email Address');
	responseDialog.attr('content', '<div style="text-align: center; margin-top: 100px;"><img src="/images/backgrounds/loading.gif" width="36" height="36" border="0" /></div>');
}

function checkAddress(address) {
	// xhr call to php script for checking validity of email address. Return true or false.
	var validAddress = dojo.xhrPost({
		url: '/helpers/validEmail.php',
		postData: "email=" + address,
		load: function(response, ioArgs) {
			return response;
		},
		error: function(response, ioArgs) {
			return response;
		}
	});
	return validAddress;
}

function checkDatabase(address) {
	var inDatabase = dojo.xhrPost({
		url: '/helpers/databaseEmail.php',
		postData: "email=" + address,
		load: function(response, ioArgs) {
			return response;
		},
		error: function(response, ioArgs) {
			return response;
		}
	});
	return inDatabase;
}

function doSignup(address) {
	var status = 'valid';
	var postedForm = dojo.xhrPost({
		url: '/signup/?p=subscribe&id=1',
		content: {
			"email": address,
			"htmlemail": "1",
			"list[1]": "signup",
			"subscribe": "Subscribe",
			"listname[1]": "blast list"
		},
		handle: handleDialog(address, 'valid')
	});
}

function handleDialog(address, status) {
	// Must handle Address Okay, Address Already Subscribed, and Invalid Email (with form to correct)
	var title = '';
	var content = '';
	var responseDialog = dijit.byId('theDialog');
	switch(status) {
		case 'valid':
			title = 'Subscription Confirmation';
			content = '<div style="height: 213px; margin-top: 15px;"><p>A confirmation email has been sent to:</p><b>' + address + '</b><p>Please confirm the subscription in that email.</p></div>';
			responseDialog.attr('title', title);
			responseDialog.attr('content', content);
			break;
		case 'invalid':
			title = 'Invalid Email Address';
			content = '<div style="height: 213px; margin-top: 15px;" id="MessageContents"><p><b>' + address + '</b> appears to be an invalid email.</p><p>Please correct the mistake below and Try Again or close this dialog box.</p></div>';
			responseDialog.attr('title', title);
			responseDialog.attr('content', content);
			// Add a textfield with the address for user to edit and resubmit
			var editEmail = new dijit.form.TextBox({id: 'editEmail', name: 'editEmail', value: address, });
			// responseDialog.containerNode.appendChild(editEmail.domNode);
			dojo.byId('MessageContents').appendChild(editEmail.domNode);
     	  	editEmail.attr('style', 'width: 400px; height: 30px; padding-left: 10px; color: #333; font-size: 15px;');
			// Add the resubmit button
			var tryAgainButton = new dijit.form.Button({label: "Try Again", id: 'TryAgain'});
			responseDialog.containerNode.appendChild(tryAgainButton.domNode);
			dojo.connect(dojo.byId('TryAgain'), "onclick", function() {
				doSignupCheck(null, editEmail.value);
			});
			break;
		case 'duplicate':
			title = 'Duplicate Entry';
			content = '<div style="height: 213px; margin-top: 15px;"><p><b>' + address + '</b> is already in the database.</p></div>';
			responseDialog.attr('title', title);
			responseDialog.attr('content', content);
			break;
		case 'confirm':
			title = 'Email Confirmed';
			content = '<div style="height: 213px; margin-top: 15px;"><p>Email confirmed!</p></div>';
			responseDialog.attr('title', title);
			responseDialog.attr('content', content);
			break;
	}
	var closeButton = new dijit.form.Button({label: "Close", id: 'Close'});
	closeButton.attr('style', 'float: right;');
	responseDialog.containerNode.appendChild(closeButton.domNode);
	dojo.connect(dojo.byId('Close'), "onclick", function() {
		responseDialog.hide();
		responseDialog.destroyRecursive();
	});
}
