var FORM_GENERATOR_URL = null;
var FORM_GENERATOR_CONTROL_OPTION_SELECT = '[x]';
var FORM_GENERATOR_LANG = {

	'page' : {

		'actions' : {

			'create' : 'Steuerelement erstellen',
			'move' : 'Seite verschieben',
			'delete' : 'Seite löschen'
		}

	},

	'control' : {

		'title' : {

			'type' : 'Typ'

		},

		'actions' : {

			'move' : 'Steuerelement verschieben',
			'edit' : 'Steuerelement bearbeiten',
			'delete' : 'Steuerelement löschen'
		}

	}

};

$('.modFormGenerator-protected-pages')
		.ready(
				function() {

					formGenerator_preaparePageSortable($('ul.modFormGenerator-protected-pages'));
		
					$('a[actionType="createPage"]').click(function() {

						formGenerator_createPage();

					});

					$('a[actionType="saveForm"]')
							.click(
									function() {

										var item = $(this).parent('li');

										if (!item
												.hasClass('ui-menuStrip-item-disabled')) {

											item
													.addClass('ui-menuStrip-item-disabled');

											formGenerator_saveForm(
													$('[name="formGenerator_editForm"]'),
													function() {
														item
																.removeClass('ui-menuStrip-item-disabled');
													});
										}
									});

				});

function formGenerator_refreshForm(data) {

	$('ul.modFormGenerator-protected-pages').html('');

	$.each(data['pages'], function(i, v) {

		formGenerator_createPage(v);

	});

}

function formGenerator_refreshControl(control, data) {

	var text = [];

	if (data.label != null)
		text.push('<i><b>' + data.label + '</b></i>');

	if (data.type != null)
		text.push(FORM_GENERATOR_LANG['control']['title']['type'] + ': <i>'
				+ data.type + '</i>');

	control.children('.modFormGenerator-protected-control-title').html(
			text.join(' - '));

	control.data('data', data);

}

function formGenerator_createPage(data) {

	var pages = $('ul.modFormGenerator-protected-pages');

	if (data == null)
		data = {};

	var page = $('<li />', {
		page : (pages.children('li').length + 1)
	});

	var title = $('<div />', {
		class : 'modFormGenerator-protected-page-title',
		text : 'Seite ' + (pages.children('li').length + 1)
	});
	var actions = $(
			'<div />',
			{
				class : 'modFormGenerator-protected-page-actions',
				html : ''
						+ ''
						+ '<a actionType="create" href="#" rel="dialog" title="'
						+ FORM_GENERATOR_LANG['page']['actions']['create']
						+ '"><div class="modFormGenerator-protected-page-actions-icon"><div class="modFormGenerator-protected-page-actions-create-control"></div></div></a>'
						+ '<a actionType="move" href="#" title="'
						+ FORM_GENERATOR_LANG['page']['actions']['move']
						+ '"><div class="modFormGenerator-protected-page-actions-icon"><div class="modFormGenerator-protected-page-actions-move"></div></div></a>'
						+ '<a actionType="delete" href="#" title="'
						+ FORM_GENERATOR_LANG['page']['actions']['delete']
						+ '"><div class="modFormGenerator-protected-page-actions-icon"><div class="modFormGenerator-protected-page-actions-delete"></div></div></a>'
						+ '<div class="floatClear"></div>' + ''
			});

	var floatClear = $('<div />', {
		class : 'floatClear'
	});

	var item = $('<div />');
	item.append(title);
	item.append(actions);
	item.append(floatClear);

	var list = $('<ul />', {
		class : 'modFormGenerator-protected-controls'
	});
	page.append($('<div />').append(item).append(list));

	$.each(data, function(i, v) {

		formGenerator_createControl(v, list);

	});

	formGenerator_preapareControlSortable(list);

	$(page.find('a[actionType="create"]')[0]).click(function() {

		formGenerator_controlEditWindow(list);

	});

	$(page.find('a[actionType="delete"]')[0]).click(function() {

		formGenerator_deletePage(page.attr('page'));

	});

	pages.append(page);

}

