var first_form_submit = true;
var callback_completed = false;
var first_form_click_done = false;

/* SP Migration Changes start */
var chkRS = false;
var isAccountQuestions = false;
var additional_submit = false;
/* SP Migration Changes end */

function copyElementData(srcContainer, srcElementSuffix, destElementSuffix) {
	var elements = document.getElementById(srcContainer).getElementsByTagName(
			'*');
	for ( var i = 0; i < elements.length; i++) {
		var element = elements[i];
		if (element.type == 'text' || element.type == 'hidden'
				|| element.type == 'checkbox' || element.type == 'select-one') {
			srcElementId = element.id;
			expDestElementId = srcElementId.substring(0, srcElementId
					.indexOf(srcElementSuffix))
					+ destElementSuffix;
			if (document.getElementById(expDestElementId)
					&& element.value != "") {
				document.getElementById(expDestElementId).value = element.value;
			}
		}
	}
}

function resetElementData(srcContainer) {
	var elements = document.getElementById(srcContainer).getElementsByTagName(
			'*');
	for ( var i = 0; i < elements.length; i++) {
		var element = elements[i];
		if (element.type == 'text') {
				document.getElementById(element.id).value = "";
		}
	}
}

function replaceContent(topContainerId, formContainerId, isUpdate) {

	if ($("#replaceScript").length > 0) {
		script = $("#replaceScript");
		if ($(script).length > 0) {
			$("#replaceScript").empty();
		}
	}

	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.id = 'replaceScript';
	var src = 'http://sms.wmg.com/sms/register?js=true';
	if(isUpdate) {
		src += '&updateprofile=yes';
	}

	var elements = document.getElementById(formContainerId)
			.getElementsByTagName('*');
	for ( var i = 0; i < elements.length; i++) {
		var element = elements[i];
		if (element.type == 'text' || element.type == 'hidden'
				|| (element.type == 'checkbox' && element.checked == 1)
				|| element.type == 'select-one') {
			//Masking mobile number be sent the second time.
			if(isUpdate && element.name == "mobile" &&
				jQuery.trim($("#mListMobile1").val()) == jQuery.trim($("#mListMobile2").val())) {
				src += "&mobile=";
			} else {
				src += "&" + element.name + "=" + jQuery.trim(element.value);
			}
		}
	}
	script.src = src;
	try {
		document.getElementById(topContainerId).appendChild(script);
	} catch (err) {
		// Skip error as this will be take care by the alertTimeoutError method.
		// alert(err);
	}
	setTimeout("alertTimeoutError()", 5000); // wait for 5 seconds

}

/* Setting ErrorMessage on Time out */
function alertTimeoutError() {

	if (!callback_completed) {
		setError("Unable to process your request at this time");
	}
}

