function submitSurveyFormData()
{
	$.get("/survey/ajax/process.php?", $('#survey_form').formToArray(), null, 'json');
}

// ---- Falk ---

//-------------------------------------
// -- Verify Mail Functions          --
//-------------------------------------

function initVerifyScreen()
{
	var needMailVerify = inlineCheckErrorsMsgFormInit['FROM_STATE_NEEDMAILVERIFY'];
	var needSMSVerify = inlineCheckErrorsMsgFormInit['FROM_STATE_NEEDSMSVERIFY'];
	var isMailVerified = inlineCheckErrorsMsgFormInit['FROM_STATE_ISMAILVERIFIED'];
	var isSMSVerified = inlineCheckErrorsMsgFormInit['FROM_STATE_ISSMSVERIFIED'];
	var isAN = inlineCheckErrorsMsgFormInit['USER_STATE_ISAN'];

	if(needMailVerify)
	{
		$('#mailFrame').show();
		if(isMailVerified)
		{
			$('#verifyMailFrame').hide();
			$('#verifiedMailFrame').show();
			$('#changeMailFrame').hide();
		}
		else
		{
			$('#verifyMailFrame').show();
			$('#verifiedMailFrame').hide();
			$('#changeMailFrame').hide();
			$('#needVerificationMsg').show();
		}
	}
	else
	{
		$('#mailFrame').hide();
	}
	
	if(needSMSVerify)
	{
		$('#smsFrame').show();
		if(isSMSVerified)
		{
			$('#verifyCellularNumberFrame').hide();
			$('#verifiedCellularNumberFrame').show();
			$('#changeCellularNumberFrame').hide();
		}
		else
		{
			$('#verifyCellularNumberFrame').show();
			$('#verifiedCellularNumberFrame').hide();
			$('#changeCellularNumberFrame').hide();
			$('#needVerificationMsg').show();
		}
	}
	else
	{
		$('#smsFrame').hide();
	}
	
	if(isAN)
	{
		$('#verifyInfoText_AN').show();
		$('#verifyInfoText_AG').hide();
	}
	else
	{
		$('#verifyInfoText_AN').hide();
		$('#verifyInfoText_AG').show();
	}

	if(!needSMSVerify && !needMailVerify)
	{
		$('#infoTextVerified' + (isAN ? '_AN' : '')).show();
		$('#infoTextNonVerified' + (isAN ? '_AN' : '')).hide();
	}

}

function toggleMailChanger()
{
	$('#verifyMailFrame').hide();
	$('#changeMailFrame').show();
}

function changeMail()
{
	var parameters = new Object;

	parameters.method = 'changeEmailAddress';
    	
	parameters.email = $('#emailToChange').val();
    
    parameters.userid = $('#userID').val();
    parameters.userprofileid = $('#userProfileID').val();
    
	$.get
	(
		'/v3/verification/ajax/inline.php',
		parameters,
		handleUserEmailCheckResponse,
		'json'
	);
}

function handleUserEmailCheckResponse(response)
{
	if (response != '{}')
	{	
		if (response.errno == 1)
		{
			$('#errorMsgCheckEmail').show();
			$('#errorMsgCheckEmail').html(response.error);
		}
		else
		{
			$('#errorMsgCheckEmail').hide();
			$('#changeMailFrame').hide();
			
			$('#changeSucssessBoxMsg').html(inlineCheckErrorsMsgFormInit['AJAX_INLINE_MSG_EMAIL_CHANGED']);
			$('#changeSuccessBox').show();
			$('#userEmailDisplay').html(response.email);
			$('#emailToChange').val(response.email);
			$('#verifyMailFrame').show();
		}
	}
}

function sendMailAgain()
{
	var parameters = new Object;

	parameters.method = 'resendEmailAddress';	
    
    parameters.userprofileid = $('#userProfileID').val();
    parameters.userid = $('#userID').val();

	$.get
	(
		'/v3/verification/ajax/inline.php',
		parameters,
		$('#resendMailButton').html(inlineCheckErrorsMsgFormInit['AJAX_INLINE_MSG_EMAIL_RESEND']),
		'json'
	);
}

