var cf_trans = 500;
var google_map = false;
var cf_status = 'hidden';

function init_contact_loader(){
	// Set the initial state for the contact form container
	$('.contact-form').css({
		'position': 'absolute',
		'z-index': 300,
		'top': -48
	});
	
	// Show the close button and add contact form hide functionality onclick
	$('.contact-form .close').show().click(function(){
		if(cf_status == 'visible') hide_contact_form();
	});

	// Add contact form toggle functionality onclick
	$('a[href="/contact"], a[href="' + contact_page + '"]').click(function(){
		if(cf_status == 'hidden') show_contact_form();
		if(cf_status == 'visible') hide_contact_form();
		return false;
	});
	
	// Add contact form hide functioniality onclick
	$('.contact-overlay-container').click(function(){ if(cf_status == 'visible') hide_contact_form(); });
}

// Change the contact form from a normal submit to and AJAX submit
$(document).ready(function(){
	$('#contact-mail-page, #contact-mail-page1').submit(submit_contact_form);
});

// Show the contact form
function show_contact_form(){
	cf_status = 'loading';
	
	$('html').scrollTop(0);
	$('body').scrollTop(0);
	
	$('.contact-overlay-container').stop(true).fadeIn(cf_trans);
	$('.contact-form').stop(true).fadeIn(cf_trans, function(){ cf_status = 'visible' });
	
	// If the google map hasn't been loaded yet, load the google map
	// NOTE: The google map isn't loaded until the contact form is displayed
	// Google maps don't display correctly when generated in hidden elements
	if(!google_map) load_google_map();
}

// Hide the contact form
function hide_contact_form(){
	cf_status = 'loading';
	$('.contact-overlay-container').stop(true).fadeOut(cf_trans);
	$('.contact-form').stop(true).fadeOut(cf_trans, function(){ cf_status = 'hidden' });
}

// Load the google map
function load_google_map(){

	// Add google map class to container
	// If JS is turned off, a large blank area won't be shown
	$('#googlemap').addClass('googlemap');
	
	var center = new google.maps.LatLng(49.436724, -2.553574);
	var myOptions = {
		zoom: 15,
		center: center,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	var map = new google.maps.Map(document.getElementById("googlemap"), myOptions);

	//var image = new google.maps.MarkerImage('/<?php print $directory ?>/images/map-marker.png',
	
	new google.maps.Size(41, 35), // This marker is 41 pixels wide by 35 pixels tall.
	
	new google.maps.Point(0,0), // The origin for this image is 0,0.
	
	new google.maps.Point(10, 33); // The anchor for this image is the base of the flagpole at 0,35.

	var mapMarker = new google.maps.Marker({
		position: center,
		map: map,
		//icon: image,
		draggable:false
	});
	google.maps.event.addListener(mapMarker, 'dragend', function(mapMarker){
		console.log(this.getPosition().lat() + ", " + this.getPosition().lng());
	});
	
	// Set google map loaded status to true
	google_map = true;
}

// Attempt to submit the contact form via AJAX
function submit_contact_form(){

		// Remove error class from inputs and textareas
		$(this).find('input, textarea').removeClass('error');
	
		var error = '';
		
		// If the name field is blank, add error class to element and add a new error message
		if($('#edit-name, #edit-name-1').val().length == 0){
			error += '<li>Name field is required!</li>';
			$('#edit-name, #edit-name-1').addClass('error');
		}
		
		// If the email is not valid, add error class to element and add a new error message
		if(!validateEmail($('#edit-mail, #edit-mail-1').val())){
			error += '<li>You must use a valid email address!</li>';
			$('#edit-mail, #edit-mail-1').addClass('error');
		}
		
		// If the subject field is blank, add error class to the element and add a new error message
		if($('#edit-subject, #edit-subject-1').val().length == 0){
			error += '<li>Subject field is required!</li>';
			$('#edit-subject, #edit-subject-1').addClass('error');
		}
		
		// If the telephone field is blank, add error class to the element and add a new error message
		if($('#edit-field-telephone, #edit-field-telephone-1').val().length == 0){
			error += '<li>Telephone field is required!</li>';
			$('#edit-field-telephone, #edit-field-telephone-1').addClass('error');
		}
		
		// If the message box is blank, add error class to the element and add a new error message
		if($('#edit-message, #edit-message-1').val().length == 0){
			error += '<li>Message field is required</li>';
			$('#edit-message, #edit-message-1').addClass('error');
		}
		
		// If there are any errors, display them in the message container, and return false
		if(error != ''){
			$('.contact-form .message-container').html('<div class="messages error"><ul>' + error + '</ul></div>');
			return false;
		}
	
		// If there aren't any errors, submit the form via ajax
		$.ajax({
			url: '/ajax-contactform',
			data: $(this).serialize(),
			type: 'POST',
			success: function(data){
				
				// If there are no error messages and there is a success message, remove any existing errors and display a success message
				if($(data).find('.error').length == 0 && $.trim($(data).find('.status').text()) == 'Your message has been sent.'){
					$('.contact-form .message-container').html('');
					$('.contact-form h2').html('Thank you, your message has been sent');
				}else{ // Else display any messages in the message container
					$('.contact-form .message-container').html($(data).filter('.message-container').html());
				}
				
				// Reload the contact form and re-add the AJAX submit to the form
				$('#block-contact_form_blocks .content, #block-contact_form_blocks-1 .content').html($(data).filter('.form').find('.content').html());
				$('#contact-mail-page, #contact-mail-page1').submit(submit_contact_form);
			}
		});
		
		// Return false - Override the default submit behaviour
		return false

}

// Validate an email address
function validateEmail(email) { 
	var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/ 
	return email.match(re)
}
