/* fidelio */

function initZipper(ids)
{
	for (var i = 0; i < ids.length; i++)
	{
		$('#'+ids[i]).children().each(function(i) {
			if (i < 3)
			{
				$(this).show();
			}
			else
			{
				$(this).hide();
			}
		});
		$('a.'+ids[i]).click(function(e) {
			var link_id = $(this).attr('rel');
			$('#'+link_id).children(':hidden').slideDown("slow", function() {
				$(this).parent().parent().children('a').fadeOut("fast");
			});
			e.preventDefault();
			return false;
		});
	}
}

function openModalPopup()
{
	var title = $('#modal-popup').children('div.head').children('h2').text();
	var url = '#TB_inline?inlineId=modal-popup&modal=true&width=444';
	$('#modal-popup').find('.close').click(function(e) {
		tb_remove();
		e.preventDefault();
		return false;
	});
	tb_show(title, url, false);
	$('#TB_ajaxContent').css('height', $('#TB_ajaxContent').children('div.modal').height()+'px');
}

function filterErrors(errors)
{
	var result = [];
	for (var formField in errors)
	{
		if (errors[formField]['isEmpty'])
		{
			result[formField] = errors[formField]['isEmpty'];
		}
		else if (errors[formField]['regexNotMatch'])
		{
			result[formField] = errors[formField]['regexNotMatch'];
		}
		else if (errors[formField]['days_mandatory'])
		{
			result[formField] = errors[formField]['days_mandatory'];
		}
		else if (errors[formField]['time_mandatory'])
		{
			result[formField] = errors[formField]['time_mandatory'];
		}
		else if (formField == 'email')
		{
			for (var error in errors[formField])
			{
				result[formField] = errors[formField][error];
				break;
			}
		}
	}
	return result;
}

function showErrorMessages(formId, errors)
{
	errors = filterErrors(errors);
	for (var formField in errors)
	{
		if (formField != 'when')
		{
			$('input[name="'+formField+'"]', $(formId)).parents('p.row').append('<div class="error" style="display: none;">' + errors[formField] + '</div>');
			$('input[name="'+formField+'"]', $(formId)).parents('p.row').children('div.error').fadeIn('fast');
		}
		else
		{
			$('input[name="'+formField+'[]"]', $(formId)).parents('div.row').append('<div class="error" style="display: none;">' + errors[formField] + '</div>');
			$('input[name="'+formField+'[]"]', $(formId)).parents('div.row').children('div.error').fadeIn('fast');
		}
	}
}

function clearErrorMessages(formId)
{
	$(formId).find('div.error').fadeOut('fast').remove();
}

function initAgencySearchForm()
{
	/* $('#zipcode1').val('').focus(); */
	
	$('#agency-search').bind('submit', function(e)
	{
		clearErrorMessages('#agency-search');
		$.post(
			'/agency-search',
			$(this).serialize(),
			function(data) {
				if (data.success)
				{
					$('#zipcode1').val('');
					$('#modal-popup').children('div.modal').html(data.agencies);
					if (typeof pageTracker !== 'undefined')
					{
						var pageviewUrl = (data.language == 'fr') ? '/rendementetplus/agency-search' : '/meerdanrendement/agency-search';
						pageTracker._trackPageview(pageviewUrl);
					}
					openModalPopup();
				}
				else
				{
					showErrorMessages('#agency-search', data.errors);
					$('#zipcode1').focus();
				}
			},
			'json'
		);
		e.preventDefault();
		return false;
	});	
	
	$('#submit-postcode').click(function(e) {
		$('#agency-search').submit();
		e.preventDefault();
		return false;
	});
	
}

var formInitValues = new Array();

function reinitContactForm() {

	if ($('#phone').val() == '000') {
		$('#phone').val('')
	}

	$('#contact-me input').each(function(){
		if($(this).attr('value') == '') {
			$(this).attr('value', formInitValues[$(this).attr('id')]);
			$(this).removeClass('notlabeled');
		}
	});		
}

