// JavaScript Document

var menu = {
	data : null,
	timeout : 1000,
	timeoutVar : null,
	selected : null,
	toggling : false,
	background : {
		'left' : '/images/bk_mn_stadion_li.png' ,
		'right' : '/images/bk_mn_spolka_li.png'
	},
	backgroundExpandable : {
		'left' : '/images/bk_mn_stadion_li_expnd.png' ,
		'right' : '/images/bk_mn_spolka_li_expnd.png'
	},
	run : function () {
		$('#leftwrap #mmenu .sekcje a').click(menu.toggle);
		$('#leftwrap #mmenu ul a').mouseover(menu.expand).mouseout(menu.remover).each(function () {
			var id = $(this).attr('id');
			if (filter(menu.data,function (el) { return (el.parent_id == id) }).length)
				$(this).parent().addClass('expnd');
		});
		menu.selected = ($('#leftwrap #mmenu .right').css('display') == 'none') ? 'left' : 'right';
	},
	toggle : function (e) {
		e.preventDefault();
		if (!menu.toggling)
		{
			menu.toggling = true;
			$('.floatingmenu').remove();
			$('#leftwrap #mmenu ul.'+menu.selected).slideUp(function () {
				$('#leftwrap #mmenu').children().hide();
				menu.selected = (menu.selected == 'left') ? 'right' : 'left';
				$('#leftwrap #mmenu div.'+menu.selected).show();
				$('#leftwrap #mmenu ul.'+menu.selected).slideDown(function () {
					menu.toggling = false;
					$.get('/menu.php',{selected: menu.selected,PHPSESSID:SESSIONID});
				});
			});
		}
	},
	expand : function () {
		clearTimeout(menu.timeoutVar);
		menu.mouseOverMenu = true;
		var object = $(this);
		var expandStack = ($(this).attr('stack')) ? $(this).attr('stack').split(',') : [];
		var offset = object.offset();
		var width = object.parent().width();
		var id = object.attr('id');
		var menuItems = filter(menu.data,function (el) { return (el.parent_id == id) });
		// usuwanie tych menu, ktore nam nie pasuja
		$('.floatingmenu').each(function () { if (!onList(expandStack,$(this).attr('id') ) ) $(this).remove(); });

		if (menuItems.length)
		{
			expandStack.push(id);
			var container = $('<div />')
				.addClass('floatingmenu')
				.attr('id',id)
				.appendTo('body')
				.css({
						'top' : offset.top,
						'left' : offset.left+width+5
					});
			container = $('<ul />').appendTo(container);
			for (i in menuItems)
			{
				var v = menuItems[i];
				var id = v.id;
				var bkg =
					(filter(menu.data,function (el) { return (el.parent == id) }).length > 0)
					?
					'url('+menu.backgroundExpandable[menu.selected]+')'
					:
					'url('+menu.background[menu.selected]+')';
				
				var href = v.link;
				$('<a />')
					.attr('stack',expandStack.join(','))
					.attr('id',v.id)
					.attr('href',href)
					.text(v.tytul)
					.mouseover(menu.expand)
					.mouseout(menu.remover)
					.wrap('<li />')
					.parent()
					.css('backgroundImage',bkg)
					.appendTo(container);
			}
		}
	},
	mouseOverMenu : false,
	_remover : function ()
	{
		if (!menu.mouseOverMenu) 
			$('.floatingmenu').remove();
	},
	remover : function ()
	{
		menu.mouseOverMenu = false;
		menu.timeoutVar = setTimeout('menu._remover()',menu.timeout);
	}
}


var galeria = {
	init : function () {
		$('#galeria a').fancybox();
		$('a.powiekszZdjecie').fancybox();
		
	},
	fadeOut : function () {
		$('<div />')
			.attr('id','galeriaBack')
			.appendTo('body')
			.css('opacity',0.6)
			.click(galeria.fadeIn);
	},
	fadeIn : function () {
		$('#galeriaBack').remove();
	}
}


function filter(arr,fn)
{
	out = [];
	for (i in arr)
		if (fn(arr[i])) out[out.length] = arr[i];
	return out;
}