//-------------------------------------
// -- Verify Mail Functions End      --
//-------------------------------------

//-------------------------------------
// -- Verify SMSCode Functions       --
//-------------------------------------


function toggleCellularNumberChanger()
{
	$('#verifyCellularNumberFrame').hide();
	$('#changeCellularNumberFrame').show();
}

function changeCellularNumber()
{
	var parameters = new Object;

	parameters.method = 'changeCellularPhoneNumber';	
	parameters.phonenumber = $('#cellularNumberToChange').val();
	parameters.mobile_prefix = $('#mobile_prefix').val();
    parameters.userprofileid = $('#userProfileID').val();
    parameters.userid = $('#userID').val();
    
	$.get
	(
		'/v3/verification/ajax/inline.php',
		parameters,
		handleUserCellularNumberResponse,
		'json'
	);
}

function handleUserCellularNumberResponse(response)
{
	if (response.errno == 1)
	{
		$('#errorMsgCheckCellularNumber').show();
		$('#errorMsgCheckCellularNumber').html(response.error);
	}
	else
	{
		$('#errorMsgCheckCellularNumber').hide();
		$('#changeCellularNumberFrame').hide();
		
		$('#changeSucssessBoxMsg').html(inlineCheckErrorsMsgFormInit['AJAX_INLINE_MSG_PHONENUMBER_CHANGED']);
		$('#changeSuccessBox').show();
		
		$('#userCellularNumberDisplay').html(response.phonenumber);
		$('#userCellularNumberDisplay2').html(response.phonenumber);
		$('#verifyCellularNumberFrame').show();
	}
	$('#errorMsgCheckSMSCode').hide();
	
}

function submitSMSCode()
{
	var parameters = new Object;

	parameters.method = 'verifySmsCode';	
	parameters.code = $('#smsCode').val();
    
    parameters.userid = $('#userID').val();
    parameters.userprofileid = $('#userProfileID').val();
    
	$.get
	(
		'/v3/verification/ajax/inline.php',
		parameters,
		handleSMSCodeResponse,
		'json'
	);
}

function resendSMSCode()
{
	var parameters = new Object;
	
    parameters.method = 'resendSmsCode';	
    
    parameters.userprofileid = $('#userProfileID').val();
    parameters.userid = $('#userID').val();

	$.get
	(
		'/v3/verification/ajax/inline.php',
		parameters,
		null,
		'json'
	);

	$('#VerifyCellularNumberDescription').hide();
	$('#resendVerifyCellularNumberDescription').show();
	$('#resendVerifiyCellularNumberLink').hide();
	
}

function handleSMSCodeResponse(response)
{
	if (response.errno == 1)
	{
		$('#errorMsgCheckSMSCode').html(response.error);
		$('#errorMsgCheckSMSCode').show();
	}
	else
	{
		$('#errorMsgCheckSMSCode').hide();
		$('#verifyCellularNumberFrame').hide();
		$('#verifiedCellularNumberFrame').show();
		$('#resendVerifiyCellularNumberLink').hide();
		
		if (response.sendto)
		{
			window.location.href = response.sendto;
		}
	}
}

//-------------------------------------
// -- Verify SMS Functions End       --
//-------------------------------------

// Registration form functions# 

// Content toggles
//
var embeddedMode = false;
var registrationSucceeded = false;

function showErrorOnField(fieldname, errormsg)
{
	if ($.browser.mozilla)
	{
		$('#' + fieldname).attr('style', 'outline: 2px solid red; border: 0px;');
	}
	else
	{
		$('#' + fieldname).attr('style', 'border: 2px solid red');
	}	
	$('#err-' + fieldname).html(errormsg);
	$('#err-' + fieldname).show();
}

function hideErrorOnField(fieldname)
{
	$('#' + fieldname).attr('style','');
	$('#err-' + fieldname).hide();
}