function initContactMeForm()
{
	/*
	$('#firstname').val('');
	$('#lastname').val('');
	$('#email').val('');
	$('#phone').val('');
	$('#zipcode2').val('');
	$('#week').attr('checked', '');
	$('#weekend').attr('checked', '');
	$('#morning').attr('checked', '');
	$('#noon').attr('checked', '');
	$('#afternoon').attr('checked', '');
	$('#evening').attr('checked', '');
	*/
	
	/*
	*	Hide form itinial values
	*/
	
	$('input:text').each(function(){
		formInitValues[$(this).attr('id')] = $(this).attr('value');
	});
	
	$('input:text').focus(function(){
		if($(this).attr('value') == formInitValues[$(this).attr('id')]) {
			$(this).attr('value', '');
			$(this).addClass('notlabeled');
		}																				
	});
	
	$('input:text').blur(function(){
		if($(this).attr('value') == '') {
			$(this).attr('value', formInitValues[$(this).attr('id')]);
			$(this).removeClass('notlabeled');			
		}																				
	});	
	
	
	$('#contact-me').bind('submit', function(e) {
		clearErrorMessages('#contact-me');
		
		$('#contact-me input:text').each(function(){
			if($(this).attr('value') == formInitValues[$(this).attr('id')]) {
				$(this).attr('value', '');
				$(this).addClass('notlabeled');
			}
		});
		
		var mailRegexp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]{2,}([.][a-z]{2,3})+$/;
		
		if (!$('#email').val().match(mailRegexp)) {
			$('#email').val('');
		}
		
		if ($('#phone').val() == '000') {
			$('#phone').val('')
		}

		if ($('#email').val() != "" && $('#phone').val() == '') {
			$('#phone').val('000')
		}
		
		var formArray = $(this).serializeArray();
		var whenArray = new Array();
		
		$('ul.when_check input:checked').each(function(){
			whenArray.push($(this).attr('id'));
		});
				
		var myValues = new Array();
		
		for (key in formArray) {
		
			if (formArray[key]['name'] == 'when[]') {
				formArray[key]['value'] = whenArray.pop();
			}
		
			myValues.push(formArray[key]['name']+'='+formArray[key]['value']);
		}
		
		var formValues = myValues.join('&');
		/*alert(formValues);*/

		$.post(
			'/contact-me',
			formValues,
			//$(this).serialize(),
			function(data) {
				if (data.success)
				{
					$('#firstname').val('');
					$('#lastname').val('');
					$('#email').val('');
					$('#phone').val('');
					$('#zipcode2').val('');
					$('#week').attr('checked', '');
					$('#weekend').attr('checked', '');
					$('#morning').attr('checked', '');
					$('#noon').attr('checked', '');
					$('#afternoon').attr('checked', '');
					$('#evening').attr('checked', '');
					$('#modal-popup').children('div.modal').html(data.successMessage)
					if (typeof pageTracker !== 'undefined')
					{
						var pageviewUrl = (data.language == 'fr') ? '/rendementetplus/contact' : '/meerdanrendement/contact';
						pageTracker._trackPageview(pageviewUrl);
					}
					openModalPopup();
					reinitContactForm();
				}
				else
				{
					showErrorMessages('#contact-me', data.errors);
					$('#name').focus();
				}
			},
			'json'
		);
		reinitContactForm();
		e.preventDefault();
		return false;
	});
	
	
	$('#submit-contact-me').click(function(e) {
		$('#contact-me').submit();
		e.preventDefault();
		return false;
	});
}

$(document).ready(function() {
	$.ajaxSetup({
		beforeSend: function(request) {
			$('#loading-anim').show();
		},
		complete: function(request, status) {
			$('#loading-anim').hide();
		}
	});
	initZipper(['zippit-1', 'zippit-2']);
	initAgencySearchForm();
	initContactMeForm();
});