function onList(arr,el)
{
	for (i in arr)
		if (arr[i] == el) return true;
	return false;
}

function validate(fn,obj)
{
	var text = {pl:'Proszę wypełnić pole oznaczone na czerwono',en:'Please fill in the field marked red'};
	if (fn(obj.val()))
	{
		obj.parent().css({color:'#FF0000'});
		alert(text[lang]);
		obj.focus();
		return false;
	}
	else
	{
		obj.parent().css({color:'inherit'});
		return true;
	}
}


$(document).ready(function () {
	menu.run();
	galeria.init();
	$('#searchbox,#nwslttr').clearText();
	zespol.init();
	searchBox.init();
	newsletter.init();
	$('.printit').click(function (e) { e.preventDefault(); window.print(); });
//						$('#euronews').rssreader('http://www.euro2012-pl.org/rss.xml');
	$('#form1').submit(function (e) {
			e.preventDefault();
			var data = $('#form1').serializeArray();
			if (!validate(function (s) { return s == ''; },$('#form1 input[name=name]'))) return;
			if (!validate(function (s) { return (s.indexOf('@')<1 || s.indexOf('.')<1); },$('#form1 input[name=email]'))) return;
			if (!validate(function (s) { return s == ''; },$('#form1 input[name=subject]'))) return;
			if (!validate(function (s) { return s == ''; },$('#form1 textarea'))) return;
			$.post('/mail.php',data);
			$('#form1 input[type=submit]').attr('disabled','disabled');
			var text = {pl:'Wiadomość została wysłana',en:'Message has been sent'};
			alert('Wiadomość została wysłana.');
	});
	
	$('#friendRecommend').click(friendRecommend.dialog);
	
	$('.pobierzPlik').each(function (i,el) { var l = $(this).attr('href'); $(this).attr('href',l+':download'); });
	
	$('.webcam').click(function (e) { e.preventDefault(); $('#camera a').click(); });
	
});


var searchBox = {
	initVal : null,
	width : 500,
	visible : false,
	closeText : {'pl': 'zamknij','en': 'close'},
	noResults : {'pl': 'Brak wyników','en': 'No results'},
	init : function () {
		this.initVal = $('#searchbox').val();
		$('#search form').submit(searchBox.submit);
	},
	submit : function (e) {
		e.preventDefault();
		if ($('#searchbox').val() == searchBox.initVal || $('#searchbox').val() == '') return;
		searchBox.removeBox(searchBox.fetchResults);
	},
	fetchResults : function () {
		searchBox.renderBox();
		$.get('/search.php',{search : $('#searchbox').val(),PHPSESSID:SESSIONID},searchBox.displayResults,'json');
	},
	displayResults : function (res) {
//		$('#searchResults')
//			.removeClass('loading');
		var currcat = '';
		var ul = $('<ul />')
			.appendTo('#searchResults')
			.hide()
			;
		if (res.length == 0)
		{
				var li = $('<li />')
					.text(searchBox.noResults[lang])
					.addClass('header')
					.appendTo(ul)
					;
		}
		else
			$.each(res,function (i,el) {
				if (currcat != el.category)
				{
					currcat = el.category;
					var li = $('<li />')
						.text(currcat)
						.addClass('header')
						.appendTo(ul)
					;
				}
				var li = $('<a />')
					.text(el.title)
					.attr('href',el.link)
					.wrap('<li />')
					.parent()
					.appendTo(ul)
				;
			});
		ul.slideDown();
	},
	renderBox : function () {
		searchBox.visible = true;
		var left = $('#search').offset().left;
		var top = $('#search').offset().top;
		
		var w = $('#search').width();
		var h = $('#search').height();
		
		var div = $('<div />')
			.attr('id','searchResults')
			.addClass('loading')
			.appendTo('body')
			.css({
					 	'opacity' : 0.9,
						'width' : searchBox.width,
						'left' : left + w - searchBox.width,
						'top' : top+h
					})
			.hide()
			.fadeIn()
			;
		$('<a />')
			.text(searchBox.closeText[lang])
			.addClass('close')
			.click(searchBox.removeBox)
			.appendTo(div)
			;
	},
	removeBox : function (fn) {
		if (!$.isFunction(fn)) fn = function () {};
		if (searchBox.visible)
		{
			$('#searchResults').fadeOut(300,function () { $(this).remove(); searchBox.visible = false; fn(); });
		}
		else
		{
			fn();
		}
	}
}

