var first_form_submit = true;
var additional_submit = false;
var mobile_form_handle = false;
var callback_completed = false;
var first_form_click_done = false;
var mobileFilter = /^[.]{0}$|^\d{10,15}$/;
var mobileFilterUS = /^[.]{0}$|^\d{10}$/;
var mobileFilterOTHER = /^[.]{0}$|^\d{10,15}$/;

var noOfTries = 2;
var tryCount = 0;
var chkRS = false;
var isAccountQuestions = false;

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;
			}
		} else if (element.type == 'select') {
		
			srcElementId = element.id;
			expDestElementId = srcElementId.substring(0, srcElementId
							.indexOf(srcElementSuffix))
							+ destElementSuffix;
							
			if (document.getElementById(expDestElementId)
					&& element.value != "") {
				$(expDestElementId + " option[@selected='selected']").removeAttr("selected");
				$(expDestElementId + " option[@value='" + element.value + "']").attr("selected","selected");	
			}
			
		}
	}
}

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, isAdditional, maskMobile) {

	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';
	}

	if(mobile_form_handle) {
		src += '&mobile=' + jQuery.trim($("#mListMobile1").val()) + '&keywordId=' + $("#keywordId1").val() + '&signuptype=any';
	} else {
		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') {
				
				var id = element.id;
				if((maskMobile && element.name == "mobile") ||(isUpdate && element.name == "mobile" &&
					jQuery.trim($("#mListMobile1").val()) == jQuery.trim($("#mListMobile2").val()))) {
					//Masking mobile number be sent the second time.
					src += "&mobile=";
				} else if (isUpdate && id && id.match("^additional_") == "additional_") {
					//Masking additional List Ids be sent the second time.
					continue;
				} else if (isAdditional && id && id.match("^newsletterId") == "newsletterId") {
					//Masking regular List Ids be sent the third time.
					continue;
				} else if (isAdditional && id && id.match("^keywordId") == "keywordId") {
					//Masking regular mobile keyword Ids be sent the third time.
					continue;				
				} else {
					// Business as usual
					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()", 10000); // wait for 8 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;
			tryCount = 0;
		});
		$(".mlistCloseText").click(function(event){
			$("#mobilePinForm").hide();
			$("#mobilePinForm").removeClass("form2");
			$("#mobilePinForm").removeClass("form3");
			$("#mobilePinForm").addClass("form1");
			event.preventDefault();
			first_form_click_done = false;
			tryCount = 0;
		});
		/*
		 * 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;
			tryCount = 0;
			
			$("#mListEmailForm1").show();
			$("#mListMobileForm1").hide();
			$("#mListZipForm1").show();
			$("#mListCountryForm1").show();
			$(".mobilesignupmsg").hide();
			$("#mListMobileForm2").hide();
			
			$("#mobileFormWrapper").addClass("mailTheme");
			$("#mobileFormWrapper").removeClass("mobileTheme");
		});
		/*
		 * Event Handling on click of "Signup for mailing List" Button This block
		 * displays the Layer1(form 1)
		 */
		$("#mContainer").children("a.mobileButton").click(function(){
			first_form_submit = true;
			mobile_form_handle = 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');
			$(".mobilesignupmsg").show();
			first_form_submit = true;
			callback_completed = false;
			first_form_click_done = false;
			tryCount = 0;
			
			$("#mListEmailForm1").hide();
			$("#mListMobileForm1").show();
			$("#mListZipForm1").hide();
			$("#mListCountryForm1").hide();
			
			$("#mobileFormWrapper").addClass("mobileTheme");
			$("#mobileFormWrapper").removeClass("mailTheme");
		});
		
		
		
		/*
		 * 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;
			
			if (mobile_form_handle) {
			
				var mobile = jQuery.trim($("#mListMobile1").val());
				mobile = mobile.replace(/\s|\+|\-/g, '');
				
				if (mobile.length == 0 || !mobileFilter.test(mobile)) {
					/*	setError("Please Enter a valid Mobile Number"); */
					$("#mListMobileForm1").find(".error").fadeIn('slow');
					$("#mListMobile1").fadeIn('slow', function(){
						$(this).addClass('err');
					});
					errorOccured = true;
				}
				else {
					$("#mListMobileForm1").find(".error").hide();
					/*	 $('.mlistError').empty(); */
				}
				var mKeywordId = MobileKeywordIds['United States'];
				$("#keywordId1").val(mKeywordId);
				
			}
			else {
			
				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})+$/;
				
				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();
				}
				
				var mobile = mobile.replace(/\s|\+|\-/g, '');
				var country = jQuery.trim($("#mListCountry1").val());
				
				if (country == 'United States') {
					mobileFilter = mobileFilterUS;
				}
				else {
					mobileFilter = mobileFilterOTHER;
				}
				
				if (!mobileFilter.test(mobile)) {
					/*	setError("Please Enter a valid Mobile Number"); */
					$("#mListMobileForm1").find(".error").fadeIn('slow');
					$("#mListMobile1").fadeIn('slow', function(){
						$(this).addClass('err');
					});
					errorOccured = true;
				}
				else {
					$("#mListMobileForm1").find(".error").hide();
					/*	 $('.mlistError').empty(); */
				}
				
				
				var newsletterId = "";
				if (EmailListIds[country]) {
					newsletterId = EmailListIds[country];
				}
				else {
					newsletterId = EmailListIds['United States'];
				}
				$("#newsletterId1").val(newsletterId);
				
				var keywordId = "";
				if (MobileKeywordIds[country]) {
					keywordId = MobileKeywordIds[country];
				}
				else {
					keywordId = MobileKeywordIds['United States'];
				}
				$("#keywordId1").val(keywordId);
				
			}
			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());
			var countryLyr2 = jQuery.trim($("#mListCountry2").val());
			
			mobile = mobile.replace(/\s|\+|\-/g, '');
			
			if (countryLyr2 == 'United States') {
				mobileFilter = mobileFilterUS;
			}
			else {
				mobileFilter = mobileFilterOTHER;
			}
			if (!mobileFilter.test(mobile)) {
				/* 			setError("Please Enter a valid Mobile Number"); */
				$("#mListMobileForm2").find(".error").fadeIn('slow');
				$("#mListMobile2").fadeIn('slow', function(){
					$(this).addClass('err');
				});
				errorOccured = true;
			}
			else {
				$("#mListMobileForm2").find(".error").hide();
				/* $('.mlistError').empty(); */
			}
			
			
			if (jQuery.trim($("#mListMobile2").val()) == 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();
			
			var country = jQuery.trim($("#mListCountry2").val());
			
			var newsletterId = "";
			if (EmailListIds[country]) {
				newsletterId = EmailListIds[country];
			}
			else {
				newsletterId = EmailListIds['United States'];
			}
			
			
			var keywordId = "";
			if (MobileKeywordIds[country]) {
				keywordId = MobileKeywordIds[country];
			}
			else {
				keywordId = MobileKeywordIds['United States'];
			}
			
			$("#newsletterId2").val(newsletterId);
			$("#keywordId2").val(keywordId);
			
			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){
		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 (mobile_form_handle) {
						showMListThankyouScreen();
						mobile_form_handle = false;
						
					}
					else 
						if (first_form_submit) {
							$("#formContainer1").hide();
							showMListThankyouScreen();
							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(){
	
		$("#formContainer1").hide();
		$("#formContainer2").hide();
		$("#mobilePinForm").removeClass("form1");
		$("#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');
		}
	}




