var tcf = function() {

	var current_contenteditable = {};

	/**
	 * Returns the current editable element
	 */
	function getCurrentContentEditable() {
		if (current_contenteditable.id) {
			var elem = $('#tc_module_inline_edit_'
					+ current_contenteditable.key + '_'
					+ current_contenteditable.id + ' .tc_module_inline_content');
			elem.removeAttr('contenteditable');
			return elem;
		}

		return null;
	}
	;

	/**
	 * End wysiwyg editing.
	 * 
	 * @return The element
	 */
	function endContentTypeEditInline() {
		var elem = getCurrentContentEditable();
		if (!elem)
			return;

		current_contenteditable = {};
		$('body').removeClass('tc_edit_inline');
		$('body').addClass('tc_edit_mode_edit');

		// remove loader from save button
		// parent.$('#tcb_pages_content_save .ui-icon').addClass('icon_save')
		// .removeClass('icon_loader');

		// switch barmode
		parent.$('#tcb_bar_mode_inline').hide();
		parent.$('#tcb_mode_changer').show();
		var idparts = explode("_",elem.parent().attr('id'));
		tcf.reloadModule(idparts[5]);
	}
	;

	/**
	 * Save the current wysiwyg editable via ajax.
	 */
	function saveContentTypeEditInline() {
		var elem = getCurrentContentEditable();
		if (!elem)
			return;

		tcf.showLoadingMask(current_contenteditable.id);

		$.post(tc_backend_root_url + 'tcBackendPages/axJsonInlineSave', {
			id : current_contenteditable.id,
			key : current_contenteditable.key,
			content : elem.html()
		}, function(data, status, request) {
			tcf.hideLoadingMask(current_contenteditable.id);
			if (data.success) {
				endContentTypeEditInline();
			} else {
				var args = {
					title : 'Fehler',
					text : ''
				};

				jQuery.each(data.errors, function() {
					args.text = args.text + '<span style="color:red;">' + this
							+ "</span><br/><br/>";
				});

				parent.tc.alert(args);

			}
		}, 'json');
	}
	;

	return {

		/**
		 * Contenteditable Plugin
		 */
		contenteditable : tcContentEditable,

		/**
		 * change to editmode
		 * 
		 * @param string
		 *            mode
		 */
		changeEditMode : function(mode) {

			try{
				$;
			}
			catch(err){
				return;
			}			
			
			// remove all
			$('body').removeClass('tc_edit_mode_edit');
			$('body').removeClass('tc_edit_mode_arrange');
			$('body').removeClass('tc_arrange_move');

//			$('.tc_area_module_holder').sortable('disable');

			if (mode == 'preview') {
				// do nothing
				parent.jQuery('#tcb_bar_mode_preview').show();
			} else if (mode == 'edit') {
				// create contenteditables
				// show edit buttons
				$('body').addClass('tc_edit_mode_edit');

			} else if (mode == 'arrange') {
				// show move indicators
				$('body').addClass('tc_edit_mode_arrange');
				$('.tc_area_module_holder').sortable('enable');
			}
			tcf.loadBackendElems();
		},

		/**
		 * reload a module via ajax
		 * 
		 * @TODO update
		 */
		reloadModule : function(id,callback,divide,skip_parent_loading) {
			
			if(!skip_parent_loading)
			{
				var elem = $('#tc_module_' + id);
				var parentelem = elem.parentsUntil('.tc_area');
				if(elem && parentelem){
				parentelem = parentelem.parent();
				  if(parentelem.get(0).id)
					  id = parentelem.get(0).id.substr(10);
				}
			}
			
			
			if(divide != false && $('#tc_module_' + id + '.tc_pool_divide, #tc_module_' + id + ' .tc_pool_divide').size())
			{
				divide = true;
			}
			
			tcf.showLoadingMask(id);
			if(callback == null) callback = function() {};
			$(
					'#tc_module_' + id + ' .tc_module_content, #tc_module_'
							+ id + '_module_holder').load(
						tc_root_url + '/tcFrontendPageRender/axHtmlShowModule', {
						id : id,
						tc_page_id: parent.tc.getPageId(),
						divide: divide?1:0
					}, function() {
						tcf.hideLoadingMask(id);
						tcf.loadBackendElems();
						callback.call($('#tc_module_' + id));						
					});
		},

		/**
		 * Remove a module from the dom
		 */
		removeModule : function(id) {
			$('#tc_module_' + id).slideUp(200, function() {
				$('#tc_module_' + id).remove();
				tcf.loadBackendElems();
			});
		},
		
		endArrangeMove: function()
		{
			$('body').removeClass('tc_arrange_move');				
			parent.$('#tcb_bar_mode_preview').show();
			parent.$('#tcb_bar_mode_arrange_move').hide();	
			$('.tc_elem_to_move').removeClass('tc_elem_to_move');			
		},
		
		/**
		 * Moves a module
		 */
		moveModule: function(targetelem)
		{
			var idparts = explode("_",$('.tc_elem_to_move').attr('id'));
			var source_id = idparts[2];
			idparts = explode("_",$(targetelem).attr('id'));
			var target_id = idparts[4];
			var target_place = idparts[3];
			
			
			tcf.showLoadingMask(source_id);
			$('body').removeClass('tc_arrange_move');	
			
			//TODO Post from parent cause of url
			$.post(tc_backend_root_url + 'tcBackendPages/axJsonMoveModule', {
				source_id : source_id,
				target_id : target_id,
				target_place: target_place
			}, function(data, status, request) {
				
				tcf.hideLoadingMask(source_id);
				
				$('.tc_elem_to_move').removeClass('tc_elem_to_move');
				
				if (!data.success) {
					var args = {
						title : 'Fehler',
						text : ''
					};

					jQuery.each(data.errors, function() {
						args.text = args.text + '<span style="color:red;">' + this
						+ "</span><br/><br/>";
					});

					parent.tc.alert(args);
				}else{					
					$('#tc_module_' + source_id).slideUp(400,function(){
						if(target_place == 'before')
							$('#tc_module_' + source_id).remove().insertBefore('#tc_module_' + target_id);
						else
							$('#tc_module_' + source_id).appendTo('#tc_module_' + target_id  + ' .tc_area_module_holder:first');
						
						$('#tc_module_' + source_id).slideDown();
						tcf.loadBackendElems();
					});
				}				
				parent.$('#tcb_bar_mode_preview').show();
				parent.$('#tcb_bar_mode_arrange_move').hide();
				
			}, 'json');			
				
		},

		/**
		 * Triggers initialization for editing a content type.
		 */
		contentTypeEdit : function(id, key) {
			parent.tc.openContentTypeSettings(id, key);
		},
		contentTypeEditInline : function(options) {
			$('body').removeClass('tc_edit_mode_edit');
			$('body').addClass('tc_edit_inline');
			parent.$('#tcb_mode_changer').hide();
			parent.$('#tcb_bar_mode_inline').show();
			parent.$('#tcb_toolbar_page_buttons button').hide();
			
			$.each(options.formattings, function(index,value){
				parent.$('#tcb_pages_content_' + value).show();
			});
			var elem = $('#tc_module_inline_edit_' + options.key + '_' + options.id
					+ ' .tc_module_inline_content');
			elem.tcContentEditable();
			current_contenteditable = {
				id : options.id,
				key : options.key,
				content : elem.html()
			};
		},

		/**
		 * Init to cancel the editable.
		 */
		contentTypeEditInlineCancel : function() {
			endContentTypeEditInline();
		},
		/**
		 * Init to save the editable
		 */
		contentTypeEditInlineSave : function() {
			saveContentTypeEditInline();
		},

		/**
		 * shows the loading mask for a specific module
		 */
		showLoadingMask : function(id) {
			
			var elem = $('#tc_module_' + id + ' .tc_module_loading_overlay');
			
			var height = elem.parent().outerHeight();
			var width = elem.parent().outerWidth();			
			
			elem.height(height).width(width).addClass('show');
			$(
					'#tc_module_'
							+ id
							+ ' .tc_module .tc_module_loading_overlay, #tc_module_'
							+ id + ' .tc_area .tc_module_loading_overlay')
					.removeClass('show');
		},
		/**
		 * hide the loading mask for a specific module
		 */
		hideLoadingMask : function(id) {
			$('#tc_module_' + id + ' .tc_module_loading_overlay').removeClass(
					'show');
		},
		loadBackendElems : function(id) {
			if (id) {
				mainprefix = '#tc_module_' + id;
				subprefix = '#tc_module_' + id + ' ';
			} else {
				mainprefix = '';
				subprefix = '';
			}

			// remove old elems
			$(subprefix + '.tc_backend_elem').remove();
			$('.tc_elem_to_move').removeClass('tc_elem_to_move');

			// loading mask
			$(mainprefix + '.tc_module, ' + mainprefix + '.tc_area')
					.each(
							function(index, item) {
								$(this).prepend('<div class="tc_module_loading_overlay tc_backend_elem"></div>');
								$(this).prepend('<div class="tc_module_actions tc_backend_elem"><div class="tc_module_actions_inner tc_backend_elem"></div></div>');								
							});

			
			
			//move drop handles
			$(mainprefix + '.tc_area')
					.each(
							function(index, item) {
								var idparts = explode('_', $(this).attr('id'));
								$('.tc_area_module_holder:first',this)
										.append(
										/* TODO translate */
										'<div id="tc_move_drop_aslast_' + idparts[2] + '" class="tc_move_drop_handle tc_backend_elem"></div>');
								$('.tc_area_module_holder',this).children().last().click(function(){
									tcf.moveModule(this);
								});								
								
							});

			$(mainprefix + '.tc_area .tc_module, ' + mainprefix + '.tc_area .tc_area').each(function(index, item) {
				var idparts = explode("_",$(this).attr('id'));				
				$(this).before(
						/* TODO translate */
						'<div id="tc_move_drop_before_' + idparts[2] + '" class="tc_move_drop_handle tc_backend_elem"></div>');
				$(this).prev().click(function(){
					tcf.moveModule(this);
				});
			});
				
			
			// add settings button
			$(mainprefix + '.tc_module_with_setting ')
					.each(
							function(index, item) {
								$(this).find('.tc_module_actions .tc_module_actions_inner:first').prepend(
												/* TODO translate */
												'<div class="tc_setting_button tc_edit_mode tc_button tc_backend_elem icon_page_white_wrench" title="Edit the settings of this element."></div>');
								$('#' + $(this).get(0).id	+ ' .tc_setting_button').click(
										function(event) {
											parent.tc.openModuleSettings($(
													event.target).parent().parent().parent().get(
													0).id.substr(10));
										});
							});
			
			// add inline button
			$(subprefix + '.tc_module_inline_edit')
					.each(
							function(index, item) {
								var idparts = explode('_', item.id);
								
								var module_id = $(this).parent().parent().parent().get(0).id;
								
								if(!module_id || module_id.substr(0,10) != 'tc_module_')
									return;
								
								$('#' + module_id + ' .tc_module_actions .tc_module_actions_inner:first')
										.prepend(
												'<div class="tc_edit_button tc_edit_mode tc_button tc_backend_elem icon_page_white_edit '
														+ tcf_content_type['editicon-'
																+ idparts[5]
																+ '-'
																+ idparts[4]]
														+ '" title="Edit this content"></div>');

								$('#' + module_id + ' .tc_edit_button:first')
										.click(
												function(event) {
													var idparts = explode('_',
															$(event.target)
																	.parent().parent().parent().parent().find('.tc_module_inline_edit:first')
																	.get(0).id);
													tcf_content_type['callback-'+  idparts[5] + '-'	+ idparts[4]]({id: idparts[5], key: idparts[4]});
												});
								
							/*	var module = $(item).parent().parent();
								module.dblclick(module,
										function(event) {
											if(!$('body').hasClass('tc_edit_mode_edit')) return;
											$($(event.data).find('.tc_module_inline_edit:first').get(0).id);
											tcf_content_type['callback-'+  idparts[5] + '-'	+ idparts[4]]({id: idparts[5], key: idparts[4]});
										});		*/						
							});
			
			// move and remove handles
			$(
					mainprefix + '.tc_area .tc_module, .tc_area ' + mainprefix
							+ '.tc_module, ' + mainprefix
							+ '.tc_area .tc_area, .tc_area ' + mainprefix
							+ '.tc_area')
					.each(
							function(index, item) {
								$(this).find('.tc_module_actions .tc_module_actions_inner:first')
								.prepend(
										/* TODO translate */
										'<div class="tc_move_handle tc_button tc_backend_elem icon_move" title="Move this element."></div>');
								
								
								$(this).find('.tc_module_actions .tc_module_actions_inner:first')
								.prepend(
										/* TODO translate */
										'<div class="tc_remove_handle tc_button tc_backend_elem icon_delete" title="Remove this element."></div>');								

								$('#' + $(this).get(0).id + ' .tc_remove_handle').click(
										function(event) {
											parent.tc.cntrlr.deleteModule($(
													event.target).parent().parent().parent().get(
													0).id.substr(10));
										});
								$('#' + $(this).get(0).id + ' .tc_move_handle').click(
												function(event) {
													parent.$('#tcb_bar_mode_preview').hide();
													parent.$('#tcb_bar_mode_arrange_move').show();
													$(this).parent().parent().parent().addClass('tc_elem_to_move');
													$(this).parent().parent().parent().next('.tc_move_drop_handle').remove();
													$(this).parent().parent().parent().prev('.tc_move_drop_handle').remove();
													$(this).parent().parent().parent().find('.tc_move_drop_handle').remove();
													$('body').addClass('tc_arrange_move');
												});

							});
			

			// add handles
			$(mainprefix + '.tc_area')
					.each(
							function(index, item) {
								$(this).find('.tc_module_actions .tc_module_actions_inner:first')
										.prepend(
												/* TODO translate */
												'<div class="tc_add_handle tc_button tc_backend_elem icon_add" title="Add a new element here."></div>');

								var id = $(this).get(0).id;
								$('#' + id + ' .tc_add_handle').click(
										function(event) {
											parent.tc.openAddModule(id
													.substr(10));
										});
							});
						
			
			
			// add pool button
			$(mainprefix + '.tc_pool')
					.each(
							function(index, item) {
								$(this).find('.tc_module_actions .tc_module_actions_inner:first')
										.prepend(
												/* TODO translate */
												'<div class="tc_open_button tc_edit_mode tc_button tc_backend_elem icon_arrow_divide_right" title="Open/Close this pool area to edit/see all elements."></div>');
								var button = $('#' + $(this).get(0).id + ' .tc_open_button');
								button.unbind('click');
								button.click(
										function(event) {
											var elem = $(event.target).parent().parent().get(0);
											if($(event.target).hasClass('icon_arrow_divide_right'))
											{
												tcf.reloadModule(elem.id.substr(10),function(){
													var elem = $($(this).find('.tc_open_button').get(0));
													elem.removeClass('icon_arrow_divide_right');
													elem.addClass('icon_arrow_join_right');
													$(this).addClass('tc_pool_divide');
												},true,true);
											}else{

												tcf.reloadModule(elem.id.substr(10),function(){
													var elem = $($(this).find('.tc_open_button').get(0));
													elem.addClass('icon_arrow_divide_right');
													elem.removeClass('icon_arrow_join_right');		
													$(this).removeClass('tc_pool_divide');													
												},false,true);
											}
										});
								if($(this).hasClass('tc_pool_divide'))
								{
									button.removeClass('icon_arrow_divide_right');
									button.addClass('icon_arrow_join_right');
								}
							});					

			$(subprefix + '.tc_content_global').each(function(index,item)
			{
				$(this).prepend('<div class="tc_content_global_identifier tc_backend_elem"></div>');
			});
			$(subprefix + '.tc_content_page').each(function(index,item)
			{
				$(this)
				.prepend('<div class="tc_content_page_identifier tc_backend_elem"></div>');
			});		
			
			
			/*
			 * $('#tc_module_5_module_holder').nestedSortable( { // connectWith:
			 * '.tc_area_module_holder', tolerance : 'pointer', items :
			 * '.tc_module, .tc_area'
			 * 
			 * }); $('.tc_area_module_holder').nestedSortable('disable');
			 */

			/*
			 * 
			 * $('.tc_area_module_holder').nestedSortable({ placeholder:
			 * 'tc_arrange_placeholder', items: '.tc_module' });
			 */

		},
		/*
		loadTooltips : function() {
			// init tooltips
			$('.tc_button[title]').wTooltip( {
				className : "tc_tooltip",
				style : false,
				fadeIn : 100,
				fadeOut : 200,
				offsetX : 10,
				offsetY : 10
			});
		},*/
		/**
		 * init
		 */
		init : function() {
			// init parent ajax error
			$(document).ajaxError(function(e, xhr, options, err) {
				parent.tc.ajaxError(e, xhr, options, err);
			});

			tcf.loadBackendElems('');
//			tcf.loadTooltips();
		},
		trigger : function(params) {
			$.event.trigger(params);
			parent.$.event.trigger(params);
		},
		getUrl: function()
		{
		  return location.href;	
		},
		getRootUrl: function()
		{
		  return tc_root_url; 
		},
		reload: function()
		{
			$('body').html('<div style="margin: 20px auto; width: 300px;">Loading ...</div>');
			document.location.reload();
		}
	};
}();


$(document).ready(function() {
	tcf.init();
	parent.tcf = tcf;
	$('body').bind('tc_global_event', function(e, params) {
		if (params.type)
			tcf.trigger(params);
	});
	if(parent && parent.tc)
		parent.tc.cntrlr.previewLoaded();
});

