MCFC.contentmodules = function() {

	var customisation_carousel_initialised = false;
	var module_positioning_initialised = false;
	var loading_module = false;

	/*
	INIT FUNCTIONS
	*/

	var init_module_positioning = function() {
		// Make content modules drag and droppable.
		$("#content-modules .content-modules-column").sortable({
			items: '.module',
			connectWith: ['.content-modules-column'],
			containment: $('#content'),
			distance: 10,
			forcePlaceholderSize: true,
			handle: 'h3',
			helper: 'clone',
			opacity: 1,
			placeholder: 'module-placeholder',
			revert: true,
			scroll: false,
			scrollSensitivity: 40,
			scrollSpeed: 40,
			tolerance: 'pointer', // pointer || intersect
			zIndex: 5,
			update: update_positions, // This event is triggered when the user stopped sorting and the DOM position has changed.
			start: function(event, ui) { $('object', ui.helper).css('visibility', 'hidden'); } // start sorting
		});
		module_positioning_initialised = true;
	};

	var init_customisation_carousel = function() {
		$('#content-modules-customisation').css('height', 1).css('overflow', 'hidden').show();
		$('#content-modules-carousel').jcarousel({
			start: 	MCFC.direction() == 'rtl' ? 100 : 1,   // start at the opposite end for rtl
			scroll: 5, // number of items to scroll at once.
			animation: 'slow', // 'fast'
			easing: 'swing',
			initCallback: function() {
				// timeout hack to get safari to not scream about 0 size.
				setTimeout(function() {
					$('#content-modules-customisation').hide().css('height', 'auto').css('overflow', 'visible');
				}, 200);
			}
		});
		customisation_carousel_initialised = true;
	};

	var init_customisation_tab = function() {
		$('#content-modules-customisation-tab .open').click(pub.open);
		$('#content-modules-customisation-tab .close').click(pub.close);
	};

	MCFC.init.add_on_dom_ready(init_customisation_carousel);
	MCFC.init.add_on_dom_ready(init_customisation_tab);



	/*
	PRIVATE METHODS
	*/

	// call this to enable user customisation
	// drag drop of modules and switching them on and off.
	var enable_customisation = function() {
		// make sure we can drag boxes around.
		enable_module_positioning();
		// make sure we can remove boxes (ticking).
		$('#content-modules').addClass('module-customisation-enabled');
		// change tab button to open.
		$('#content-modules-customisation-tab .open').hide();
		$('#content-modules-customisation-tab .close').show();
	};

	var disable_customisation = function() {
		// make sure we cant drag boxes around.
		disable_module_positioning();
		// TODO make sure we cant remove boxes (ticking).
		$('#content-modules').removeClass('module-customisation-enabled');
		// change tab button to open.
		$('#content-modules-customisation-tab .open').show();
		$('#content-modules-customisation-tab .close').hide();
	};

	var enable_module_positioning = function() {
		if (!module_positioning_initialised) {
			init_module_positioning();
		}
		$('#content-modules .module-header').addClass('customisable');
		$('#content-modules .content-modules-column').sortable('enable');
	};

	var disable_module_positioning = function() {
		$('#content-modules .module-header').removeClass('customisable');
		$('#content-modules .content-modules-column').sortable('disable');
	};

	// gets a callback when a column has been modified.
	var update_positions = function(event, ui) {
		save_user_customisation();
	};

	var is_module_active = function(module_id) {
		return !!$('#module-' + module_id).get(0);
	};

	var get_smallest_column_index = function() {
		var smallest_col_index = 0;
		var number_of_modules = 99;
		var counter = 0;
		$('#content-modules .content-modules-column').each(function() {
			if ($('.module', this).length < number_of_modules) {
				smallest_col_index = counter;
				number_of_modules = $('.module', this).length;
			}
			counter++;
		});
		return smallest_col_index;
	};

	var add_module = function(module_id) {
		var url = MCFC.contentmodules.data.get_contentmodule_url.replace('[ID]', module_id);
		var query_string = {};
		loading_module = true;
		$.get(url, query_string, function(data, success) {
			if (success == 'success') {
				var column = $($('#content-modules .content-modules-column')[get_smallest_column_index()]);
				column.append(data);
				if (MCFC.fontsizes) {
					MCFC.fontsizes(column.find('.module:last'));
				}
				save_user_customisation();
			} else {
				console.error('Could not load url ' + url);
			}
			loading_module = false;
		});
		$('#module-tray-' + module_id).addClass('active');
	};

	var remove_module = function(module_id) {
		$('#module-tray-' + module_id).removeClass('active');
		$('#module-' + module_id).remove();
		save_user_customisation();
	};

	var save_user_customisation = function() {
		var settings = [];
		var x = 0;
		var y = 0;
		$('#content-modules .content-modules-column').each(function() {
			y = 0;
			$('.module', this).each(function() {
				var id = $(this).attr('id').replace(/^module-/, '');
				settings.push({ id: id, x: x, y: y });
				y++;
			});
			x++;
		});
		$.post(MCFC.contentmodules.data.save_contentmodule_url, { settings: JSON.stringify(settings) });
	};

	/*
	PUBLIC METHODS
	*/

	var pub = {

		open: function() {
			$('#content-modules-customisation').slideDown();
			enable_customisation();
			return false;
		},

		close: function(speed) {
			$('#content-modules-customisation').slideUp(speed);
			disable_customisation();
			return false;
		},

		toggle: function(module_id) {
			if (loading_module) { return; }
			if (is_module_active(module_id)) {
				remove_module(module_id);
			} else {
				add_module(module_id);
			}
		}

	};

	return pub;

} ();