var friendRecommend = {
	text : {pl : 'Wyślij', en : 'Send' },
	text2 : {pl : 'Zamknij', en : 'Close' },
	text3 : {pl : 'Poleć znajomemu', en : 'Recommend to a friend' },
	text4 : {pl : 'Wiadomość wysłana', en : 'Message sent' },
	text5 : {pl : 'Twoje imię', en : 'Your name' },
	dialog : function (e) {
		e.preventDefault();
		var butt = {};
		butt[friendRecommend.text[lang]] = function() {
											var letter = $('.ui-dialog form').serializeArray();
											$.post('/mail.php',letter);
											$(this).dialog('close');
											alert(friendRecommend.text4[lang]);
									};
		butt[friendRecommend.text2[lang]] = function() {
											$(this).dialog('close');
										};
										
		$('	<div title="'+friendRecommend.text3[lang]+'">\
					<form>\
						<label>'+friendRecommend.text5[lang]+'<input type="text" name="name" /></label><br/>\
						<label>E-mail <input type="text" name="polecznajomemu" /></label><br/>\
					</form>\
				</div>\
			')
			.dialog({
								modal : true,
//								height: 380,
								buttons: butt
							});
			$('.ui-dialog input:first').focus();
			$('.ui-dialog form').submit(function (e) { e.preventDefault(); });
	}
}

var newsletter = {
	confirm : {
		'pl': 'Dziękujemy za zapisanie się do naszego newsletteru.',
		'en' : 'Thank you for signing up for our newsletter.'
	},
	entertext : null,
	p : null,
	init : function () {
		var obj = $('#nwslttr_submit').parent().parent();
		obj.css('height',obj.height());
		newsletter.p = $('#nwslttr').parent().prev();
		var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		$('#nwslttr_submit').parent().submit(function (e) {
			e.preventDefault();
			var send = $(this).serializeArray();
			if (filter.test($('#nwslttr').val())) {		
				newsletter.p.fadeOut(300,function () {$.post('newsletter.php',send,newsletter.submit);});
				$('#nwslttr').fadeOut(300).next().fadeOut(300);
			}
		});
	},
	submit : function () {
		newsletter.p.text(newsletter.confirm[lang]).fadeIn();
//		$('<div />').text(newsletter.confirm[lang]).dialog({modal:true});
		$('#nwslttr').parent().remove();
	}
}