/* Registering event handlers for the submit(Layer1 and Layer2) and close button */
$( function() {

	$("#mobilePinForm").children("a.closeButton").click( function(event) {
		$("#mobilePinForm").hide();
		$("#mobilePinForm").removeClass("form2");
		$("#mobilePinForm").removeClass("form3");
		$("#mobilePinForm").addClass("form1");
		event.preventDefault();
		first_form_click_done = false;
	});
	$(".mlistCloseText").click( function(event) {
		$("#mobilePinForm").hide();
		$("#mobilePinForm").removeClass("form2");
		$("#mobilePinForm").removeClass("form3");
		$("#mobilePinForm").addClass("form1");
		event.preventDefault();
		first_form_click_done = false;
	});
	/*
	 * Event Handling on click of "Signup for mailing List" Button This block
	 * displays the Layer1(form 1)
	 */
	$("#mContainer").children("a.mailButton").click( function() {
		first_form_submit = true;
		setError("");
		$("#mobilePinForm").show();
		$('#formContainer1').show();
		$("#formContainer2").hide();
		$('#formContainer3').hide();
		$("#mobilePinForm").addClass("form1");
		$("#mobilePinForm").removeClass("form2");
		$("#mobilePinForm").removeClass("form3");
		$("#formContainer1").find("a.submit").removeClass("disabled");
		$("#formContainer2").find("a.submit").removeClass("disabled");
		resetElementData('formContainer1');
		resetElementData('formContainer2');
		first_form_submit = true;
		callback_completed = false;
		first_form_click_done = false;
	});

	/*
	 * Event Handling for onclick on TEXTFIELDS in Layer1(Form1) Removes the
	 * default text in the TEXTFIELD,allows the user to give inputs
	 */
	$("#mListEmail1").focus( function() {
		$("#mListEmail1").removeClass("err");
	});

	$("#mListMobile1").focus( function() {
		$("#mListMobile1").removeClass("err");
	});

	$("#mListZip1").focus( function() {
		$("#mListZip1").removeClass("err");
	});

	/*
	 * Event Handling for onclick of Submit Button in Layer1(Form1) Validation
	 * Fields - Email, Mailing list and Postal code Returns false when
	 * validation fails
	 */
	$("#formContainer1")
			.find("a.submit")
			.click(
					function(event) {
						if (first_form_click_done) {
							event.preventDefault();
							return false;
						}
						var errorOccured = false;
						var email = $("#mListEmail1").val();
						var zipCode = $("#mListZip1").val();
						var mobile = jQuery.trim($("#mListMobile1").val());
						var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
						// var zipFilter = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
						// var mobileFilter =/^[\+0-9- .]*$/;

						if (!filter.test(email)) {
							$("#mListEmailForm1").find(".error").fadeIn('slow');
							$("#mListEmail1").fadeIn('slow', function() {
								$(this).addClass('err');
							});
							errorOccured = true;
						} else {
							$("#mListEmailForm1").find(".error").hide();
						}
						if (zipCode == "Postal Code" || zipCode.length == 0) {
							$("#mListZipForm1").find(".error").fadeIn('slow');
							$("#mListZip1").fadeIn('slow', function() {
								$(this).addClass('err');
							});
							errorOccured = true;
						} else {
							$("#mListZipForm1").find(".error").hide();
						}

						if (errorOccured) {
							first_form_click_done = false;
							return false;
						}

						callback_completed = false;
						setError("");
						$("#formContainer1").find("a.submit").addClass("disabled");
						if(mobile.length > 0) {
							$("#signuptype1").val("all");
						} else {
							$("#signuptype1").val("any");
						}
						replaceContent('mContainer', 'formContainer1');
						first_form_click_done = true;
						event.preventDefault();
					});

	$("#mListMobile2").focus( function() {
		$("#mListMobile2").removeClass("err");
	});

	$("#mListZip2").focus( function() {
		$("#mListZip2").removeClass("err");
	});

	/*
	 * Event Handling for onclick of Submit Button in Layer2(Form2) Validation
	 * Fields - Postal code and Mailing list Returns false when validation fails
	 */
	$("#formContainer2").find("a.submit").click( function(event) {
		var errorOccured = false;
		var zipCodeForm2 = $("#mListZip2").val();
		var mobile = jQuery.trim($("#mListMobile2").val());
		if(mobile == jQuery.trim($("#mListMobile1").val())) {
			mobile = "";
		}
		// var zipFilter = /(^\d{5}$)|(^\d{5}-\d{4}$)/;

		if (zipCodeForm2.length == 0) {
			$("#mListZipForm2").find(".error").fadeIn('slow');
			$("#mListZip2").fadeIn('slow', function() {
				$(this).addClass('err');
			});
			$("#mlistForm2Left").height(
					$("#mlistForm2Right").height() + 'px');
			errorOccured = true;
		} else {
			$("#mListZipForm2").find(".error").hide();
		}

		if (errorOccured) {
			return false;
		}

		var dobMonth = $("#mlMonthDropDown").val();
		var dobDate = $("#mlDateDropDown").val();

		if (dobMonth != "" && dobDate != "") {
			$("#mListDob").val(dobMonth + "/" + dobDate);
		}
		callback_completed = false;
		setError("");
		$("#formContainer2").find("a.submit").addClass("disabled");
		if(mobile.length > 0) {
			$("#signuptype2").val("all");
		} else {
			$("#signuptype2").val("any");
		}
		replaceContent('mContainer', 'formContainer2', true);
		event.preventDefault();
	});	
});

