/**
 * Opinions controller JavaScripts
 *
 * @author Andrzej Korniów <andrzej.korniow@esky.pl>
 * @author Tomasz Głaz
 * @author Dariusz Pobożniak
 * @author Piotr Musiałek <piotr.musialek@esky.pl>
 */

var opinion_date_html;

function bindOpinionsActions(containerToBind) {
	$('#' + containerToBind + ' a').click(function() {
		var elementId = $(this).attr('id');

		$("div[id$='opinion-buttons-container']").addClass("hidden");
		$("#" + elementId + "-container").removeClass("hidden");

		$(this).addClass('hidden');

		$("#" + elementId + "-container a#button-active").click(function(){
			$("#" + elementId + "-container").addClass("hidden");
			$("#" + elementId).removeClass("hidden");
		});

		return false;
	});
}

function goTo(hash) {
	var $target = $(hash);
	if ($target.length) {
		var targetOffset = $target.offset().top;
		$('html,body').animate({scrollTop: targetOffset}, 1000);
	}
}

function opinionErrorPlacement (error, element) {
	if (element.context.type=="radio") {
		element.parent().parent().children(".error-container").append(error);
	} else {
		element.parent().children(".error-container").append(error);
	}
}
function opinionHighlight (element) {
	$(element).addClass("invalid-form-element");
	if ($(element).attr("type")=="radio") {
		$("input[name="+$(element).attr("name")+"]").addClass("invalid-form-element");
		$(element).parent().parent().children("label").addClass('error');
	} else {
		$(element).parent().children("label").addClass('error');
	}
}
function opinionUnhighlight (element) {
	if ($(element).attr("id")!="fyear") {
		$(element).removeClass("invalid-form-element");
		if ($(element).attr("type")=="radio") {
			$("input[name="+$(element).attr("name")+"]").removeClass("invalid-form-element");
			$(element).parent().parent().children("label").removeClass('error');
		} else {
			$(element).parent().children("label").removeClass('error');
		}
	}
}
function opinionOnfocusout (el) {
	$(el).parents("form").validate().element($(el));
}
function opinionShowErrors () {
	this.defaultShowErrors();
	$(".error-label-bottom").children("a").attr("href", '#'+$(".invalid-form-element:first").attr("id"));
	if ($(".error").length) {
		var frame = $('html');
		var scroll_top = frame.attr("scrollTop");
		if (scroll_top == 0) {
			var frame = $('body');
			var scroll_top = frame.attr("scrollTop");
		}
		if ($(".errors-label").hasClass("hidden")) {
			$(".errors-label").removeClass("hidden");
			frame.animate({scrollTop: scroll_top+89}, 1);
		}
	} else {
		var frame = $('html');
		var scroll_top = frame.attr("scrollTop");
		if (scroll_top == 0) {
			var frame = $('body');
			var scroll_top = frame.attr("scrollTop");
		}
		if (!$(".errors-label").hasClass("hidden")) {
			$(".errors-label").addClass('hidden');
			frame.animate({scrollTop: scroll_top-89}, 1);
		}
	}
}