function showHelpBubble(anchorId, bubbleId, onClientPosition)
{
	var bubbleObject = document.getElementById(bubbleId);
	var inputObject = document.getElementById(anchorId);
	
	if (!bubbleObject || !inputObject)
	{
		return (false);
	}

	var position = {};
	position = onClientPosition ? $('#'+anchorId).offset() : $('#'+anchorId).position();
	
	var offsetTop = position.top - $('#' + bubbleId).height();
	var offsetLeft = position.left;
	
	$('#' + bubbleId).css('top', offsetTop + 'px');
	$('#' + bubbleId).css('left', offsetLeft + 'px');
	$('#' + bubbleId).show();
	
	$('#formHider').css('top', $('#' + bubbleId).offset().top + 'px');
	$('#formHider').css('left', $('#' + bubbleId).offset().left + 'px');
	$('#formHider').css('width', $('#' + bubbleId).width() + 'px');
	$('#formHider').css('height', $('#' + bubbleId).height()+ 'px');
	$('#formHider').show();
	
}

function showPasswordChanger()
{
	$('#password_change_trigger').toggle();
	$('#password_change').toggle();
	$('#password_label').toggle();
	$('#old_password_label').toggle();
	$('#old_password').attr('name', 'old_password').enable().val('');
}	


// Event handlers for help
//
function registerHelpBubbleEvents()
{
	var helpBubbleFields = new Array
	(
		'password',
		'mobile_number',
		'landline_number'
	);

	// Show / hide static help bubble for all helpBubbleFields
	//
	for (var i in helpBubbleFields)
	{
		$('#' + helpBubbleFields[i]).blur
		(
			function()
			{
				$('#info-' + $(this).attr('id')).hide();
				$('#formHider').hide();
			}
		).focus
		(
			function()
			{
				if($(this).attr('id') == 'mobile_number')
				{
					$('#helpbubble_mobile_number').html
					(
						$('#check_an')[0].checked
							? mobileNumberHelpBubbleContentAn
							: mobileNumberHelpBubbleContentAg
					);
				}
				showHelpBubble($(this).attr('id'), 'info-' + $(this).attr('id'));
			}
		);
	}

	// Show / hide dynamic help bubble for username, depending on check_an status,
	// and trigger AJAX username suggestion fetching
	//		
	$('#username').blur
	(
		function()
		{
			if ($('#check_an').attr('checked'))
			{

				$('#info-' + $(this).attr('id') + '-AN').hide();
			}
			else
			{
				$('#info-' + $(this).attr('id') + '-AG').hide();
			}
			$('#formHider').hide();
			setTimeout("$('#suggestions').hide();", 200);
		}
	).focus
	(
		function()
		{
			if ($('#check_an').attr('checked'))
			{
				showHelpBubble($(this).attr('id'), 'info-' + $(this).attr('id') + '-AN');
			}
			else
			{
				showHelpBubble($(this).attr('id'), 'info-' + $(this).attr('id') + '-AG');
			}

			if ($('#firstname').val().length >= 3)
			{
				getUserNameSuggestions($('#firstname').val());
			}
		}
	);
}

// Username suggestion (triggered right above)
//
function getUserNameSuggestions(inputString)
{
	var parameters = new Object;

	parameters.method = 'suggestUsernames';	
	parameters.firstname = inputString;
	$.get
	(
		"/v3/registration/ajax/inline.php",
		parameters,
		handleUserNameSuggetionResponse,
		'json'
	);
}

function handleUserNameSuggetionResponse(response)
{
	var htmlcode = '';
	
	if (response.suggestions != "{}")
	{	
		var position = {};
		position = $('#username').position();
		
		var offsetTop = position.top + 10;
		var offsetLeft = position.left;
		
		$('#suggestions').css('top', offsetTop + 'px');
		$('#suggestions').css('left', offsetLeft + 'px');
		$('#suggestions').show();

		htmlcode = $('#suggestionsTitleTemplate').html();

		for (var i = 0; i < response.suggestions.length; i++)
		{
			htmlcode += 
				'<li onClick="fillUserName(\''
					+ response.suggestions[i]
					+ '\');">' 
					+ response.suggestions[i]
					+ "</li>";
		}
		$('#autoSuggestionsList').html(htmlcode);
	}
}

function fillUserName(newValue)
{
	$('#username').val(newValue);
	setTimeout("$('#suggestions').hide();", 200);
}

