/*
		Class: bt_ttnewspdf
*/
bt_ttnewspdf = function () {

	var config;
	var el;

	function initSettings() {
		config = new Hash ({
			site_host: 'http://schau-hin.info/',
			swfupload_file_size_limit: "10 MB",
			swfupload_file_types_description : "Nur Bilder",
			swfupload_button_text:
				'<span class="upload_text">Logo hochladen</span>',
			swfupload_button_text_style:
				'.upload_text { font-size: 12; color: #ffffff; font-family:"Trebuchet MS";}',
			logoarea_width: 458,
			logoarea_height: 70,
			highlight_color: 'rgb(250, 221, 130)',
			highlight_color_default: '#FFFFFF',
			inlineEdit_savingText:
				'<img src="http://schau-hin.info/typo3conf/ext/bt_ttnewspdf/pi1/template/loading.gif" />&nbsp;Wird gespeichert...',
			inlineEdit_clickToEditText: 'Klicken zum Bearbeiten',
			inlineEdit_highlightcolor: '#FADD82',
			inlineEdit_highlightendcolor: '#DBEBF1',
			inlineEdit_okText: 'Speichern',
			inlineEdit_cancelText: 'Abbruch',
			typeNum: '',
			pageId: ''
		});
			//TODO: id = { content:['tx_btttnewspdf_pi1-content', true] },

		el = {
			content     : $('tx_btttnewspdf_pi1-content'),
			closingText : $('tx_btttnewspdf_pi1-closingText'),
			dataProgress: $('tx_btttnewspdf_pi1-dataProgress'),
			defaultLogo : $('tx_btttnewspdf_pi1-defaultLogo'),
			filter      : $('tx_btttnewspdf_pi1-filter'),
			filterText	: $('tx_btttnewspdf_pi1-filterText'),
			head        : $('tx_btttnewspdf_pi1-head'),
			headEditor  : $('tx_btttnewspdf_pi1-headEditor'),
			helpContent : $('tx_btttnewspdf_pi1-helpContent'),
			//helpToggle  : $('tx_btttnewspdf_pi1-helpToggle'),
			image       : $('tx_btttnewspdf_pi1-image'),
			imageItem   : $('tx_btttnewspdf_pi1-imageItem'),
			noflash     : $('tx_btttnewspdf_pi1-noflash'),
			pdfButton   : $('tx_btttnewspdf_pi1-pdfButton'),
			pdfProgress : $('tx_btttnewspdf_pi1-pdfProgress'),
			progress	: $('tx_btttnewspdf_pi1-progress'),
			subhead     : $('tx_btttnewspdf_pi1-subhead'),
			step1Tip    : $('tx_btttnewspdf_pi1-step1Tip'),
			step1tooltip: $('tx_btttnewspdf_pi1-step1tooltip'),
			step1       : $('tx_btttnewspdf_pi1-step1'),
			step2Tip    : $('tx_btttnewspdf_pi1-step2Tip'),
			step2tooltip: $('tx_btttnewspdf_pi1-step2tooltip'),
			step2       : $('tx_btttnewspdf_pi1-step2'),
			step3Tip    : $('tx_btttnewspdf_pi1-step3Tip'),
			step3tooltip: $('tx_btttnewspdf_pi1-step3tooltip'),
			step3       : $('tx_btttnewspdf_pi1-step3'),
			step4       : $('tx_btttnewspdf_pi1-step4'),
			step4content: $('tx_btttnewspdf_pi1-step4Content'),
			step4Tip    : $('tx_btttnewspdf_pi1-step4Tip'),
			step4tooltip: $('tx_btttnewspdf_pi1-step4tooltip'),
			overlay     : $('tx_btttnewspdf_pi1-overlay'),
			help        : $('tx_btttnewspdf_pi1-help'),
			helpClose   : $('tx_btttnewspdf_pi1-helpClose'),
			defaultPdf  : $('tx_btttnewspdf_pi1-defaultPdf')
		};
	}

	/*
			Function: initSWFUpload

			Inits the SWF image uploader with all handlers, is used e.g. to make the uploaded image draggable
	*/
	function initSWFUpload(){
		new SWFUpload({
			upload_url : config.get('site_host') + 'index.php?id=' + config.get('pageId') ,
			post_params : {
				'tx_btttnewspdf_pi1[action]' : 'uploadImage',
				'type' :  config.get('typeNum')},
			flash_url : config.get('site_host') + "typo3conf/ext/bt_ttnewspdf/lib/swfupload.swf",
			use_query_string: false,
			file_size_limit: config.get('swfupload_file_size_limit'),
			file_types: "*.jpg; *.jpeg; *.gif; *.png; *.bmp",
			file_types_description :
				config.get('swfupload_file_types_description'),
			file_upload_limit: 0,
			file_queue_limit: 1,
			button_placeholder_id : "tx_btttnewspdf_pi1-submit" ,
			button_width: "102",
			button_height: "26",
			button_text: config.get('swfupload_button_text'),
			button_image_url:
				config.get('site_host') + "typo3conf/ext/bt_ttnewspdf/pi1/template/button_bg.jpg",
			button_text_style: config.get('swfupload_button_text_style'),
			button_text_left_padding: 9,
			button_text_top_padding: 2,
			debug: false,
			file_dialog_complete_handler: function () {
					this.startUpload();
			},
			upload_start_handler: function () {
				if ($('tx_btttnewspdf_pi1-movableImage')) {
					$('tx_btttnewspdf_pi1-movableImage').fade();
				}
				el.progress.appear();
			},
			upload_success_handler: function(File, serverData) {
				el.imageItem.update(serverData);

				new Draggable('tx_btttnewspdf_pi1-movableImage', {
					snap: function(x, y) {
						return[
							(x < (config.get('logoarea_width')-$('tx_btttnewspdf_pi1-movableImage').getWidth()))
							? (x > 0 ? x : 0 ) : (config.get('logoarea_width')-$('tx_btttnewspdf_pi1-movableImage').getWidth()),
							(y < (config.get('logoarea_height')-$('tx_btttnewspdf_pi1-movableImage').getHeight()))
							? (y > 0 ? y : 0) : (config.get('logoarea_height')-$('tx_btttnewspdf_pi1-movableImage').getHeight()) ];
					}
				});
			},
			upload_complete_handler : function() {
				el.progress.toggle();
			},
			swfupload_load_failed_handler: function() {
				el.noflash.show();
			}
		});
	}

	/*
			Function: updateArticles

			Updates the shown articles with a given categorie and filter text via AJAX request.

			Parameters:

				cat - Category from which the articles should be shown
				filter - Text filter
	*/
	function updateArticles(cat, filter) {

		if (el.content.empty()) {
			this.aIds = ''
		} else {
			this.aIds = Sortable.serialize('tx_btttnewspdf_pi1-content', {tag:'div', name:'aIds'})
		}

		new Ajax.Updater('tx_btttnewspdf_pi1-data', config.get('site_host') + 'index.php?id=' + config.get('pageId'), {
			method: 'post',
			parameters: {
				'tx_btttnewspdf_pi1[category]': cat,
				'tx_btttnewspdf_pi1[filterText]': filter,
				'tx_btttnewspdf_pi1[aIds]': aIds,
				'tx_btttnewspdf_pi1[action]': 'getNewsItems',
				'type': config.get('typeNum')
			},
			onCreate: function () {el.dataProgress.toggle()},
			onComplete: function () {
				el.dataProgress.toggle();
				Sortable.create('tx_btttnewspdf_pi1-data', {
					containment: ['tx_btttnewspdf_pi1-data', 'tx_btttnewspdf_pi1-content'],
					dropOnEmpty: true,
					tag:'div',
					constraint:''
				});

				Sortable.create('tx_btttnewspdf_pi1-content', {
					containment: ['tx_btttnewspdf_pi1-content', 'tx_btttnewspdf_pi1-data'],
					dropOnEmpty: true,
					tag:'div',
					constraint:''
				});
			}
		});
	}

	/*
			Function: initObservers

			Inits all needed observers.
	*/
	function initObservers() {


		el.image.morph('background: ' + config.get('highlight_color'));

		el.filter.observe('change', function() {
			updateArticles(el.filter.getValue(), '');
			el.filterText.value = '';
		});

		el.filterText.observe('keyup', function() {
			updateArticles(
				el.filter.getValue(),
				el.filterText.getValue());
		});

		el.headEditor.observe('change', function() {
			el.head.update(el.headEditor.innerHTML);
		});

		el.pdfButton.observe('click', function() {

			var articles = Sortable.serialize('tx_btttnewspdf_pi1-content', {tag:'div', name:'articles'});

			var imgInfo = '';
			if (!el.imageItem.empty()) {
				imgInfo =
					//$('tx_btttnewspdf_pi1-movableImage').src+','+
					$('tx_btttnewspdf_pi1-pdfImage').value+','+
					$('tx_btttnewspdf_pi1-movableImage').positionedOffset()+','+
					$('tx_btttnewspdf_pi1-movableImage').getWidth()+','+
					$('tx_btttnewspdf_pi1-movableImage').getHeight();
			}

			var headText = el.head.innerHTML;
			var subheadText = el.subhead.innerHTML;
			var closingText = el.closingText.innerHTML;

			new Ajax.Updater('tx_btttnewspdf_pi1-pdfStatus', config.get('site_host') + 'index.php?eID=tx_btttnewspdf_pi1', {
			  method: 'post',
			  parameters: {
			  	'tx_btttnewspdf_pi1[articles]': articles,
			  	'tx_btttnewspdf_pi1[imgInfo]': imgInfo,
			  	'tx_btttnewspdf_pi1[headText]': headText,
			  	'tx_btttnewspdf_pi1[subheadText]': subheadText,
			  	'tx_btttnewspdf_pi1[closingText]': closingText
			  },
			  onCreate: function() { el.pdfProgress.toggle() },
				onSuccess: function() { el.pdfProgress.toggle() }
			});

		});

		el.defaultLogo.observe('click', function() {

			el.imageItem.update(
				'<img id="tx_btttnewspdf_pi1-movableImage" src="' + config.get('site_host')  +
					'typo3conf/ext/bt_ttnewspdf/pi1/template/sh_logo_small.jpg" /><input type="hidden" id="tx_btttnewspdf_pi1-pdfImage" value="' +
					config.get('site_host')  + 'typo3conf/ext/bt_ttnewspdf/pi1/template/sh_logo.jpg" />');
			new Draggable('tx_btttnewspdf_pi1-movableImage', {
				snap: function(x, y) {
						//via el
					return[
						(x < (config.get('logoarea_width')-$('tx_btttnewspdf_pi1-movableImage').getWidth()))
						? (x > 0 ? x : 0 ) : (config.get('logoarea_width')-$('tx_btttnewspdf_pi1-movableImage').getWidth()),
						(y < (config.get('logoarea_height')-$('tx_btttnewspdf_pi1-movableImage').getHeight()))
						? (y > 0 ? y : 0) : (config.get('logoarea_height')-$('tx_btttnewspdf_pi1-movableImage').getHeight()) ];
				}
			});
		});

		el.step4.observe('click', function() {
			el.step4content.toggle();

			if(el.step4content.visible()) {
				el.step4.firstDescendant().src = 'typo3conf/ext/bt_ttnewspdf/pi1/template/button_up.jpg';
			} else {
				el.step4.firstDescendant().src = 'typo3conf/ext/bt_ttnewspdf/pi1/template/button_down.jpg';
			}

			if (el.step4.hasClassName('active')) {
				el.step4.removeClassName('active')
			} else {
				el.step4.addClassName('active');
			}
		});

		/*el.helpToggle.observe('click', function() {
			el.helpContent.toggle();
			if (el.helpContent.visible()) {
				el.helpToggle.innerHTML = 'Einf&uuml;hrungstext ausblenden';
			} else {
				el.helpToggle.innerHTML = 'Einf&uuml;hrungstext einblenden';
			}
		});*/

		el.helpClose.observe('click', function() {
			el.help.hide();
			el.overlay.hide();
			$('tx_btttnewspdf_pi1-step1Content').toggle();
		});

		el.defaultPdf.observe('click', function() {
			new Ajax.Updater('tx_btttnewspdf_pi1-content', config.get('site_host') + 'index.php?id=' + config.get('pageId'), {
				method: 'post',
				parameters: {
					'tx_btttnewspdf_pi1[category]': '134',
					'tx_btttnewspdf_pi1[action]': 'getNewsItems',
					'type': config.get('typeNum')
				},
				onComplete: function () {
					Sortable.create('tx_btttnewspdf_pi1-data', {
						containment: ['tx_btttnewspdf_pi1-data', 'tx_btttnewspdf_pi1-content'],
						dropOnEmpty: true,
						tag:'div',
						constraint:''
					});

					Sortable.create('tx_btttnewspdf_pi1-content', {
						containment: ['tx_btttnewspdf_pi1-content', 'tx_btttnewspdf_pi1-data'],
						dropOnEmpty: true,
						tag:'div',
						constraint:''
					});
				}
			});
		});

		createTooltip(el.step1Tip, el.step1tooltip, el.step1);
		createTooltip(el.step2Tip, el.step2tooltip, el.step2);
		createTooltip(el.step3Tip, el.step3tooltip, el.step3);
		createTooltip(el.step4Tip, el.step4tooltip, el.step4);
	}

	function createTooltip(tipIcon, tip, reference) {
		tipIcon.observe('mouseover', function() {
			var position = reference.positionedOffset().toString();
			position = position.split(",");
			tip.setStyle({
				top: (position[1]-2) + 'px',
				left: (position[0]-333) + 'px'
			});
			tip.toggle();
		});
		tipIcon.observe('mouseout', function() {
			tip.toggle();
		});
	}


	/*
			Function: inlineEdit

			Makes the element to the given id editable inline.

			Parameters:

				editable - Id of the element which should be editable
				target - Id of element which should be updated once the editing of editable is finished
	*/
	function inlineEdit(editable, target) {
		Object.extend(Ajax.InPlaceEditor.prototype, {
  		getText: function() {
  			return this.element.innerHTML
					.replace(/<br>/gi, '\r')
					.replace(/<br\/>/gi, '\r')
					.replace(/<br \/>/gi, '\r')
					.unescapeHTML();

			}
		});

		new Ajax.InPlaceEditor(editable , config.get('site_host') + 'index.php?id=' + config.get('pageId'), {
			rows: 2,
			formClassName: 'tx_btttnewspdf_pi1-inplaceeditor-form',
			cancelControl: 'button',
			okText: config.get('inlineEdit_okText'),
			cancelText: config.get('inlineEdit_cancelText'),
			savingText: config.get('inlineEdit_savingText'),
			clickToEditText: config.get('inlineEdit_clickToEditText'),
			callback: function(form, value) { return 'tx_btttnewspdf_pi1[action]=inlineEdit&type='+
				config.get('typeNum') + '&tx_btttnewspdf_pi1[newContent]=' + encodeURIComponent(value)},
			onComplete: function() {
				Element.update(target, $(editable).innerHTML);

				$(target+'Default').hide();
			},
			highlightcolor: config.get('inlineEdit_highlightcolor'),
			highlightendcolor: config.get('inlineEdit_highlightendcolor')
		});
	}

	/*
			Function: initMenuPoint

			Inits one menu point, with observers and logic.

			Parameters:
				contentArea - Element which should be highlighted on click
				menu - Element that will be clickable to open the menu point
				content - Element that will be toggled visible once menu is clicked
	*/
	function initMenuItem(contentArea, menu, content) {
		menu.observe('click', function() {
			if (contentArea.hasClassName('highlight')) {
				contentArea.removeClassName('highlight')
				contentArea.morph('background: ' + config.get('highlight_color_default'))
				menu.removeClassName('active');
			} else {
				contentArea.addClassName('highlight')
				contentArea.morph('background: ' + config.get('highlight_color'));
				menu.addClassName('active');
			}
			content.toggle();
			if(content.visible()) {
				menu.firstDescendant().src = 'typo3conf/ext/bt_ttnewspdf/pi1/template/button_up.jpg';
			} else {
				menu.firstDescendant().src = 'typo3conf/ext/bt_ttnewspdf/pi1/template/button_down.jpg';
			}
		});
	}

	return {
		/*
				Function: init

				Inits the class bt_ttnewspdf, is called after object creation.
				Merges default configuration with given definitions through the parameter.

				Parameters:

					arg - Array that will be merged with var config
		*/
		init : function(arg) {
			initSettings();
			config = config.merge($H(arg));
				//TODO: via config
			config.set('typeNum', $('tx_btttnewspdf_pi1-typeNum').value);
			config.set('pageId', $('tx_btttnewspdf_pi1-pageId').value);

			//elefant.test : $('tx_btttnewspdf_pi1-content');

			initSWFUpload();
			updateArticles($('tx_btttnewspdf_pi1-filter').getValue(), $('tx_btttnewspdf_pi1-filterText').getValue());
				//TODO: via el
			inlineEdit('tx_btttnewspdf_pi1-headEditor', 'tx_btttnewspdf_pi1-head');
			inlineEdit('tx_btttnewspdf_pi1-subheadEditor', 'tx_btttnewspdf_pi1-subhead');
			initObservers();
			//	TODO: via el
			initMenuItem($('tx_btttnewspdf_pi1-image'), $('tx_btttnewspdf_pi1-step1'), $('tx_btttnewspdf_pi1-step1Content'));
			initMenuItem($('tx_btttnewspdf_pi1-editableContent'), $('tx_btttnewspdf_pi1-step2'), $('tx_btttnewspdf_pi1-step2Content'));
			initMenuItem($('tx_btttnewspdf_pi1-content'), $('tx_btttnewspdf_pi1-step3'), $('tx_btttnewspdf_pi1-step3Content'));
				//TODO: via el ggf schlefe
			$('tx_btttnewspdf_pi1-step1Content').toggle();
			$('tx_btttnewspdf_pi1-step2Content').toggle();
			$('tx_btttnewspdf_pi1-step3Content').toggle();
			$('tx_btttnewspdf_pi1-step4Content').toggle();
		}
	}
}();

document.observe("dom:loaded", function() {
	bt_ttnewspdf.init({});
})
