/**
 * Promotions scripts
 *
 * @author Andrzej Korniów
 * @author Dariusz Pobożniak
 */
$(document).ready(function() {
	//if ($('#promotions').length > 0) {
		// promotions week calendar
		$('#day-sel').change(function() {
			window.location.href = $(this).val();
		});

		function getTextExtractor() {
			return (function() {
				var patternLetters = /[ĄĆĘŁŃÓŚŹŻąćęłńóśźż]/g,
					patternDateDmy = /^(?:\D+)?(\d{1,2})\.(\d{1,2})\.(\d{2,4})$/,
					lookupLetters = {
						'Ą':'A','Ć':'C:','Ę':'E','Ł':'L','Ń':'N','Ó':'O','Ś':'S','Ź':'Z','Ż':'Z',
						'ą':'a','ć':'c:','ę':'e','ł':'l','ń':'n','ó':'o','ś':'s','ź':'z','ż':'z'
					},
					letterTranslator = function(match) {
						return lookupLetters[match] || match;
					};

				return function(node) {
					var $node = $(node),
						text = $.trim($node.text()),
						date = text.match(patternDateDmy);
					if (date) {
						return [date[3], date[2], date[1]].join("-");
					}
					else {
						if ($node.hasClass('t-price')) {
							return (parseFloat($node.find('strong').text()).toFixed(2));
						} else {
							return text.replace(patternLetters, letterTranslator);
						}
					}
				};
			})();
		}

		/**
		 * Make entire promotions tables rows clickable and attach sort plugin
		 *
		 * @author Dariusz Pobożniak
		 */
		if ($('.dest-select').length > 0) {
			$('.dest-select').delegate('tr', 'click', function (e) {
				e.preventDefault();

				if ($(this).find('a').length > 0) {
					window.location.href = $(this).find('a:first').attr('href');
				}
			});

			$('.dest-select').find('table').tablesorter({
				sortList: [[1,0]],
				headers: {
					1: { sorter: 'digit' },
					2: { sorter: false }
				},
				textExtraction: getTextExtractor()
			});


			// scrolling table body
			if ($(".pick-place").length) {
				$(".pick-place").after('<div class="table-clone"></div>');
				$('.dest-select').children("table").clone().appendTo(".table-clone");
				$('.dest-select').children("table").children("tbody").hide();
				$('.dest-select').children(".table-clone").children("table").addClass("scrollable").children("thead").hide();
				$('.dest-select').children("table").bind("sortEnd",function() {
					$('.dest-select').children(".table-clone").children("table").children("tbody").remove();
					$('.dest-select').children("table").children("tbody").clone().appendTo(".dest-select > .table-clone > table");
					$('.dest-select').children(".table-clone").children("table").children("tbody").show();
				});
			}


		}

		/**
		 * Dropdown selects on promotions main page
		 *
		 * @author Andrzej Korniów
		 * @author Dariusz Pobożniak
		 */
		function dropdown() {
			var $promoQsf = $('.promo-qsf'),
				$dropDown = $('.dropdown-select'),
				$dropDownParent = $dropDown.parents('.nl'),
				openClass = 'open-dropdown',
				$selectedItem = null,
				selectBuffer = '',
				lastKeyTimeout;

			/**
			 * Cleans the characters buffer
			 *
			 * @author Andrzej Korniów
			 */
			function cleanKeyBuffer() {
				selectBuffer = '';
				clearTimeout(lastKeyTimeout);
			}

			/**
			 * Highlight select list item using a class
			 *
			 * @author Andrzej Korniów
			 */
			function highlightItem() {
				if ($selectedItem.length) {
					$('.open-dropdown .highlighted-item').removeClass('highlighted-item');
					$selectedItem.addClass('highlighted-item');
				}
			}

			/**
			 * Customselect keyboard navigation
			 *
			 * @author Andrzej Korniów
			 */
			function manageKeyboard() {
				var arrowDetected = false;

				$(document).keydown(function(e) {
					if ($('.open-dropdown').length) {
						e.stopPropagation();

						// Timeout for last entered character cleaning the characters buffer
						clearTimeout(lastKeyTimeout);
						lastKeyTimeout = setTimeout(cleanKeyBuffer, 2000);

						// Letters or space
						if (e.which >= 65 && e.which <= 90 || e.which == 32) {
							if (arrowDetected) {
								arrowDetected = false;
								cleanKeyBuffer();
							}

							selectBuffer = selectBuffer + String.fromCharCode(e.which);
							e.preventDefault();
						}
						// Backspace
						else if (e.which == 8) {
							if (selectBuffer.length > 0) {
								selectBuffer = selectBuffer.substring(0, selectBuffer.length - 1);
							}

							e.preventDefault();
						}
						// Arrows
						else if (e.which == 38 || e.which == 40) {
							arrowDetected = true;

							if ($selectedItem == null) {
								selectBuffer = $('.open-dropdown .dropdown li:first').attr('rel');
							}
							// Arrow up
							else if (e.which == 38) {
								if (!$selectedItem.prev('li').length) {
									return false;
								}

								selectBuffer = $selectedItem.prev('li').attr('rel');
							}
							// Arrow down
							else if (e.which == 40) {
								if (!$selectedItem.next('li').length) {
									return false;
								}

								selectBuffer = $selectedItem.next('li').attr('rel');
							}

							e.preventDefault();
						}
						// Enter
						else if (e.which == 13) {
							$selectedItem.click();
							e.preventDefault();
						}

						// Escape all regexp characters
						selectBuffer = selectBuffer.replace(new RegExp("([{}\(\)\^$&.\*\?\/\+\|\[\\\\]|\]|\-)", "g"), "\\$1");

						var regexp = new RegExp('^' + selectBuffer + '([\(\)A-Za-z\s]*)', 'i');

						// Search for matching item on the select list
						$('.open-dropdown .dropdown li').each(function () {
							if (regexp.test($(this).attr('rel'))) {
								$('.open-dropdown .dropdown').scrollTop(0);
								$('.open-dropdown .dropdown').scrollTop($(this).position().top);
								$selectedItem = $(this);
								return false;
							}
						});

						highlightItem();
					}
				});
			}

			/**
			 * Prevents choosing equal airports in QSF by hiding list item in clicked dropdown
			 *
			 * @param $div clicked dropdown list
			 */
			function hideSameDropdownItem($div) {
				$div.find('.hidden-item').show().removeClass('hidden-item');
				$div.find('.dropdown-autocomplete').find('[rel=' + $dropDown.not($div).children('span.title').text() + ']').has('span[rev=Airport]').addClass('hidden-item').hide();
			}

			if ($dropDown.length) {
				var xhr = [],
					$title = $dropDown.find('.title'),
					$input = $dropDown.next('input'),
					countrycode = null;

				$promoQsf.find('select').customSelect();

				function dropdownAjax($div, $li, type, code, inputText, destination) {
					if (xhr[destination] != null) {
						xhr[destination].abort();
					}

					xhr[destination] = $.ajax({
						url: $div.find('.dropdown').attr('rel'),
						type: 'POST',
						dataType: 'html',
						data: {
							inputText: typeof inputText != 'undefined' ? $.trim(inputText) : '',
							type: type,
							code: code,
							destination: destination
						},
						beforeSend: function() {
							$li.addClass('loading');
						},
						success: function(result) {
							$li.removeClass('loading');

							cleanKeyBuffer();
							$selectedItem = null;

							if (result.length) {
								$div.html(result);
							}

							hideSameDropdownItem($div);
						},
						error: function() {
							$div.removeClass('loading');
						}
					});
				}

				// close dropdown list after clicking outside
				$(document).click(function(event) {
				    if ($(event.target).parents('.dropdown-select').length < 1) {
				        if($('.dropdown-select').parents('.nl').hasClass(openClass)) {
				            $('.dropdown-select').parents('.nl').removeClass(openClass);
				        }
				    }
				});

				$dropDown.find('ul.dropdown-autocomplete li').live('hover', function (e) {
					$selectedItem = $(this);
					highlightItem();
				});

				$dropDown.find('ul.dropdown-autocomplete li, .return').live('click', function(e) {
					var $li = $(this),
						$div = $li.closest('.dropdown-select'),
						destination = $li.closest('.dropdown').attr('rev'),
						chosenItem = $li.attr('rel'),
						itemType = $li.find('span.dropdown-info').attr('rev'),
						code = null,
						nextType = null;

					if (!$li.hasClass('any-country')) {
						if (!$li.hasClass('return')) {
							nextType = $li.attr('rev');
							code = $li.find('span.dropdown-info').attr('rel');

							if (itemType == 'Country') {
								countrycode = code;
							}
						} else {
							if ($li.attr('rev') == 'City') {
								code = countrycode;
							} else {
								code = $div.parent().find('input.code').val();
							}

							nextType = $li.attr('rev');
						}

						if (itemType != 'City' && itemType != 'Airport' && !$li.hasClass('any-location')) {
							dropdownAjax($div, $li, nextType, code, chosenItem, destination);
						} else {
							$dropDownParent.removeClass(openClass);
						}

						$div.next().focus().val(chosenItem);
						$div.find('.title').text(chosenItem);

						$div.parent().find('input.type').val(itemType);
						$div.parent().find('input.code').val($li.find('.dropdown-info').attr('rel'));
					} else {
						$dropDownParent.removeClass(openClass);
						$div.parent().find('input.type').val('');
						$div.parent().find('input.code').val('');
					}
				});

				$input.each(function() {
					$(this).bind('change', function (e) {
						var text = e.target.value;
						text.match(/\((\S{3})\)/);
						var code = RegExp.$1;

						$(this).prev('.dropdown-select').find('.title').text(text);
						$(this).parent().find('.type').val('City');
						$(this).parent().find('.code').val(code);
					});
				});

				$title.live('click', function () {
					if ($(this).closest('.nl').hasClass(openClass)) {
						$(this).closest('.nl').removeClass(openClass);
					} else {
						$dropDownParent.removeClass(openClass);
						hideSameDropdownItem($(this).parent());
						$(this).closest('.nl').addClass(openClass);
					}
				});
			}

			manageKeyboard();
		}

		dropdown();
	//}
});