function formGenerator_createControl(data, list) {

	var items = list;

	text = [];
	if (data.label != null)
		text.push('<i><b>' + data.label + '</b></i>');

	if (data.type != null)
		text.push(FORM_GENERATOR_LANG['control']['title']['type'] + ': <i>'
				+ data.type + '</i>');

	var title = $('<div />', {
		class : 'modFormGenerator-protected-control-title',
		html : text.join(' - ')
	});
	var actions = $(
			'<div />',
			{
				class : 'modFormGenerator-protected-control-actions',
				html : ''
						+ ''
						+ '<a actionType="move" href="#" title="'
						+ FORM_GENERATOR_LANG['control']['actions']['move']
						+ '"><div class="modFormGenerator-protected-control-actions-icon"><div class="modFormGenerator-protected-control-actions-move"></div></div></a>'
						+ '<a dialogType="editControl" href="#" rel="dialog" title="'
						+ FORM_GENERATOR_LANG['control']['actions']['edit']
						+ '"><div class="modFormGenerator-protected-control-actions-icon"><div class="modFormGenerator-protected-control-actions-edit"></div></div></a>'
						+ '<a actionType="delete" href="#" title="'
						+ FORM_GENERATOR_LANG['control']['actions']['delete']
						+ '"><div class="modFormGenerator-protected-control-actions-icon"><div class="modFormGenerator-protected-control-actions-delete"></div></div></a>'
						+ '<div class="floatClear"></div>' + ''
			});
	var floatClear = $('<div />', {
		class : 'floatClear'
	});

	var item = $('<li />', {
		controlType : data.type
	});
	item.append(title);
	item.append(actions);
	item.append(floatClear);

	item.data("data", data);

	// ##########################################
	// ##########################################

	$(item.find('a[dialogType="editControl"]')[0]).click(
			function() {

				formGenerator_controlEditWindow($(this).parents(
						'li[controlType]').data('data'), $(this));
			});

	$(item.find('a[actionType="delete"]')[0]).click(function() {

		formGenerator_deleteControl($(this).parents('li[controlType]'));
	});
	items.append(item);

}

function formGenerator_deletePage(index) {

	page = $('[page="' + index + '"]');
	page.find('li[controlType]').each(function(i, v) {

		formGenerator_deleteControl(v);

	});
	page.fadeOut('slow', function() {

		page.remove();

	});

}
function formGenerator_deleteControl(control) {

	control = $(control);

	control.fadeOut('slow', function() {

		control.remove();

	});

}

function formGenerator_controlEditWindow(data, link) {

	var list = null;
	if ($(data).hasClass('modFormGenerator-protected-controls'))
		list = $(data);

	if (data == null || list != null)
		data = {};

	$
			.mbox(
					{

						key : 'modFormGenerator_controlEdit',
						dialogType : 'saveAbort',
						title : FORM_GENERATOR_LANG['control']['actions']['edit'],
						closeAble : false,
						resizeAble : true,
						style : {
							width : '500px',
							height : '400px'
						},
						request : {
							url : FORM_GENERATOR_URL,
							data : $.extend(true, {
								action : 'editControl'
							}, data)
						},

						events : {

							dialogResult : {

								save : function() {

									var mbox = $
											.mbox('modFormGenerator_controlEdit');
									var form = mbox.control
											.find('form[name="editForm"]');

									var data = {

										type : $(
												form
														.find('[name="typeSelect"]'))
												.val(),
										required : $(
												form
														.find('[name="requiredFieldCheckBox"]:checked'))
												.val(),
										label : $(
												form.find('[name="labelText"]'))
												.val(),
										rows : $(
												form
														.find('[name="rowAmountNumber"]'))
												.val(),

										infoText : {
											text : $(
													form
															.find('[name="infoText"]'))
													.val()
										},
										selected : $(
												form
														.find('[name="selectedCheckBox"]:checked'))
												.val(),
										multiple : $(
												form
														.find('[name="multipleCheckBox"]:checked'))
												.val(),
										name : $(form.find('[name="nameText"]'))
												.val()

									};

									if (data.type == 'select') {

										vals = [];

										$.each(form.find('[name="valueText"]')
												.val().split('\n'), function(i,
												v) {

											val = [];
											if (v.split('|').length > 1) {
												v = v.split('|');

												if (v.length > 3) {

													val = {

														'label' : v[1],
														'value' : v[2],
														'description' : v[3]
													};

													if (v[0] == FORM_GENERATOR_CONTROL_OPTION_SELECT)
														val['selected'] = true;

												} else
													val = {

														'label' : v[0],
														'value' : v[1],
														'description' : v[2]
													};

											} else
												val = {
													'label' : v
												};
											
											vals.push(val);

										});

										data.value = vals;
									
									} else {

										data.value = $(
												form.find('[name="valueText"]'))
												.val();

									}

									if (link != null) {

										formGenerator_refreshControl(link
												.parents('li[controlType]'),
												data);

									} else if (list != null) {

										formGenerator_createControl(data, list);

									}

									mbox.close();

								},
								abort : function() {
								}
							}
						}

					}).show();

}