/*
 * This Callback function is used for retrieving the status of the submitted
 * Form(User details).
 */
function callback(status, response) {
	/* Real Time Sign Up Changes */
	if (chkRS) {
		chkRS = false;
		if ($(joinScrId).length > 0) {
			$.wmgfeature.spCallback(joinScrVal, "joinScreen");
		}
		else if ($(editProfId).length > 0) {
			$.wmgfeature.spCallback(editProfVal, "editProfile");
		}
		else if ($(editAccId).length > 0) {
			if (isAccountQuestions) {
				isAccountQuestions = false;
				$.wmgfeature.spCallback(editAccQueVal, "editAccOues");
			}
			else {
				$.wmgfeature.spCallback(editAccDataVal, "editAccNormal");
			}
		}
	}
	else {
		if (status == 'success') {
			if ($('toReplace').length > 0) {
				document.getElementById('toReplace').innerHTML = response;
			}
			
			if (additional_submit) {
				showMListThankyouScreen();
				additional_submit = false;
				
			}
			else if (first_form_submit) {
				$("#formContainer1").hide();
				copyElementData('formContainer1', '1', '2');
				$("#mobilePinForm").removeClass("form1");
				$("#mobilePinForm").addClass("form2");
				$("#formContainer2").show();
				$("#mlistForm2Left").height($("#mlistForm2Right").height() + 'px');
				first_form_submit = false;
				tryCount = 0;
					
			}
			else {
				
				additional_submit = false;
				$("#additionalIds input[type=checkbox]:checked").each(function(){
					if ($(this).val() != null) {
						additional_submit = true;
						$("#signuptype2").val("any");
						return false;
					}
				});
				if (additional_submit) {
					replaceContent('mContainer', 'formContainer2', false, true);
				}
				else {
					showMListThankyouScreen();
					
				}
					
			}
			
		}
		else {
			if (response.indexOf("already subscribed") > 1 && tryCount < noOfTries) {
				tryCount++;
				if (first_form_submit) {
					$("#signuptype1").val("any");
					replaceContent('mContainer', 'formContainer1', false, false, true);
				}
				else {
					$("#signuptype2").val("any");
					replaceContent('mContainer', 'formContainer2', true, false, true);
				}
				
			}
			else if (null != response && response.toLowerCase().indexOf("keyword does not") > 1 && tryCount < noOfTries) {
				tryCount++;
				if (first_form_submit) {
					$("#signuptype1").val("any");
					replaceContent('mContainer', 'formContainer1', false, false, true);
				}
				else {
					$("#signuptype2").val("any");
					replaceContent('mContainer', 'formContainer2', true, false, true);
				}
					
			}
			else {
				setError(response);
			}
		}
		callback_completed = true;	
	}
}


function showMListThankyouScreen() {

	$("#formContainer2").hide();
	$("#mobilePinForm").removeClass("form2");
	$("#mobilePinForm").addClass("form3");

	$("#formContainer3").show( function() {
		setTimeout( function() {
			$("#mobilePinForm").hide()
		}, 5000);
	});

	first_form_submit = true;

}

function setError(msg){

	if (chkRS) {
		chkRS = false;
		if ($(joinScrId).length > 0) {
			$.wmgfeature.spCallback(joinScrVal, "joinScreen");
		}
		else if ($(editProfId).length > 0) {
			$.wmgfeature.spCallback(editProfVal, "editProfile");
		}
		else if ($(editAccId).length > 0) {
			if (isAccountQuestions) {
				isAccountQuestions = false;
				$.wmgfeature.spCallback(editAccQueVal, "editAccOues");
			}
			else {
			$.wmgfeature.spCallback(editAccDataVal, "editAccNormal");
			}
		}
	} else {
	
		if (msg.indexOf(":") > 0) {
			msg = msg.substring(msg.indexOf(":") + 1);
		}
		if ($('.mlistError')) {
			$('.mlistError').html(msg);
		}
		$("#formContainer1").find("a.submit").removeClass("disabled");
		$("#formContainer2").find("a.submit").removeClass("disabled");
		first_form_click_done = false;
		$("#mlistForm2Left").height($("#mlistForm2Right").height() + 'px');
	}
}


