$(document).ready(function() {
	if ($('#ebrigady').size() === 0) return;

	var DEBUG_MODE = false;
	var desiredJobs = [];
	var sessionJobCount = (typeof(window['sessJobCount']) != 'undefined') ? sessJobCount : 0;

	//var ajaxLink = 'http://web2.student.local/ebrigady/ajax/';
	var ajaxLink = 'http://www.student.cz/ebrigady/ajax/';

	function addJob(job, noAjax)
	{
		if (noAjax !== true) {
			var ajaxUrl = ajaxLink + '?action=add&change=' + job.ord_line_id;
			if (DEBUG_MODE) console.log('AJAX URL:', ajaxUrl);
			$.getJSON(ajaxUrl);
		}
		desiredJobs[desiredJobs.length] = job.ord_line_id;
	}

	function removeJob(job)
	{
		for (i in desiredJobs) {
			if (desiredJobs[i] == job.ord_line_id) {
				var ajaxUrl = ajaxLink + '?action=remove&change=' + job.ord_line_id;
				if (DEBUG_MODE) console.log('AJAX URL:', ajaxUrl);
				$.getJSON(ajaxUrl);
				desiredJobs.splice(i, 1);
				return;
			}
		}
		
		alert("ERROR - odebiram neexistujici polozku!");
	}

	function adjustDesiredCounter(element, increment)
	{
		var value = parseInt(element.find('span.count').html()) + increment;

		if (value > 0) {
			element.find('span.count').html(value);
			if (element.is(':hidden')) element.show();

			if ($('span#menu-ebrig-count span').size() === 1) {
				$('span#menu-ebrig-count span').text(value);
			}

		} else {
			element.find('span.count').html('0');
			element.hide();

			if ($('span#menu-ebrig-count span').size() === 1) {
				$('span#menu-ebrig-count span').text('');
			}
		}
	}

	function removeJobByRedirect(job)
	{
		window.location.href = window.location.pathname + '?rmjob=' + job.ord_line_id;
	} 


	// Hovery brigadnich boxu (IE fix).
	$('.job-offer').hover(function() {
		if ($(this).hasClass('desired')) {
			$(this).addClass('desired-hard-hover');
		} else if ($(this).hasClass('reserved')) {
			$(this).addClass('reserved-hard-hover');
		} else {
			$(this).addClass('simple-hard-hover');
		}
	}, function() {
		$(this).removeClass('desired-hard-hover reserved-hard-hover simple-hard-hover');
	});


	// Graficke upravy
	// Podbarveni leveho menu.
	/*
	if ($('.leftU .submenu li.logged a:contains(eBrigády)').size() === 1 &&  $('.eb-my-jobs-table').size() === 0) {
		$('.leftU .submenu li.logged a:contains(eBrigády)').css('background-color', '#e38077');
	}
	/*if ($('.eb-my-jobs-table').size() === 1) {
		$('.leftU .submenu li.logged a:contains(Moje brigády)').css('background-color', '#e38077');
	}*/
	/*
	if ($('.leftU h2.o-agenture-student').size() === 1) {
		$('.leftU h2.o-agenture-student').css('color', '#000');
	}
	*/
	// ------


	// Akce POUZE pro krok 1.
	if ($('#ebrigady-step-1').size() > 0) {
		// Inicializujeme pole s ID vybranych brigad.
		$('#week-detail .week .job-offer.desired').each(function() {
			var jobData = eval("(" + $(this).attr('data-job') + ')');
			addJob(jobData, true);
		});

		if (DEBUG_MODE) console.log('Data ze session', desiredJobs);

		// Zobrazime citace u jednotlivych tydnu.
		$('#week-detail .week').each(function() {
			var jobCount = $(this).find('.job-offer.desired').size();

			if (jobCount > 0) {
				adjustDesiredCounter($('#week-overview a[data-week-id="' + $(this).attr('data-week-id') + '"]').parent().find('span.desired'), jobCount);
			}
		});
	}
	// ------


	// Akce POUZE pro krok 2.
	if ($('#eb-step-2-overview').size() > 0) {
		// Inicializujeme pole s ID vybranych brigad.
		$('#eb-step-2-overview td.detail').each(function() {
			var jobData = eval("(" + $(this).attr('data-job') + ')');
			addJob(jobData, true);
		});

		if (DEBUG_MODE) console.log('Data ze session', desiredJobs);
	}

	$('#eb-step-2-overview a.remove-job').click(function(event) {
		event.preventDefault();

		if (!confirm('Opravdu chcete odstranit tuto brigádu ze seznamu?')) return;

		var data = eval("(" + $(this).parent().attr('data-job') + ')');
		removeJobByRedirect(data);
	});
	// ------


	// Akce POUZE pro krok 3.
	if ($('#eb-step-3-your-jobs').size() > 0) {
		var itemCount = $('#eb-step-3-your-jobs ul li').size(), compactShowCount = 3;

		if (itemCount > compactShowCount) { 
			$('#eb-step-3-your-jobs').append('<a href="#" class="more-or-less show-more">Zobrazit vše (' + itemCount + ')</a>');
			$('#eb-step-3-your-jobs ul li').slice(compactShowCount).hide();

			$('#eb-step-3-your-jobs a.more-or-less').click(function(event) {
				event.preventDefault();

				if ($(this).hasClass('show-more')) {
					$(this).removeClass('show-more').addClass('show-less').text('Zobrazit méně');
					$('#eb-step-3-your-jobs ul li').slideDown(200);
				} else {
					$(this).removeClass('show-less').addClass('show-more').text('Zobrazit vše (' + itemCount + ')');
					$('#eb-step-3-your-jobs ul li').slice(compactShowCount).slideUp(200);
				}
			});
		}
	}
	// ------


	// Akce POUZE pro krok 4.
	if ($('#eb-step-4-final-preorder-info').size() > 0) {
		var itemCount = $('#eb-step-4-final-preorder-info ul li').size(), compactShowCount = 3;

		if (itemCount > compactShowCount) { 
			$('#eb-step-4-final-preorder-info ul').after('<a href="#" class="more-or-less show-more">Zobrazit vše (' + itemCount + ')</a>');
			$('#eb-step-4-final-preorder-info ul li').slice(compactShowCount).hide();

			$('#eb-step-4-final-preorder-info a.more-or-less').click(function(event) {
				event.preventDefault();

				if ($(this).hasClass('show-more')) {
					$(this).removeClass('show-more').addClass('show-less').text('Zobrazit méně');
					$('#eb-step-4-final-preorder-info ul li').slideDown(200);
				} else {
					$(this).removeClass('show-less').addClass('show-more').text('Zobrazit vše (' + itemCount + ')');
					$('#eb-step-4-final-preorder-info ul li').slice(compactShowCount).slideUp(200);
				}
			});
		}
	}
	// ------

	// Preklikavani tydnu
	$('#week-overview li a').click(function(event) {
		event.preventDefault();
		if ($(this).hasClass('active')) return;

		var thisWeekId = $(this).attr('data-week-id'),
			activeWeekId = $('#week-overview li a.active').attr('data-week-id');

		$('#week-overview li a.active').removeClass('active');
		$(this).addClass('active');

		$('#week-detail div.week[data-week-id="' + activeWeekId + '"]').hide();
		$('#week-detail div.week[data-week-id="' + thisWeekId + '"]').show();
	});
	// ------


	// Konfirmace pred finalnim pokusem o rezervaci (mezi kroky 4 a 5).
	$('#eb-navig-bottom.navig-step-4 a.finish-order').click(function(event) {
		return confirm('Jste si opravdu jist/á? Rezervace jsou závazné!');
	});
	// ------ 


	// Okno s detailem na kroku 2 a v "Moje brigady".
	$('#eb-step-2-overview a.job-detail, #eb-my-jobs-table a.job-detail').click(function(event) {
		event.preventDefault();

		var data = eval("(" + $(this).parent().attr('data-job') + ')');
		if (DEBUG_MODE) console.log('Data brigady ' + data.ord_line_id, data);

		$.fancybox(
			'<div id="job-detail" class="' + ($(this).hasClass('my-jobs') ? 'reserved' : 'desired') + '"><h2><span>Informace o brigádě</span> ' + data.work_type + '</h2>' +
			'<p><strong>Zaměstnavatel:</strong>' + data.employer_name + '</p>' +
			'<p><strong>Adresa pracoviště:</strong>' + data.delivery_address + '</p>' +
			'<p><strong>Hodinová mzda:</strong>' + (data.salary_hour_rate === null ? '0' : data.salary_hour_rate) + ' Kč</p>' +
			'<p><strong>Pracovní doba:</strong>' + data.shift_string + '</p>' +
			'<p><strong>Popis práce:</strong>' + data.work_type + '</p>' +
			'<p><strong>Doplňující informace:</strong>' + (data.note_public == null ? '<em>Nejsou</em>' : data.note_public) + '</p>' +
			'<div class="navig">' +
			($(this).hasClass('my-jobs') ? '' : '<a href="#" class="remove">Odebrat</a>') + 
			'<a href="#" class="close">Zavřít detail</a></div>' +
			'</div>',
			{
				'padding'			: '10',
				'transitionIn'		: 'none',
				'transitionOut'		: 'none'
			}
		);

		// Odebrani brigady.
		$('#job-detail .navig a.remove').click(function(event){
			event.preventDefault();
			removeJob(data);
			if (DEBUG_MODE) console.log('Po odebrani brigady ' + data.ord_line_id, desiredJobs);
			removeJobByRedirect(data);
			$.fancybox.close();
		});

		// Zavreni okna s detailem.
		$('#job-detail .navig a.close').click(function(event){
			event.preventDefault();
			$.fancybox.close();
		});
	});
	// ------


	// Pridani/odebrani brigady klikem na celou plosku.
	$('.job-offer').not('.unmet-req').click(function(event) {
		var data = eval("(" + $(this).attr('data-job') + ')'),
			weekId = $(this).parents('div.week').first().attr('data-week-id');
		if (DEBUG_MODE) console.log('Data brigady ' + data.ord_line_id, data);

		if ($(this).hasClass('reserved')) {
			// Nedelame nic.

		} else if ($(this).hasClass('desired')) {
			removeJob(data);
			if (DEBUG_MODE) console.log('Po odebrani brigady ' + data.ord_line_id, desiredJobs);
			$(this).removeClass('desired desired-hard-hover').addClass('simple-hard-hover');
			adjustDesiredCounter($('#week-overview a[data-week-id="' + weekId + '"]').parent().find('span.desired'), -1);

		} else {
			addJob(data);
			if (DEBUG_MODE) console.log('Po pridani brigady ' + data.ord_line_id, desiredJobs);
			$(this).removeClass('simple-hard-hover').addClass('desired desired-hard-hover');
			adjustDesiredCounter($('#week-overview a[data-week-id="' + weekId + '"]').parent().find('span.desired'), 1);
		}
	});
	// ------


	// Okno s detailem na kroku 1.
	$('.job-offer a').click(function(event) {
		event.preventDefault();
		event.stopPropagation();

		var data = eval("(" + $(this).parent().attr('data-job') + ')');
		if (DEBUG_MODE) console.log('Data brigady ' + data.ord_line_id, data);

		var buttonsHtml = '<div class="navig">', jobDetailClass = 'reserved', unmetReqHtml = '';
		if ($(this).parent().hasClass('desired')) {
			// Uzivatel ma o tuto brigadu zajem.
			buttonsHtml = buttonsHtml + '<a href="#" class="remove">Odebrat</a>';
			jobDetailClass = 'desired';

		} else if ($(this).parent().hasClass('reserved')) {
			// Nedelame nic.

		} else {
			// Volna (a obsaditelna brigada).
			if (data.unmet_requirements === null) buttonsHtml = buttonsHtml + '<a href="#" class="add">Rezervovat</a>';
			jobDetailClass = 'free';
		}
		buttonsHtml = buttonsHtml + '<a href="#" class="close">Zavřít detail</a></div>';

		if (data.unmet_requirements !== null) {
			unmetReqHtml = '<div class="unmet-req"><strong>Pro obsazení této brigády bohužel nesplňujete tyto požadavky:</strong><ul>';

			for (i in data.unmet_requirements) {
				unmetReqHtml = unmetReqHtml + '<li>' + data.unmet_requirements[i] + '</li>';
			}
			unmetReqHtml = unmetReqHtml +'</ul></div>';
		}

		$.fancybox(
			'<div id="job-detail" class="' + jobDetailClass + '"><h2><span>Informace o brigádě</span> ' + data.work_type + '</h2>' +
			'<p><strong>Zaměstnavatel:</strong>' + data.employer_name + '</p>' +
			'<p><strong>Adresa pracoviště:</strong>' + data.delivery_address + '</p>' +
			'<p><strong>Hodinová mzda:</strong>' + (data.salary_hour_rate === null ? '0' : data.salary_hour_rate) + ' Kč</p>' +
			'<p><strong>Pracovní doba:</strong>' + data.shift_string + '</p>' +
			'<p><strong>Popis práce:</strong>' + data.work_type + '</p>' +
			'<p><strong>Doplňující informace:</strong>' + (data.note_public == null ? '<em>Nejsou</em>' : data.note_public) + '</p>' +
			unmetReqHtml +
			buttonsHtml +
			'</div>',
			{
				'padding'			: '10',
				'transitionIn'		: 'none',
				'transitionOut'		: 'none'
			}
		);

		var weekId = $(this).parents('div.week').first().attr('data-week-id');

		// Pridani brigady.
		$('#job-detail .navig a.add').click(function(event){
			event.preventDefault();
			addJob(data);
			if (DEBUG_MODE) console.log('Po pridani brigady ' + data.ord_line_id, desiredJobs);
			$('.job-offer[data-job-id="' + data.ord_line_id + '"]').addClass('desired');
			adjustDesiredCounter($('#week-overview a[data-week-id="' + weekId + '"]').parent().find('span.desired'), 1);
			$.fancybox.close();
		});

		// Odebrani brigady.
		$('#job-detail .navig a.remove').click(function(event){
			event.preventDefault();
			removeJob(data);
			if (DEBUG_MODE) console.log('Po odebrani brigady ' + data.ord_line_id, desiredJobs);
			$('.job-offer[data-job-id="' + data.ord_line_id + '"]').removeClass('desired');
			adjustDesiredCounter($('#week-overview a[data-week-id="' + weekId + '"]').parent().find('span.desired'), -1);
			$.fancybox.close();
		});

		// Zavreni okna s detailem.
		$('#job-detail .navig a.close').click(function(event){
			event.preventDefault();
			$.fancybox.close();
		});
	});
	// ------


	// Tlaciko obsazeni brigad.
	$('#ebrigady-step-1').submit(function(event) {
		if (desiredJobs.length === 0) {
			event.preventDefault();
			alert('Vyberte si alespoň jednu brigádu.');
			return false;
		}

		// Create JSON string with encoded "desired" jobs. 
		var jsonStr = '['

		for (i in desiredJobs) {
			jsonStr = jsonStr + $('.job-offer[data-job-id="' + desiredJobs[i] + '"]').attr('data-job') + (parseInt(i) + 1 === desiredJobs.length ? ']' : ', ');
		}

		$('#ebrigady-step-1 input[name="json-vessel"]').val(jsonStr);

		return true;
	});
	// ------
});