function formGenerator_preaparePageSortable(item) {

	$(item)
			.sortable(
					{
						opacity : 0.6,
						disabled : false,
						handle : '.modFormGenerator-protected-page-actions a[actionType="move"]',
						cursor : 'move',
						placeholder : 'modFormGenerator-protected-page-placeholder',
						cancel : ".modFormGenerator-protected-page-disabled",
						dropOnEmpty : false,
						start : function(event, ui) {

						},
						over : function(event, ui) {
						},
						stop : function(event, ui) {
						},
						update : function(event, ui) {
							/*
							 * var item = $(ui.item);
							 * 
							 * var id, type, parentID, parentType; if
							 * ($(item.parents('li')[0]).hasClass(
							 * 'ui-pageManager-positions-item')) { // Position
							 * parentID = $(item.parents('li')[0]).attr(
							 * 'positionID'); parentType = 'position'; } else { //
							 * Link parentID = $(item.parents('li')[0]).attr(
							 * 'linkID'); parentType = 'link'; }
							 * 
							 * if
							 * (item.hasClass('ui-pageManager-positions-item')) {
							 * 
							 * id = item.attr('positionID'); type = 'position'; }
							 * else {
							 * 
							 * id = item.attr('linkID'); type = 'link'; }
							 * 
							 * $.post(UI_PAGEMANAGER_URL, { 'action' : 'move',
							 * 'id' : id, 'type' : type, 'parentID' : parentID,
							 * 'parentType' : parentType, 'sortList' :
							 * $(this).sortable('toArray') }, function(data) {
							 * 
							 * });//
							 * 
							 * ui_pageManager_PreapareList(item
							 * .parent('ul.ui-pageManager-items')); if
							 * (ui.sender != null)
							 * ui_pageManager_PreapareList(ui.sender);
							 */
						}

					});

}

function formGenerator_preapareControlSortable(item) {

	$(item)
			.sortable(
					{
						opacity : 0.6,
						disabled : false,
						handle : '.modFormGenerator-protected-control-actions a[actionType="move"]',
						cursor : 'move',
						placeholder : 'modFormGenerator-protected-control-placeholder',
						cancel : ".modFormGenerator-protected-control-disabled",
						dropOnEmpty : false,
						start : function(event, ui) {

						},
						over : function(event, ui) {
						},
						stop : function(event, ui) {
						},
						update : function(event, ui) {
						
						}

					});

}

function formGenerator_saveForm(form, complete) {

	var pages = [];

	$.each(form.find('.modFormGenerator-protected-pages').children('li'),
			function(i, v) {

				var controls = [];
				$.each($(v).find('li'), function(i, v) {

					controls.push($(v).data('data'));

				});

				pages.push(controls);

			});

	var data = {

		id : $(form.find('[name="idText"]')).val(),
		name : $(form.find('[name="nameText"]')).val(),
		sendType : $(form.find('[name="sendTypeSelect"]')).val(),
		sendValue : $(form.find('[name="sendValueText"]')).val(),
		pages : pages
	};
	
	if (tinyMCE.get('completeDialogText'))
		data.completeDialog = tinyMCE.get('completeDialogText').getContent();
	else
		data.completeDialog = $(form.find('[name="completeDialogText"]')).val();

	switch (data.sendType) {
		case 'email' :
			data.sendValue = data.sendValue.split('\n');
			break;
	}

	var lastID = data.id;
	$.post(FORM_GENERATOR_URL, {
		'action' : 'saveForm',
		data : data
	}, function(data) {

		if (lastID != data.id) {

			location = PAGE['rootPath'] + 'protected/page/formGenerator-edit-'
					+ data.id + '.html';

		} else {
			if (complete != null)
				complete();
			formGenerator_refreshForm(data);
		}

	}, 'JSON');

}