$(document).ready(function() {
	if ($('#opinions').length > 0) {
		var lastCode = null;
		var xhrOpinions = null;
		var getLimit = 10;
		var maxOpinions = 100;
		var opinionsShowed = $('.opinion-list li').length;

		var $filters = $('#opinions-filters');
		var $loader = $('.loader');

		// Scroll to the header near first error
		$(".opinionscrollto").click(function(e) {
			e.preventDefault();
			var $target = e.target.hash;
			if ($target.length) {
				var targetOffset = $($target).parents("fieldset").children("h4").offset().top;
				$('html,body').animate({scrollTop: targetOffset}, 1000);
			}
		});

		// Check if number of showed opinions on the start page is less than limit (there's no need to show 'more opinions' button)
		if (opinionsShowed < getLimit) {
			$('#show-more-opinions').hide();
		}

		// Blocks checkboxes filters tab when searching for opinion
		function blockFilters() {
			$filters.children('input').attr('disabled', 'disabled');
			$filters.children('span').css('display', 'block');
			$loader.fadeIn(200);
			$('input[name="airlines-kind"]').attr('disabled', 'disabled');
		}

		// Unblocks checkboxes filters tab when searching is over
		function unblockFilters() {
			$filters.children('input').removeAttr('disabled');
			$filters.children('span').css('display', 'none');
			$loader.fadeOut(200);
			$('#show-more-opinions').addClass('btn1');
			$('#show-more-opinions').removeClass('btn4');
			$('input[name="airlines-kind"]').removeAttr('disabled');
		}

		// Gets opinions list with AJAX
		function getOpinions(offset, limit, clear, type, location, code) {
			if (xhrOpinions != null) {
				xhrOpinions.abort();
				xhrOpinions = null;
			}

			var filters = new Array();

			// Get all filters that are checked
			$('#opinions-filters input:checked').each(function() {
				filters.push($(this).val());
			});

			blockFilters();

			xhrOpinions = $.post('/opinie/ajaxmoreopinions', {
				location: location,
				opinionsType: $('#opinions-type').val(),
				code: code,
				filters: filters,
				offset: offset,
				limit: limit
			}, function(data) {
				var itemsLength = 0;

				$('#show-all-opinions').addClass('hidden');
				$('.more-loader').addClass('hidden');

				// If list contains other type of opinions than items already showed on page, clear the list
				if (clear || $('#no-opinions-found').length) {
					$('.opinion-list').html('');
					$('#show-all-opinions').addClass('hidden');
				}

				if (data.length > 0) {
					$('.opinion-list').append(data);
					$('.opinion-list .ajaxed-opinion').css('display', 'none');
					$('.opinion-list .ajaxed-opinion').show();
					opinionsShowed += getLimit;
					itemsLength = $('.ajaxed-opinion').length;
					$('.ajaxed-opinion').removeClass('ajaxed-opinion');
				}

				if ($('#no-opinions-found').length) {
					$('#opinions-header').html('');
				} else if ($('.opinion-search-header').length) {
					$('#opinions-header').html($('.opinion-search-header:eq(0)').html());
				}

				unblockFilters();
				// If there are no more opinions to show, or maxOpinions is reached, hide button
				if (opinionsShowed >= maxOpinions || itemsLength < getLimit || $('#no-more-opinions').length > 0 || $('#is-last-opinions').length > 0) {
					$('#show-more-opinions').hide();
					$('#show-all-opinions').removeClass('hidden');
				} else {
					$('#show-more-opinions').show();
				}

				if ($('.photo').length) {
					bindPopupGallery();
				}

				if ($('.show-map').length) {
					bindAirportsScripts();
				}
			});
		}

		function markUsefullComment(id) {
			$.post('/opinie/ajaxmarkusefull', { id: id });
		}

		$('#search-opinions').click(function (e) {
			e.preventDefault();

			if ($(this).parent().find('.ac_input').hasClass('placeholder')) {
				lastCode = null;
			} else {
				lastCode = $(this).parent().find('.ac_input').val();
			}
			getOpinions(0, getLimit, true, null, null, lastCode);
		});

		// Filters tab, radio buttons change - airlines filters
		$('input[name="airlines-kind"]').change(function() {
			opinionsShowed = 0;
			lastCode = $(this).val();
			getOpinions(0, getLimit, true, 'Airline', 'World', lastCode);
		});

		// Filters tab, checkboxes change - hotel filters
		$filters.children('input').change(function () {
			opinionsShowed = 0;
			getOpinions(0, getLimit, true, $('#opinions-type').val(), null, lastCode);
		});

		// Button to get more opinions
		$('#show-more-opinions').click(function(e) {
			e.preventDefault();
			if ($(this).hasClass('btn1')) {
				$(this).removeClass('btn1');
				$(this).addClass('btn4');
				$('.more-loader').removeClass('hidden');
				opinionsShowed = $('.opinion-list li').length;
				getOpinions(opinionsShowed, getLimit, false, $(this).attr('rel'), null, lastCode);
			}
		});

		// toggle ranking section on top
		function rankingToggle() {
			var $btn = $('#btn-toprankings'),
				$ranking = $('#rlist');
			if (!$btn.hasClass('btn-active')) {
				$ranking.hide().removeClass('hidden');
			}
			$btn.click(function () {
				$ranking.stop(true, true).slideToggle(500);
				$(this).stop(true, true).toggleClass('btn-active');
			});
		};

		rankingToggle();

		$('#rlist a').click(function (e) {
			if ($(this).parent().parent().hasClass('not-jsed')) {
				return true;
			}

			e.preventDefault();

			opinionsShowed = 0;
			$('.ac_input').focus();
			$('.ac_input').val($(this).text());
			$('#search-opinions').click();
		});

		$('#link-more-airports').click(function () {
			$('#o-airportlist').slideDown('500');
			return false;
		});

		// add new opinion
		var $newOpWrp = $('#set-hotelmark');

		if ($newOpWrp.length) {
			var tipText = 'Kliknij, aby ocenić',
				isChecked = false,
				$thermometer = $('#thermometer'),
				$opTextarea = $('#ftext'),
				$tempText = $('#temperature-text'),
				$tempTextEls = $tempText.find('li');
			$tempText.find('li:eq(0)').css('display', 'block');
			$newOpWrp.find('.marks').each(function (i,j) {
				var $this = $(this),
					$tip = $('<span class="tip hide"></span>');
				if (i === 0) {
					$tip.text(tipText).removeClass('hide');
				}
				$tip.appendTo($this);
				$this.find('label').each(function () {
					$(this).data('title', $(this).attr('title')).removeAttr('title');
				});
			});

			$newOpWrp.find('input').change(function () {
				$newOpWrp.parent().validate().element($(this));
				var $this = $(this);
				tipText = '.';
				$this.next('label').removeClass().addClass('checked').siblings('label').removeClass();
				$this.prevAll('label').addClass('prev-checked');
				isChecked = true;
			});

			if ($('.photo-with-gal').length) {
				bindPopupGallery();
			}

			$("input[name=frecom]").change(function() {
				$newOpWrp.parent().validate().element($(this));
			});

			$('.marks', $newOpWrp).find('label').hover(function () {
				var $this = $(this);
				$('.tip').addClass('hide').text('.');
				$this.siblings('.tip').text($this.data('title')).removeClass('hide');
			}, function () {
				$('.tip').addClass('hide').text('.');
				if (!isChecked) {
					$($newOpWrp.find('.marks')[0]).find('.tip').text(tipText).removeClass('hide');
				}
			});

			function opinionsTextarea() {
				var charLength = $opTextarea.val().length;
				if (charLength >= 50) {
					$tempTextEls.css('display', 'none');
					$tempText.find('li:eq(1)').css('display', 'block');
					$thermometer.removeClass().addClass('level-1');
				} else {
					$tempTextEls.css('display', 'none');
					$tempText.find('li:eq(0)').css('display', 'block');
					$thermometer.removeClass().addClass('level-0');
				}
				if (charLength >= 250) {
					$tempTextEls.css('display', 'none');
					$tempText.find('li:eq(2)').css('display', 'block');
					$thermometer.removeClass().addClass('level-2');
				}
				if (charLength >= 500) {
					$tempTextEls.css('display', 'none');
					$tempText.find('li:eq(3)').css('display', 'block');
					$thermometer.removeClass().addClass('level-3');
				}
			}

			function opinionsYear() {
				var selected = $("#fmonth").val();
				$("#fmonth").html(opinion_date_html);
				$("#fmonth").children("option").eq(selected).attr("selected", "selected");
				if ($(this).val() == $("#fyear").children("option:last").attr("value")) {
					var current_date=new Date();
					current_date = current_date.getMonth();
					$("#fmonth").children("option").each(function(i) {
						if (i > current_date+1) {
							$(this).remove();
						}
					});
				}
			}

			$opTextarea.change(opinionsTextarea);
			$opTextarea.keyup(opinionsTextarea);
			opinionsTextarea();

			opinion_date_html = $("#fmonth").html();
			$("#fyear").change(opinionsYear);
			if ($("#fyear").val() == $("#fyear").children("option:last").attr("value")) {
				var current_date=new Date();
				current_date = current_date.getMonth();
				$("#fmonth").children("option").each(function(i) {
					if (i > current_date+1) {
						$(this).remove();
					}
				});
			}
			$newOpWrp.parent("form").find("button").click(function(e) {
				if (!$(this).parents("form").valid()) {
					goTo("h2");
				}
			});

			$("#airport-opinion").validate({
				errorElement: 'span',
				errorClass: "error-message",
				event: 'keyup',
				rules: {
					fyear: { required: true },
					fmonth: { required: true },
					fo_localisation: { required: true },
					fo_signs: { required: true },
					fo_service: { required: true },
					fo_parking: { required: false },
					fo_hotels: { required: false },
					fo_checkin: { required: true },
					fo_comfort: { required: true },
					ftitle: { required: true, maxlength: 255 },
					ftext: { required: true, maxlength: 5000 },
					frecom: { required: true },
					fname: { required: true, maxlength: 32 },
					fcity: { required: true, maxlength: 32 }
				},
				messages: {
					fyear: { required: "Podaj miesiąc pobytu" },
					fmonth: { required: "Podaj miesiąc pobytu" },
					fo_localisation: { required: "Oceń lokalizację" },
					fo_signs: { required: "Oceń oznakowanie" },
					fo_service: { required: "Oceń usługi" },
					fo_parking: { required: "Oceń parking" },
					fo_hotels: { required: "Oceń bazę hotelową" },
					fo_checkin: { required: "Oceń odprawę" },
					fo_comfort: { required: "Oceń komfort poczekalni" },
					ftitle: { required: "Podaj tytuł opinii", maxlength: "Tytuł nie może zawierać więcej niż 255 znaków" },
					ftext: { required: "Podaj treść opinii", maxlength: "Treść opinii nie może zawierać więcej niż 5000 znaków" },
					frecom: { required: "Wybierz rekomendację" },
					fname: { required: "Podaj imię i nazwisko", maxlength: "Imię i nazwisko nie może zawierać więcej niż 32 znaki" },
					fcity: { required: "Podaj miasto", maxlength: "Miasto nie może zawierać więcej niż 32 znaki" }
				},
				errorPlacement: opinionErrorPlacement,
				highlight: opinionHighlight,
				unhighlight: opinionUnhighlight,
				onfocusout: opinionOnfocusout,
				focusInvalid: false,
				showErrors: opinionShowErrors
			});

			$("#airline-opinion").validate({
				errorElement: 'span',
				errorClass: "error-message",
				event: 'keyup',
				rules: {
					fyear: { required: true },
					fmonth: { required: true },
					fo_punctuality: { required: true },
					fo_personel: { required: true },
					fo_connections: { required: true },
					fo_price: { required: true },
					fo_comfort: { required: true },
					fo_baggage: { required: false },
					fo_food: { required: false },
					ftitle: { required: true, maxlength: 255 },
					ftext: { required: true, maxlength: 5000 },
					frecom: { required: true },
					fname: { required: true, maxlength: 32 },
					fcity: { required: true, maxlength: 32 }
				},
				messages: {
					fyear: { required: "Podaj miesiąc pobytu" },
					fmonth: { required: "Podaj miesiąc pobytu" },
					fo_punctuality: { required: "Oceń punktualność" },
					fo_personel: { required: "Oceń personel" },
					fo_connections: { required: "Oceń połączenia" },
					fo_price: { required: "Oceń cenę biletu" },
					fo_comfort: { required: "Oceń komfort" },
					fo_baggage: { required: "Oceń bagaż" },
					fo_food: { required: "Oceń posiłki" },
					ftitle: { required: "Podaj tytuł opinii", maxlength: "Tytuł nie może zawierać więcej niż 255 znaków" },
					ftext: { required: "Podaj treść opinii", maxlength: "Treść opinii nie może zawierać więcej niż 5000 znaków" },
					frecom: { required: "Wybierz rekomendację" },
					fname: { required: "Podaj imię i nazwisko", maxlength: "Imię i nazwisko nie może zawierać więcej niż 32 znaki" },
					fcity: { required: "Podaj miasto", maxlength: "Miasto nie może zawierać więcej niż 32 znaki" }
				},
				errorPlacement: opinionErrorPlacement,
				highlight: opinionHighlight,
				unhighlight: opinionUnhighlight,
				onfocusout: opinionOnfocusout,
				focusInvalid: false,
				showErrors: opinionShowErrors
			});

			$("#hotel-opinion").validate({
				errorElement: 'span',
				errorClass: "error-message",
				event: 'keyup',
				rules: {
					fyear: { required: true },
					fmonth: { required: true },
					ftripkind: { required: true },
					fo_localization: { required: true },
					fo_food: { required: false },
					fo_personel: { required: true },
					fo_comfort: { required: true },
					fo_equipment: { required: true },
					fo_cleanliness: { required: true },
					ftitle: { required: true, maxlength: 255 },
					ftext: { required: true, maxlength: 5000 },
					frecom: { required: true },
					fname: { required: true, maxlength: 255 },
					fcity: { required: true, maxlength: 255 }
				},
				messages: {
					fyear: { required: "Podaj miesiąc pobytu" },
					fmonth: { required: "Podaj miesiąc pobytu" },
					ftripkind: { required: "Wybierz rodzaj podróży" },
					fo_localization: { required: "Oceń lokalizację" },
					fo_food: { required: "Oceń wyżywienie" },
					fo_personel: { required: "Oceń personel" },
					fo_comfort: { required: "Oceń komfort" },
					fo_equipment: { required: "Oceń wyposażenie" },
					fo_cleanliness: { required: "Oceń czystość" },
					ftitle: { required: "Podaj tytuł opinii", maxlength: "Tytuł nie może zawierać więcej niż 255 znaków" },
					ftext: { required: "Podaj treść opinii", maxlength: "Treść opinii nie może zawierać więcej niż 5000 znaków" },
					frecom: { required: "Wybierz rekomendację" },
					fname: { required: "Podaj imię i nazwisko", maxlength: "Imię i nazwisko nie może zawierać więcej niż 255 znaków" },
					fcity: { required: "Podaj miasto", maxlength: "Miasto nie może zawierać więcej niż 255 znaków" }
				},
				errorPlacement: opinionErrorPlacement,
				highlight: opinionHighlight,
				unhighlight: opinionUnhighlight,
				onfocusout: opinionOnfocusout,
				focusInvalid: false,
				showErrors: opinionShowErrors
			});
		}
		$("#airline-list-form").children("ul").children("li").children("input").change(function() {
			$("#airline-list-form").attr("action",$("#airline-list-form").children("ul").children("li").children("input:checked").val());
			$("#airline-list-form").children("ul").children("li").children("input").attr("checked", false);
			$(this).attr("checked", "checked");
		});
	}

	$(".opinion-thanks").children("#o-airportlist").submit(function(e) {
		e.preventDefault();
		if ($(".opinion-thanks").children("#o-airportlist").find("input[name=airport]:checked").val()) {
			window.location=$(".opinion-thanks").children("#o-airportlist").find("input[name=airport]:checked").val();
		}
	});

	//EskyDefault.scrollTo();
});