var zespol = {
	color : null,
	header : {'pl' : 'Formularz kontaktowy', 'en' : 'Contact form'},
	f1 : {'pl' : 'Twoje imię i nazwisko', 'en' : 'Your name'},
	f2 : {'pl' : 'Twój e-mail', 'en' : 'Your e-mail'},
	f3 : {'pl' : 'Temat wiadomości', 'en' : 'Message subject'},
	f4 : {'pl' : 'Wiadomość', 'en' : 'Message'},
	b1 : {'pl' : 'Anuluj', 'en' : 'Cancel'},
	b2 : {'pl' : 'Wyślij', 'en' : 'Send'},
	b3 : {'pl' : 'Zamknij', 'en' : 'Close'},
	success : {'pl' : 'Wiadomość została wysłana', 'en' : 'Message has been sent'},
	init : function () {
		if ($('.zespol').size() == 0) return; 
		var people = $('.zespol .person');
		$('.zespol .person a').click(zespol.showForm);
		var accordion = people
			.wrapAll('<div />')
			.parent()
			;
		var divisions = [];
		people.each(function (i,el) { var l = $(this).attr('dzial'); divisions[l] = l; });

		for (i in divisions)
		{
			var dzial = people.filter('div[dzial='+i+']').wrapAll('<div />').parent();
			$('<a />')
				.attr('href','#')
				.text(i)
				.wrap('<h2 />')
				.parent()
				.insertBefore(dzial)
				;
		}
		accordion.accordion({ header: "h2", collapsible: true, autoHeight: false });
//		accordion
//			.find('.ui-state-active')
//			.removeClass('ui-state-active')
//			.removeClass('ui-corner-top')
//			.addClass('ui-state-default')
//			.addClass('ui-corner-all')
//			.next()
//			.hide()
//			.prev()
//			.find('.ui-icon-triangle-1-s')
//			.removeClass('ui-icon-triangle-1-s')
//			.addClass('ui-icon-triangle-1-e')
//			;
	},
	showForm : function () {
		var butt = {};
		var id = $(this).attr('id');
		butt[zespol.b2[lang]] = function() {
										if (zespol.validate())
										{
											var letter = $('.ui-dialog form').serializeArray();
											$.post('/mail.php',letter);
											$('.ui-dialog-content').empty().text(zespol.success[lang]).css({'lineHeight': '56px','textAlign':'center'});
											$('.ui-dialog-buttonpane button:first').remove();
											$('.ui-dialog-buttonpane button').text(zespol.b3[lang]);
										}
									};
		butt[zespol.b1[lang]] = function() {
											$(this).dialog('close');
										};
										
		$('	<div title="'+zespol.header[lang]+'">\
					<form>\
					<input type="hidden" name="id" value="'+id+'"/>\
					<label>'+zespol.f1[lang]+' <input type="text" name="nazwa" /></label><br/>\
					<label>'+zespol.f2[lang]+' <input type="text" name="email" /></label><br/>\
					<label>'+zespol.f3[lang]+' <input type="text" name="temat" /></label><br/>\
					<label>'+zespol.f4[lang]+' <textarea name="tresc" style="width: 100%; height: 130px;"></textarea></label>\
					</form>\
				</div>\
			')
			.dialog({
								modal : true,
//								height: 380,
								buttons: butt
							});
			$('.ui-dialog input:first').focus();
	},
	validate : function () {
		var ret = true;
		$('.ui-dialog form input,.ui-dialog form textarea').each(function (i,el) {
			if ($(this).val() == '')
			{
				$(this).parent().css('color' , '#F00');
				ret = false;
			}
			else
			{
				$(this).parent().css('color' , '#999');
			}
		});
		return ret;
	}
}

var press = {
	texts : {
		'close' : {'en' : 'close','pl' : 'zamknij'},
		'download' : {'en' : 'download file','pl' : 'pobierz plik'},
		'logout' : {'en' : 'log out', 'pl' : 'wyloguj się'},
		'error' : {'en' : 'Incorrect login data', 'pl' : 'Niepoprawne dane logowania' }
	},
	loginCheck : function () {
		$.ajax({
			type: 'POST',
			url: '/media.ajax.php',
			dataType: 'json',
			data: {loginCheck : true},
			success: function (data) {
				if (data.passed && SESSIONID == data.sessionid)
					press.display(data.login);
			}
		});
	},
	login : function () {
		var loginfo = $('#pressLogin form').serializeArray();
		$.ajax({
			async: false,
			type: 'POST',
			url: '/media.ajax.php',
			dataType: 'json',
			data: loginfo,
			success: function (data) {
				
				if (data.passed && SESSIONID == data.sessionid)
					press.display(data.login);
				else
					alert(press.texts.error[lang]);
				}
		});
	},
	display : function (login) {
		$('.pressinfo').remove();
		$('<div />')
			.addClass('pressinfo')
			.insertAfter('#pressLogin')
			.prev()
			.hide()
			;
		$('.pressinfo').html('<a class="logout">'+press.texts.logout[lang]+'</a><strong>'+login+'</strong>').find('.logout').click(press.logout);
		$.ajax({
			async: false,
			type: 'POST',
			url: '/media.ajax.php',
			dataType: 'json',
			data: { feed : true },
			success: function (data) {
					$.each(data,function (i,e) {
						var div = $('<div />')
							.addClass('row')
							.attr('element',e.id)
							.appendTo('.pressinfo')
							.html('<span>'+e.data+'</span> <strong>'+e.tytul+'</strong>')
							.find('strong')
							.click(function () { press.more(e.id); })
							;
						if (e.grafika != '')
						{
							div.parent().prepend('<img src="/other/'+e.grafika+'" style="height: 36px; width: 40px; margin-right: 5px; float: left;" />');
							$('<br />').insertBefore(div);
							div.parent().find('span').css({marginTop: 6, display: 'inline-block'});
							$('<br style="clear: both;" />').insertAfter(div);
						}
					});
				
				}
		});
	},
	more : function (id)
	{
		if ($('.pressinfo div.row[element='+id+']').hasClass('expanded')) return;
		
		$('.pressinfo div.row[element!='+id+']').slideUp(300);
		var row = $('.pressinfo div.row[element='+id+']')
			.addClass('expanded')
			.prepend('<a class="close">'+press.texts.close[lang]+'</a>')
			;
		row.find('a.close').click(press.less);

		$.ajax({
			async: false,
			type: 'POST',
			url: '/media.ajax.php',
			dataType: 'json',
			data: { more : id },
			success: function (data) {
					var div = $('<div />')
						.html(data.tekst)
						.addClass('more')
						.appendTo(row)
						.hide()
						.slideDown(400)
						;
					if (data.plik != '') $('<a />').addClass('download').attr({href:data.plik+':download'}).text(press.texts.download[lang]).prependTo(div);
				}
		});
	},
	less : function ()
	{
		$('.pressinfo .row .more,.pressinfo .row .close').remove();
		$('.pressinfo .row').slideDown(300).removeClass('expanded');
	},
	logout : function ()
	{
		$.ajax({
			async: false,
			type: 'POST',
			url: '/media.ajax.php',
			dataType: 'json',
			data: { logout : true },
			success: function (data) {
					$('.pressinfo')
						.remove()
						;
					$('#pressLogin')
						.show()
						.find('input[type!=submit]')
						.val('')
						;
				}
		});
	}
}

