$(document).ready(function() {
	$("#ContactForm").hide(); 
	$("a#LinkContactUs, a#fsm, a.cta-button").click(function(e) {
		if ($("#ContactForm").is(":hidden")){
			
			$("#ContactForm").slideDown("slow");

		} else{
			$("#ContactForm").slideUp("slow");

		}
		e.preventDefault();
	});

	var _loadingImg = $('<img />')
		.attr('src','/img/ajax-loader.gif')
		.attr('id','loader')
		.hide();

	
	$('#ContactDoForm').submit(function(e){
		
		_loadingImg.appendTo('#ContactForm').show();
		
		$.post('/contacts/index',
            $(this).serializeArray(),
            afterValidate,
            "json"
        );
        return false;

		e.preventDefault();		
	});
	
	function afterValidate(data,status) {
		$(".flmessage").remove();
		$(".error-message").remove();
		
        if (data.errors) {
            onError(data.errors);
        } else if (data.success) {
            onSuccess(data.success);
        }		
	}
	
	function onError (data) {
	   flashMessage(data.message);
		$.each(data.data, function(model, errors) {
			for (fieldName in this) {
				var element = $("#" + camelize(model + '_' + fieldName));
				var _insert = $(document.createElement('div')).insertAfter(element);
 				_insert.addClass('error-message').text(this[fieldName])
			}
	        _loadingImg.hide();
	    });
	};
	
	function onSuccess(data) {
        
        _loadingImg.hide();
		flashMessage(data.message);
		
		$( "#ContactForm" ).clearForm();

		setTimeout( function() {
			$('#ContactForm').slideUp("slow");
		}, 5000 );
	
    };

	function flashMessage(message) {
		
        var _insert = $(document.createElement('div')).css('display', 'none');
        _insert.attr('id', 'flashMessage').addClass('flmessage').text(message);
        _insert.insertBefore($("#ContactDoForm")).fadeIn('slow');
    }

	function camelize(string) {
        var a = string.split('_'), i;
        s = [];
        for (i=0; i<a.length; i++){
            s.push(a[i].charAt(0).toUpperCase() + a[i].substring(1));
        }
        s = s.join('');
        return s;
    }
});