// Inline local field validation
//
function validateTelephoneLandlineNumber()
{
	if (this.keyCode != 16)
	{	
		hideErrorOnField('landline_number');
	}
	
	if (!this.value.match(/^[0-9]{1,50}$/) && this.value.length > 0)
	{
		showErrorOnField($(this).attr('id'), inlineCheckErrors['AJAX_ERROR_MSG_PHONE_NUMBER']);
		newText = this.value.replace(/[^0-9,]/g, '');
		this.value = newText;
	}
}


// Inline remote field validation
//
function validateRemotely(field)
{
	if (field.value != "")
	{
		var parameters = new Object;
		
		parameters.fieldId = field.id;
		
		if(field.id == 'email')
		{
			parameters.email = field.value;
			parameters.method = 'checkEmail';			
		}
		else if (field.id == 'username')
		{
			parameters.username = field.value;
			parameters.check_an = $('#check_an').val();
			parameters.method = 'checkUsername';
		}		
			
		$.get
		(
			"/v3/registration/ajax/inline.php",
			parameters,
			handleRemoteValidationResponse,
			'json'
		);
	}
}

function validateRemotelyOnLegacyFeed(parameters, callbackfunction)
{
	/**
	* @todo XmlHTTPRequest / Bugzilla: 25
	*/ 
	$.post("/formChecker.php", parameters, callbackfunction, 'json');
	
}

function handleRemoteValidationResponse(response)
{
	hideErrorOnField(response.fieldName);
	if (response.errno == 0)
	{
		return;
	}
	else if (response.errno == 1)
	{
		showErrorOnField(response.fieldId, response.error);
	}
}

// Complete form validation / submit
//
function handleFormSubmissionResponse(response)               
{
	if (response.errorlist)
	{
		$('#regFormSubmitButton').attr('src', regFormSubmitButtonUrl);
		$('#regFormSubmitButton').attr("disabled", false); 
		for (key in response.errorlist)
		{
			showErrorOnField(key,response.errorlist[key]);
		}
		showErrorOnField('submit', inlineCheckErrors['AJAX_ERROR_MSG_FINAL_ERROR_NOTE']);
	}
	else
	{
		hideErrorOnField('submit');
		if (embeddedMode)
		{
			registrationSucceeded = true;
			$('#mhContent').hide();
			$('#subscriptionForm').submit();
		}
		else
		{
			window.location.href = response.sendto;
		}
	}
}

function submitFormData()
{
	if (embeddedMode && registrationSucceeded)
	{
		return (true);
	}

	$('#regFormSubmitButton').attr('src', pleaseWaitButtonUrl);
	$('#regFormSubmitButton').attr("disabled", true); 
	
	$('#err-submit').hide();
	
	$('#registration_form input, #registration_form textarea, #registration_form select').each
	(
		function(i, el) 
		{
			hideErrorOnField(el.name);
		}
	);
	
	var formData = $('#registration_form').formToArray();
	if (embeddedMode)
	{
		formData.push
		(
			{name: 'mode', value: 'embedded'}
		);
	}

	
	$.get("/v3/registration/ajax/process.php?", formData, handleFormSubmissionResponse, 'json');
	return (false);
}

var handleZipCodeVerificationResponse = function(response) 
{
	if (response)
	{
		if (response.result == -1)
		{
			showErrorOnField('zip', inlineCheckErrors['AJAX_ERROR_MSG_ZIPCODE']);
		}
		else if (response.result == 1)
		{
			if ( $('#city').val() == '') $('#city').val(response.city);
		}
		else if (response.result == 3)
		{
			showErrorOnField('zip', inlineCheckErrors['AJAX_ERROR_MSG_ZIP_PROPOSAL'] + ' ' + response.nearestValidZipcode);
		}
	}
}