// karuzela
$.fn.carousel = function ()
{
	var timer = 10000;
	var parent = this;
	var children = $(parent).children();
	var left = 17;
// ^^^^^ bo nie chcialo czytac offsetu :(
	var mod = children.length;
	$(parent).find('a').click(function (e) { $(parent).stop(); e.preventDefault(); change(); });
	if (mod > 1)
	{
		var current = 0;
		$.each(children,function (i, el){ $(this).css({'height':$(parent).height(), 'width' : $(parent).width()-left }); if ($(this).css('display') != 'none') current = i; });
		var width = $(parent).width();
		var change = function ()
		{
			var cur = children[current];
			current = (current+1)%mod;
			var next = children[current];
			$(next).css({'left':width+left}).show();
			$(next).animate({'left':left},300);
			$(cur).animate({'left':-width},300,function () { $(this).hide(); });
			$(parent).animate({'opacity':1},timer,change);
		}
		$(parent).animate({'opacity':1},timer,change);
	}
}

$.fn.clearText = function () {
	$(this).each(function (i,el) {
		var value = $(this).val();
		var obj = $(this);
		$(this)
			.focus(function () { if (value == obj.val()) obj.val(''); })
			.blur(function () { if ('' == obj.val()) obj.val(value); });
		return $(this);
	});
}


// czytnik rss
$.fn.rssreader = function (url) {
	var parent = this;
	//use the JQuery get to grab the URL from the selected item, put the results in to an argument for parsing in the inline function called when the feed retrieval is complete
		$.get('proxy.php?url='+url, function(d) {
			
			//find each 'item' in the file and parse it
			$(d).find('item').each(function() {
				
				//name the current found item this for this particular loop run
				var $item = $(this);
				// grab the post title
				var title = $item.find('title').text();
				// grab the post's URL
				var link = $item.find('link').text();
				// next, the description
				var description = $item.find('description').text();
				//don't forget the pubdate
				var pubDate = $item.find('pubDate').text();
				
				$('<h4 />').text(pubDate).appendTo(parent);
				$('<h3 />').text(title).appendTo(parent);
				$('<p />').text(description).appendTo(parent);
				$('<a />').attr({'href':link , 'target' : '_blank'}).text('wiecej').appendTo(parent);
			});
		});
}

function truncate (str,l)
{
	var data = str.substr(0,l).split(' ');
	data[data.length-1] = null;
	return data.join(' ')+' ...';
}