﻿(function ($, undefined) {

	var $document = $(document);

	var globalTabIndex = 0;

	//class
	function MultiTopImageSwitcher(e, mti, options) {

		var AnimationSteps = 65;
		var AnimationWidth = 31;

		var self = this;
		var $list = $('<ol class="multi-top-image-switcher"></ol>');
		var current = 0;
		var $items;
		var $addLi;

		function setBackground($elements, step) {
			$elements.css({
				'backgroundImage': 'url(' + options.switcherImage + ')',
				'backgroundPosition': -(step * AnimationWidth) + 'px 0px',
				'backgroundRepeat': 'none'
			});
		}

		function updateAnimation(currentStep) {
			var $item = $items.eq(current);
			var $div = $item.find('div');

			setBackground($div, currentStep);

			if (currentStep == AnimationSteps) {
				$div.hide();
			}
			else if ($div.is(':hidden')) {
				if (options.editMode) {
					$div.show();
				}
				else {
					$div.fadeIn('fast');
				}
			}
		}

		function update() {

			$list.empty();

			for (var i = 1; i <= options.items.length; i++) {
				$list.append('<li><div></div><span>' + i + '</span></li>');
			}

			if (options.editMode) {
				$list.append('<li class="multi-top-image-add"><span style="color:white;">+</span></li>');
			}

			$items = $('li', $list[0]);
			$addLi = $('li.multi-top-image-add', $list[0]);

			$items.find('div, span').css({
				'position': 'absolute',
				'top': '0px',
				'left': '0px',
				'width': '100%',
				'height': '100%'
			});

			var $divs = $items.find('div');
			$divs.css('display', 'none');
			setBackground($items, AnimationSteps - 1);
			setBackground($divs, 0);
		}

		update();

		if ((options.items.length <= 1) && (!options.editMode)) {
			return;
		}

		$list.appendTo(e);
		$list.bind({
			mouseenter: function () { mti.stop(); },
			mouseleave: function () { mti.start(); }
		});

		$items.live('click', function (event) {
			var $target = $(event.currentTarget);
			var index = $target.index();

			self.stop();

			if (!options.items.length || !options.items[current].isEditingBounds) {
				if ($target.is('.multi-top-image-add')) {
					mti.addItem();
				}
				else {
					mti.next(index);
				}
			}

			event.stopPropagation();
		});

		self.options = options;
		self.update = update;

		self.start = function (duration) {
			var currentStep = 0;
			var $span = $items.eq(current).find('span');

			function step() {
				updateAnimation(currentStep);
				currentStep++

				if (currentStep > AnimationSteps) {
					self.stop();
					$span.fadeIn('fast', function () {
						mti.next();
					});
				}
				else {
					self.timer = window.setTimeout(step, (duration / AnimationSteps));
				}
			}

			self.stop();
			$span.fadeOut('fast', step);
		};

		self.stop = function () {
			if (self.timer) {
				window.clearTimeout(self.timer);
				self.timer = null;
			}
		};

		self.show = function () {
			$list.fadeIn();
		}

		self.hide = function () {
			$list.fadeOut();
		}

		self.current = function (newCurrent) {
			if (newCurrent !== undefined) {
				var $old = $items.eq(current);
				$old.removeClass('multi-top-image-current');
				$old.find('div').hide();
				$old.find('span').show();

				current = newCurrent;

				var $new = $items.eq(current);
				$new.addClass('multi-top-image-current');
				updateAnimation(0);
			}

			return current;
		};

		self.item = function (index) {
			return $items.eq(index);
		};
	}

	//class
	function MultiTopImageItemEditor($editor) {

		return {
			bind: function ($element, item) {

				function setTinyMceText($textarea, text) {
					var id = $textarea.attr('id')
					$textarea.val(text);
					tinyMCE.execCommand('mceAddControl', false, id);
				}

				//lk
				function resetItemFlag(item) {
					item.isEditingBounds = false;
					item.toBeDeleted = false;
					item.moveLeft = false;
					item.moveRight = false;
				}

				var $visualSelector = $editor.find('.visual-selector');
				var visualSelector = SkodaVisualSelector($visualSelector);

				var $textarea = $editor.find('textarea');
				var $texteditor = $editor.find('.topimage-editor-text');
				var $duration = $editor.find('.topimage-duration');

				var $html = $('<div>' + item.imageHtml + '</div>');
				var $anchor = $html.find('a');

				$visualSelector.bind('hasFlashChanged hasSilverlightChanged', function () {
					if (visualSelector.hasFlash() || visualSelector.hasSilverlight()) {
						$texteditor.slideUp();
					}
					else {
						$texteditor.slideDown();
					}
				});

				$editor.find('a.change-bounds-link').click(function () {
					//lk
					resetItemFlag(item);
					item.isEditingBounds = true;
					$.popupEditor.hide();
				});

				$editor.find('a.delete-link').click(function () {
					//lk
					resetItemFlag(item);
					item.toBeDeleted = true;
					$.popupEditor.hide();
				});

				$editor.find('.topimage-popup-close').click(function () {
					//lk
					resetItemFlag(item);
					$.popupEditor.hide();
				});

				$editor.find('.topimage-popup-move-left').click(function () {
					//lk
					resetItemFlag(item);
					item.moveLeft = true;
					$.popupEditor.hide();
				});

				$editor.find('.topimage-popup-move-right').click(function () {
					//lk
					resetItemFlag(item);
					item.moveRight = true;
					$.popupEditor.hide();
				});

				$duration.val(item.duration);
				visualSelector.bindElements($anchor, $html);

				if (visualSelector.hasFlash() || visualSelector.hasSilverlight()) {
					$texteditor.hide();
				}
				else {
					$texteditor.show();
					setTinyMceText($textarea, item.text);
				}
			},
			update: function (item) {
				function relativize(url) {
					var origin = (window.location.protocol + '//' + window.location.host + '/').toUpperCase();

					url = url || '';

					if (url.toUpperCase().indexOf(origin) == 0) {
						url = '/' + url.substr(origin.length);
					}

					return url;
				}
				var visualSelector = SkodaVisualSelector($editor.find('.visual-selector'));
				var visual = visualSelector.makeVisual();
				var $textarea = $editor.find('textarea');
				var $duration = $editor.find('.topimage-duration');

				visual.css({ width: '940px', height: '492px' });
				visual.find('object').css({ width: '940px', height: '492px' });

				item.imageHtml = visual ? visual.wrap('<div/>').parent().html() : '';
				item.duration = $duration.val();

				var editorId = $textarea.attr('id');
				var editor = tinymce.EditorManager.get(editorId);

				if (editor) {
					var $body = $(editor.contentDocument.body);

					$body.find('a').each(function () {
						var $this = $(this);
						var url = $this.attr('href');
						$this.attr('href', relativize(url));
					});

					if (visual.find('object').length) {
						item.text = '';
					}
					else {
						item.text = $body[0].innerHTML;
					}

					tinyMCE.execCommand('mceFocus', false, editorId);
					tinyMCE.execCommand('mceRemoveControl', false, editorId);
				}
			}
		};
	}

	//class
	function multiTopImageBoundsEditor($boundsEditor, $element, mti, item) {
		var $text = $element.find('.mtText');
		var $x = $boundsEditor.find('.topimage-bounds-x')
		var $y = $boundsEditor.find('.topimage-bounds-y')
		var $w = $boundsEditor.find('.topimage-bounds-w')
		var $h = $boundsEditor.find('.topimage-bounds-h')

		$x.blur(updatePosition);
		$y.blur(updatePosition);
		$w.blur(updatePosition);
		$h.blur(updatePosition);

		$text.addClass('mtText-changing-bounds');
		mti.hideSwitcher();

		function updateEditor() {
			$x.val($text.position().left);
			$y.val($text.position().top);
			$w.val($text.width());
			$h.val($text.height());
		}

		function updatePosition() {
			$text.resizable('destroy');
			$text.draggable('destroy');

			$text.width($w.val());
			$text.height($h.val());
			$text.css({
				left: $x.val() + 'px',
				top: $y.val() + 'px'
			});

			beginDrag();
		}

		function beginDrag() {
			$text.draggable({ drag: updateEditor });
			$text.resizable({ resize: updateEditor, handles: 'all' });
		}

		updateEditor();
		beginDrag();

		var elementOffset = $element.offset();

		$boundsEditor.appendTo(document.body);
		$boundsEditor.show();
		$boundsEditor.css('z-index', 10000);
		$boundsEditor.offset({
			top: elementOffset.top - $boundsEditor.height(),
			left: elementOffset.left
		});

		$boundsEditor.find('.topimage-bounds-ok').one('click', function (event) {

			event.stopPropagation();

			$text.resizable('destroy');
			$text.draggable('destroy');
			$text.removeClass('mtText-changing-bounds');

			updatePosition();
			$boundsEditor.fadeOut('fast');

			item.width = $w.val();
			item.height = $h.val();
			item.left = $x.val();
			item.top = $y.val();

			mti.showSwitcher();
			mti.save();
			mti.edit();
		});
	}

	//class
	function MultiTopImage(e, options) {

		options.items = options.items || [];

		var current = 0;
		var self = this;
		var timer = null;
		var parent = e.parent();

		var $itemEditor = $(options.itemEditor);
		var $boundsEditor = $(options.boundsEditor);
		var $hiddenField = $(options.hiddenField);

		var itemEditor = new MultiTopImageItemEditor($itemEditor);

		var elements = $.map(options.items, format);

		for (var i in elements) {
			parent.append(elements[i]);
		}

		var switcher = new MultiTopImageSwitcher(parent, self, options);
		if (switcher.current != null)
			switcher.current(0);

		function onAddItem() {

			//dk
			$.popupEditor.hide();

			var element = $('<div><a href=""><img alt="" /></a><div class="mtText"></div></div>');
			parent.append(element);
			elements.push(element);
			options.items.push({
				duration: 5000,
				imageHtml: '<a href=""><img alt="" /></a>',
				text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla lobortis, diam eget posuere eleifend, velit magna luctus eros, sit amet elementum enim purus nec mauris. Phasellus pretium diam nec ipsum.',
				width: 100,
				height: 50,
				left: 10,
				top: 10
			});
			switcher.update();
			next(elements.length - 1);
			//lk
			switcher.current(current);
		}

		function edit() {

			var index = current;

			//lk
			var iitem = options.items[current];
			iitem.isEditingBounds = false;
			iitem.toBeDeleted = false;
			iitem.moveLeft = false;
			iitem.moveRight = false;

			$.popupEditor.hide();

			switcher.item(index).popupEditor($itemEditor, {
				onBeforeShown: function () {
					itemEditor.bind(elements[index], options.items[index]);
				},
				onBeforeHidden: function () {
					itemEditor.update(options.items[index]);
					var newHtml = format(options.items[index], index);
					elements[index].replaceWith(newHtml);
					elements[index] = newHtml;
				},
				onAfterHidden: function () {
					var item = options.items[index];

					function moveLeft(array, index) {
						var newindex = index - 1;

						if (newindex == -1) {
							newindex = array.length - 1;
						}

						var item = array[index];
						array[index] = array[newindex];
						array[newindex] = item;
						return newindex;
					}

					function moveRight(array, index) {
						var newindex = index + 1;

						if (newindex == array.length) {
							newindex = 0;
						}

						var item = array[index];
						array[index] = array[newindex];
						array[newindex] = item;
						return newindex;
					}

					if (item.isEditingBounds) {
						delete item.isEditingBounds;
						self.save();
						multiTopImageBoundsEditor($boundsEditor, elements[index], self, item);
					}
					else if (item.moveLeft) {
						delete item.moveLeft;

						moveLeft(elements, index);
						current = moveLeft(options.items, index);

						switcher.update();
						switcher.current(current);

						self.save();
						setTimeout(edit, 1);
					}
					else if (item.moveRight) {
						delete item.moveRight;

						moveRight(elements, index);
						current = moveRight(options.items, index);

						switcher.update();
						switcher.current(current);

						self.save();
						setTimeout(edit, 1);
					}
					else if (item.toBeDeleted) {
						delete item.toBeDeleted;

						options.items.splice(index, 1);

						elements[index].remove();
						elements.splice(index, 1);

						switcher.options.itemCount--;
						switcher.update();

						//lk
						var currentFlag = 0;
						if (current > 0) {
							current--;
							currentFlag = 1;
						}

						self.save();
						//lk
						nextOnDelete(currentFlag);
					}

					else {
						self.save();
					}
				}
			});
		}

		function format(item, index) {
			var result = $('<div>' + item.imageHtml + '<div class="mtText">' + item.text + '</div></div>');

			result.css({
				position: 'absolute',
				visibility: (index == current) ? '' : 'hidden',
				top: 0,
				left: 0
			});

			if (options.editMode) {
				result.find('a').click(function (event) {
					event.preventDefault();
				});
			}

			result.find('.mtText').css({
				width: item.width + 'px',
				heigth: item.height + 'px',
				left: item.left + 'px',
				top: item.top + 'px',
				display: (/\<object/ig).test(item.imageHtml) ? 'none' : 'block'
			});

			return result;
		}

		//lk
		function nextOnDelete(currentFlag) {
			var speed = 'fast';
			if (elements[current] != null) {
				elements[current].fadeTo(speed, 0.0, function () {
					elements[current].css({
						'visibility': 'hidden',
						'width': '1px',
						'height': '1px'
					});

					if (currentFlag > 0) {
						var indexCheck = (current + 1) % elements.length;
						if ((indexCheck % elements.length) > 0) {
							current = indexCheck;
						}
						else {
							current = elements.length - 1;
						}
					}
					elements[current].css({
						'visibility': 'visible',
						'width': '',
						'height': ''
					});

					elements[current].fadeTo(speed, 1.0, function () {
						switcher.current(current);
						//lk -> jachym spatny indexy. Jedine nova metoda editOnDelete s predanim indexu a current ktery se ma mazat.
						edit();
						edit();
					});
				});
			}
			else {
				current = 0;
			}
		}

		function next(index, speed) {
			speed = speed || 'fast';

			if (index === undefined) {
				index = current + 1;
			}

			function callback() {
				if (options.editMode) {
					edit();
				}
				else {
					scheduleNext();
				}
			}

			if (index == current) {
				callback();
				return;
			}

			//lk
			if (elements[current] != null) {
				elements[current].fadeTo(speed, 0.0, function () {
					elements[current].css({
						'visibility': 'hidden',
						'width': '1px',
						'height': '1px'
					});
					current = index % elements.length;

					elements[current].css({
						'visibility': 'visible',
						'width': '',
						'height': ''
					});

					elements[current].fadeTo(speed, 1.0, function () {
						switcher.current(current);
						callback();
					});
				});
			}
			else {
				current = 0;
			}
		}

		function scheduleNext() {
			if (options.editMode || options.items.length < 2) {
				return;
			}

			switcher.start(options.items[current].duration);
		}

		self.start = function () {
			scheduleNext();
		};

		self.stop = function () {
			switcher.stop();
		};

		self.next = function (index) {
			next(index);
		};

		self.addItem = function () {
			onAddItem();
		}

		self.save = function () {
			$hiddenField.val(JSON.stringify(options));
		};

		self.hideSwitcher = function () {
			switcher.hide();
		}

		self.showSwitcher = function () {
			switcher.show();
		}

		self.edit = edit;

		e.remove();
		scheduleNext();
	}

	$.fn.multiTopImage = function () {
		var mti;
		var slice = Array.prototype.slice;

		if (typeof arguments[0] === 'string') {
			mti = this.data('multiTopImage');
			mti[arguments[0]].apply(mti, slice.call(arguments, 1));
		}
		else {
			mti = new MultiTopImage(this, arguments[0]);
			this.data('multiTopImage', mti);
		}

		return this;
	}

})(jQuery);
