
// DOM ready event
jQuery(document).ready(function() {
	Service.SendAffiliate.getInstance();
});

// Creating Namespace
var Service = {};

/**
 * Module: SendAffiliate
 */
Service.SendAffiliate = (function()  {
	function constructor(caller, options) {
		// Private members.
		function onSend() {
			var name = jQuery('#affiliateForm #name').val();
			if (jQuery.trim(name) == '') {
				jQuery('#affiliateForm #name').focus();
				alert('Please enter your name.');
				return false;
			}

			var validRegnow = Common.Validate.validateFormat(
				Common.Validate.FORMAT.REGNOW, jQuery('#affiliateForm #regnow').val());
			if (!validRegnow) {
				jQuery('#affiliateForm #regnow').focus();
				alert('Please enter a valid RegNow Affiliate ID.');
				return false;
			}

			var website = jQuery('#affiliateForm #website').val();
			if (jQuery.trim(website) == '') {
				jQuery('#affiliateForm #website').focus();
				alert('Please enter a valid website URL.');
				return false;
			}

			var validEmail = Common.Validate.validateFormat(
				Common.Validate.FORMAT.EMAIL, jQuery('#affiliateForm #email').val());
			if (!validEmail) {
				jQuery('#affiliateForm #email').focus();
				alert('Please enter a valid E-mail address.');
				return false;
			}

			var comment = jQuery('#affiliateForm #comment').val();
			if (jQuery.trim(comment) == '') {
				jQuery('#affiliateForm #comment').focus();
				alert('Please give your comments.');
				return false;
			}

			var validCaptcha = Common.Validate.validateFormat(
				Common.Validate.FORMAT.CAPTCHA, jQuery('#affiliateForm #captchaId').val());
			if (!validCaptcha) {
				jQuery('#affiliateForm #captchaId').focus();
				alert('Please enter the correct Secure ID you see in the image.');
				return false;
			}

			var param = jQuery('#affiliateForm').serialize();
			Common.Utils.log("affiliate form: \n" + Common.Utils.tostr(param));
			Common.AJAX.getInstance().postOnBlock("/contact/sendAffiliateCall.call",
				param, afterSend);

			// force browser ignore the another event at one time because this method binds the event 'onsubmit' and 'onclick'
			return false;
		}

		function afterSend(data, textStatus) {
			Common.Utils.log(Common.Utils.tostr(data));

			if (Common.Utils.isObject(data)) {
				if (data.type == 'INFO') {
					jQuery('#affiliateForm').clearForm();
					alert(data.message);
				} else {
					// occur exception
					alert(data.message);
				}
			}
		}

		return { // Public members.
			initialize: function() {
				jQuery('#sbAffiliateLink').removeClass('sidebarNav').addClass('sidebarNavCur');
				jQuery('#affiliateForm').submit(onSend);
				jQuery('#affiliateForm #send').click(onSend);
				jQuery('#affiliateForm #name').focus();

				Common.Utils.loadCaptcha();
			}
		};
	} // constructor end

	// Singleton control code
	var instance;
	return {
		getInstance: function()	{
			if(!instance) {
				instance = constructor();
				instance.initialize();
			}
			return instance;
		}
	}
})();