// Attachment of the event handlers
//
function initRegForm()
{

	// Bindings for local validation / action
	//
	$('#city').keyup
	(
		function()
		{
			hideErrorOnField($(this).attr('id'));
		}
	);

	$('#landline_number').keyup(validateTelephoneLandlineNumber);
	
	$('#password').change
	(
		function()
		{
			hideErrorOnField($(this).attr('id'));

			if ($('#password').val().length > 0 && $('#password').val().length < 6)
			{
				showErrorOnField($(this).attr('id'), inlineCheckErrors['AJAX_ERROR_MSG_PASSWORD']);
			}
			else if ($('#password').val().toLowerCase() == $('#username').val().toLowerCase())
			{
				showErrorOnField($(this).attr('id'), inlineCheckErrors['AJAX_ERROR_MSG_PASSWORD_IS_USERNAME']);
			}
		}
	);

	$('#passwordACK').keyup
	(
		function()
		{
			hideErrorOnField($(this).attr('id'));
		}
	).change
	(
		function()
		{
			hideErrorOnField($(this).attr('id'));
		
			if ($('#password').val() != $('#passwordACK').val())
			{
				showErrorOnField($(this).attr('id'), inlineCheckErrors['AJAX_ERROR_MSG_PASSWORD_MISMATCH']);
			}
		}
	);


	// Remote (AJAX) verification
	//
	$('#zip').keyup
	(
		function()
		{
			hideErrorOnField($(this).attr('id'));
			
			if ($('#zip').val().length == 5)
			{
				var parameters = new Object;
				parameters.check = 'zipcode';
				parameters.zipcode = $('#zip').val();
				parameters.cityContainerID = 'city';
				validateRemotelyOnLegacyFeed(parameters, handleZipCodeVerificationResponse);
			}
		}
	);

	$('#email').keyup
	(
		function()
		{
			hideErrorOnField($(this).attr('id'));
		}
	).change
	(
		function()
		{
			validateRemotely(this);
		}
	);

	$('#username').keyup
	(
		function()
		{
			hideErrorOnField($(this).attr('id'));

			if (!this.value.match(/^[\w\-\._]{0,40}$/))
			{
				showErrorOnField($(this).attr('id'), inlineCheckErrors['AJAX_ERROR_MSG_USERNAME_PLAINTEXT']);
				newText = this.value.replace(/[^\w\-\._]/g, '');
				this.value = newText;
			}
		}
	).change
	(
		function()
		{
			validateRemotely(this);
			setTimeout("$('#suggestions').hide();", 200);
		}
	);

	// Submit handling
	//
	if ($('#regFormSubmitButton').length > 0)
	{
		$('#regFormSubmitButton').click(submitFormData);
	}
	else if ($('#subscriptionFormSubmitButton').length > 0)
	{
		$('#subscriptionFormSubmitButton').click(submitFormData);
		embeddedMode = true;
	}

	// Form field dependency handling
	//
	$('#check_an').click(handleAnClick);	
	$('#check_company').click(handleCompanyStatusChange);
	$('#contractorConfirmationButton').click(handleAnConfirmation);
		
	$('#check_directorlikecontact').click
	(
		function()
		{
			if ($('#check_directorlikecontact').attr('checked'))
			{
				$('#container_isLikeContact').hide();
			}
			else
			{
				$('#container_isLikeContact').show();
			}
		}
	);						

	function handleAnConfirmation()
	{
		$('#check_an').attr('checked', true);
		handleAnStatusChange();
		$('#formHider').hide();
		$('#contractorConfirmationDialogue').hide();
	}

    function handleAnClick()
    {
 		if (editProfileMode && $('#check_an').attr('checked'))
		{
			$('#check_an').attr('checked', false);
			showHelpBubble('check_an', 'contractorConfirmationDialogue', true);			
		}
		else
		{
			handleAnStatusChange();
		}
    }

	function handleAnStatusChange()
	{
		if ($('#check_an').attr('checked'))
		{
			$('#benefitContractor').show();
			$('#benefitBuyer').hide();			
			$('#check_company').attr('checked', true);
			$('#contractorSpecificData').show();
		}
		else
		{	
			$('#benefitContractor').hide();
			$('#benefitBuyer').show();
		}
	}

	function handleCompanyStatusChange()
	{
		if ($('#check_company').attr('checked'))
		{
			$('#contractorSpecificData').show();
		}
		else
		{
			$('#contractorSpecificData').hide();
		}
	}

	// OnLoad initialization
	//
	registerHelpBubbleEvents();	
	handleAnStatusChange();
	handleCompanyStatusChange();
}