var FLICKR_API_KEY = '136750182707da929b6392ab54061c44';
var FLICKR_BASEURL = 'http://api.flickr.com/services/rest/';


String.prototype.startsWith = function(str) {return (this.match("^"+str)==str)}

// podpinanie lokalnych linków zaczynających się od "/"
$("a").live("click", function(e){
	var href = $(this).attr("href");
	if(href.startsWith(BASE_URL) && !href.startsWith(BASE_URL + "/pl/foto")){
		e.preventDefault();
		$('#page-container').load(href, function () {
			flickrGetSets();
			initContact();
			initLoaders();
			initGallery();
			initForms('form#footer-newsletter input[type=text], form#search input[type=text], .replies .comment');
		});
	}
	//if(href.startsWith(BASE_URL)){
	//	e.preventDefault();
	//	//window.location = href;
	//	$('#viewport').load(href,{ajax: 'true'});
	//	//http://bublewicz.tomogroup.pl/pl/aktualnosci/pytanie-pose-do-ministra-srodowiska/
	//	//console.log("$('#page-container').load('" + href + "',{ajax: 'true'});")
	//	/*, function () {
	//	
	//		flickrGetSets();
	//		initContact();
	//		initLoaders();
	//		initGallery();
	//		initForms('form#footer-newsletter input[type=text], form#search input[type=text], .replies .comment');
	//	})*/
	//}
});

Path.rescue(function(){
	if (this.current.indexOf('#!') != -1) {
		$('#page-container').load(this.current.replace('#!', ''), function () {
			flickrGetSets();
			initContact();
			initLoaders();
			initGallery();
			initForms('form#footer-newsletter input[type=text], form#search input[type=text], .replies .comment');
		})
	}
});
 
Path.listen();

// Init
$(document).ready(function () {
	initContact();
	initHeader();
	initOffices();
	initForms('form#footer-newsletter input[type=text], form#search input[type=text], .replies .comment');
	initPhotosEqualHeights(4);
	initNavigation();
	flickrGetSets();
	initGallery();
})

$('.link-top').live('click', function (e) {
	$(window).scrollTop(0);
	e.preventDefault();
})

function initLoaders() {
	$('ul.feed').each(function () {
		var self = this;
		var toolbar = $(this).next('.toolbar').eq(0);
		var page = 1;
		var pages = 0;
		
		$('.link-expand:not(.link)').click(function (e) {
			var link = this;
			if (page != pages) {
				$.getJSON(BASE_URL+'/feed', {'page': page},
					function (result) {
						if (result.errorcode == 0) {
							pages = parseInt(result.pages)
							page += 1;
							$(self).append(result.html)
							
							if (page == pages) {
								$(link).hide();
							}
						}
					}
				);
			} else {
				$(link).hide();
			}
			e.preventDefault();
		})
	})
}

function initNavigation() {
	var href = window.location.href;
	if (href.match($('#navigation li a:contains("Wydarzenia")').attr('href'))) {
		//$('#navigation h1').html('Wydarzenia')
	}
	
	$('#navigation li a').live('click', function (e) {
		var parent = $(this).parent().parent();
		$('li', parent).removeClass('current');
		$(this).parent().addClass('current');
		
		if ($(this).text() == 'Wydarzenia') {
			$('#navigation h1').html('Wydarzenia')
		} else {
			$('#navigation h1').empty().append(
				$('<a>', {
					'href': '/pl/wydarzenia/', 
					'title': 'Wydarzenia', 
					'html': 'Wydarzenia'})
			);
		}
	})
	
	$('#navigation h1 a').live('click', function () {
		$('#navigation h1').empty().html('Wydarzenia')
		$('#navigation li').removeClass('current');
		$('#navigation li a:contains("Wydarzenia")').parent().addClass('current')
	})
}

function flickrLoadSet(photoset_id, photo_id, target) {

	var infoSet = {'title': '', 'description': '', 'photoset_id': '', 'date_create': ''};
	$.getJSON(FLICKR_BASEURL+'?jsoncallback=?', {
			'method': 'flickr.photosets.getInfo',
			'photoset_id': photoset_id,
			'api_key': FLICKR_API_KEY,
			'media': 'photo',
			'format': 'json'//,
			//'nojsoncallback': 1
		}, function (result) {
			if (result.stat == 'ok') {
				infoSet.title = result.photoset.title._content;
				infoSet.description = result.photoset.description._content;
				infoSet.photoset_id = result.photoset.id;
				infoSet.date_create = new Date(result.photoset.date_create*1000);
				
				if (infoSet.description == '') {
					$('#photoset-description').remove();
				} else {
					$('#photoset-description').html(infoSet.description);
				}
				
				if (infoSet.title == '') {
					$('#single-photo h5.title').remove()
				} else {
					//$('#single-photo h5.title').html(infoSet.title);
					$('.photo-wrapper h3.arrow-left span').html(infoSet.title);
				}
				
				if (infoSet.date_create == '') {
					$('#single-photo .time').remove()
				} else {
					$('#single-photo .time').html(jQuery.timeago(infoSet.date_create));
				}
			}
		}
	);

	$.getJSON(FLICKR_BASEURL+'?jsoncallback=?', {
			'method': 'flickr.photosets.getPhotos',
			'photoset_id': photoset_id,
			'api_key': FLICKR_API_KEY,
			'media': 'photo',
			'format': 'json'//,
			//'nojsoncallback': 1
		}, function (result) {
			if (result.stat == 'ok') {
				var items = new Array;
				var current_item = {};
				
				for (a in result.photoset.photo) {
					var item = result.photoset.photo[a];
					var src = 'http://farm{{ farm }}.static.flickr.com/{{ server }}/{{ primary }}_{{ secret }}_{{ size }}.jpg';
					src = src.replace('{{ farm }}', item.farm);
					src = src.replace('{{ server }}', item.server);
					src = src.replace('{{ primary }}', item.id);
					src = src.replace('{{ secret }}', item.secret);
					
					src = src.replace('{{ size }}', 'm');
					items.push({
						'id': item.id,
						'title': item.title,
						'src': src,
						'is_current': (item.id == photo_id)
					})
					
					if (item.id == photo_id) {
						src = src.replace('{{ size }}', 'z');
						src = src.replace('_m', '_z');
						current_item = {
							'id': item.id,
							'title': item.title,
							'src': src
						}
					}
				}
				
				$('#single-photo h5.title').html(current_item.title);
				
				var img = new Image();
				img.src = current_item.src;
				img.alt = infoSet.title;
				img.onload = function () {
					$('#photo-container').empty();
					$('#photo-container').append(img);
					
					if ($('#photo-container img').width() > $('#photo-container').width()) {
						$('#photo-container img').css({'width': $('#photo-container').width()})
					}
					
					galleryControls();
					
					var prev = $('ul.photos li.current').prev();
					if (prev.size() == 0) { prev = $('ul.photos li:last-child'); }
					$('#link-photo-previous').attr('href', prev.data('href'));
					
					var next = $('ul.photos li.current').next();
					if (next.size() == 0) { next = $('ul.photos li:first-child'); }
					$('#link-photo-next').attr('href', next.data('href'));
				}
				
				$(target).each(function () {
					var container = this;
					$(this).empty();
					$.each(items, function (index, item) {
						var li = $('<li>').data('href', BASE_URL+'/pl/foto/?flickr_photoset_id='+photoset_id+'&photo_id='+item.id).appendTo(container);
						if (item.is_current) { $(li).addClass('current') }
						if (index > 7) { li.hide(); }
						var a = $('<a>', {'class': 'photo', 'href': BASE_URL+'/pl/foto/?flickr_photoset_id='+photoset_id+'&photo_id='+item.id, 'title': item.title}).appendTo(li);
						var img = $('<img>', {'src': item.src, 'alt': item.title}).appendTo(a);
						$('<a>', {'href': BASE_URL+'/pl/foto/?flickr_photoset_id='+photoset_id+'&photo_id='+item.id, 'title': item.title, 'class': 'title', 'html': item.title}).appendTo(li);
					})
					
					/*var toolbar = $('.toolbar', $(this).parent()).eq(0)
					$('.link-expand:not(.link)', toolbar).click(function (e) {
						$('li:hidden', container).slice(0, 4).show();
						e.preventDefault();
					})*/
				})
				
				initPhotosEqualHeights(4);
				$(target).hide();
				
				var toolbar = $(target).next('.toolbar').eq(0);
				$('.link-expand').click(function (e) {
					$('li:hidden', $(target))/*.slice(0, 4)*/.show();
					$(target).show();
					$(this).hide();
					e.preventDefault();
				})
			}
		}
	);
}

function flickrGetSets() {
	
	if ($('ul.flickr-photo-sets').size() == 0) { return false; }
	if ($('ul.flickr-photo-sets').html() != '') { return false; }
	
	$.getJSON(FLICKR_BASEURL+'?jsoncallback=?', {
			'method': 'flickr.photosets.getList',
			'user_id': FLICKR_USER_ID,
			'api_key': FLICKR_API_KEY,
			'format': 'json'//,
			//'nojsoncallback': 1
		}, function (result) {
			if (result.stat == 'ok') {
				var items = new Array;
				for (a in result.photosets.photoset) {
					var item = result.photosets.photoset[a]
					
					var src = 'http://farm{{ farm }}.static.flickr.com/{{ server }}/{{ primary }}_{{ secret }}_m.jpg';
					src = src.replace('{{ farm }}', item.farm);
					src = src.replace('{{ server }}', item.server);
					src = src.replace('{{ primary }}', item.primary);
					src = src.replace('{{ secret }}', item.secret);
					items.push({
						'id': item.id,
						'title': item.title._content,
						'description': item.description._content,
						'src': src,
						'date_create': new Date(item.date_create*1000),
						'primary': item.primary
					})
				}
				
				$('ul.flickr-photo-sets').each(function () {
					var container = this;
					$(this).empty();
					$.each(items, function (index, item) {
						var li = $('<li>').appendTo(container);
						if (index > 7) { li.hide(); }
						var a = $('<a>', {'class': 'photo', 'href': '/pl/foto/?flickr_photoset_id='+item.id+'&photo_id='+item.primary, 'title': item.title}).appendTo(li);
						var img = $('<img>', {'src': item.src, 'alt': item.title}).appendTo(a);
						$('<a>', {'href': '/pl/foto/?flickr_photoset_id='+item.id+'&photo_id='+item.primary, 'title': item.title, 'class': 'title', 'html': item.title}).appendTo(li);
						$('<span>', {'class': 'time', 'html': jQuery.timeago(item.date_create)}).appendTo(li);
					})
					
					var toolbar = $('.toolbar', $(this).parent()).eq(0)
					$('.link-expand:not(.link)', toolbar).click(function (e) {
						$('li:hidden', container).slice(0, 4).show();
						e.preventDefault();
					})
				})
				
				// ukrywanie wiecej niz 4 galerii na stronie Wydarzenia
				var i = 0;
				$('.photo-wrapper-feed ul.flickr-photo-sets li').each(function () {
					if (i > 3) { $(this).hide(); }
					i++;
				})
				initPhotosEqualHeights(4);
			}
		}
	);
	//http://api.flickr.com/services/rest/?method=flickr.photosets.getList&user_id=&api_key=&format=json
}

function initContact() {
	$('.contact-dialog').unbind('click');
	$('.contact-dialog').bind('click', function (e) {
		dialog('<div class="title clearfix"><h3>Napisz do mnie</h3> <span class="info">Proszę o przestrzeganie <a href="#" title="Regulamin">Regulaminu</a></span></div>'			
			+'<form method="post" action="/pl/contact/">'
			+'<fieldset>'
			+'<input type="text" name="name" class="input space" value="Wpisz imię i nazwisko..." />'
			+'<input type="text" name="email" class="input" value="Wpisz swój adres e-mail..." />'
			+'<div class="clear">&nbsp;</div><label class="clearfix">Wiadomość </label>' //<span>Dodaj: <a href="#" title="foto">foto</a> <a href="#" title="link">link</a></span>
			+'<textarea name="message">Zacznij wpisywać wiadomość...</textarea>'
			+'<button class="button-rounded" type="submit">Wyslij</button><a class="cancel" href="#" title="anuluj">Anuluj</a>'
			+'</fieldset>'
			+'</form>');
		initForms('.dialog form input, .dialog textarea');
		
		$(document).bind('keydown', function(e) {
			if (e.which == 27) {
				$('.dialog').fadeOut(500, function () {
					$('.dialog').remove();
					$(document).unbind('keydown');
				});
				e.stopPropagation();
				e.preventDefault();
			}
		});
		
		e.stopPropagation();
		e.preventDefault();
	})
}

function initForms(selector) {
	// domyślne wartości
	$(selector).each(function () {
		$(this).data('default_value', $(this).val());
		$(this).focus(function () {
			if ($(this).val() == '' || $(this).val() == $(this).data('default_value')) {
				$(this).val('');
			}
		}).blur(function () {
			if ($(this).val() == '') {
				$(this).val($(this).data('default_value'));
			}
		}).keydown(function(e) {
			if (e.which == 27) { // escape
				if ($(this).val() == '') {
					$(this).val($(this).data('default_value'));
				}
				
				e.stopPropagation();
				e.preventDefault();
			}
		});
	})
}

function initHeader() {
	$('#shortcuts ul li').hover(
		function () { $(this).stop().animate({opacity: .6}, 90) },
		function () { $(this).stop().animate({opacity: 1}, 300) }
	);
	
	$('#share a, body:not(.rules) #logo-po-header').css({opacity: .6}).hover(
		function () { $(this).stop().animate({opacity: 1}, 90) },
		function () { $(this).stop().animate({opacity: .6}, 200) }
	);
}

function dialog(html) {
	$('.dialog').remove()
	
	var container = $('<div>', {'class': 'dialog'}).appendTo('body');
	var overlay = $('<div>', {'class': 'dialog-overlay'}).css({width: $(window).width(), height: $(document).height()}).appendTo(container);
	
	var wrapper = $('<div>', {'class': 'dialog-wrapper'}).appendTo(container);
	var dialog = $('<div>', {'class': 'dialog-window'}).appendTo(wrapper);
	
	$(dialog).html(html);
	
	$(wrapper)
		.data('_top', parseInt($(window).height()/2-$(wrapper).outerHeight()/2))
		.css({
			top: $(wrapper).data('_top')+$(window).scrollTop(), 
			left: parseInt($(window).width()/2-$(wrapper).outerWidth()/2)
		});
		
	$('<a>', {'class': 'close', 'href': '#'}).click(function (e) {
		$(container).fadeOut(500, function () {
			$(container).remove(); 
		});
		e.preventDefault();
	}).appendTo(dialog);
	
	$('.dialog .cancel').click(function (e) {
		$(container).fadeOut(500, function () {
			$(container).remove(); 
		});
		e.preventDefault();
	})
		
	$(window).scroll(function() {
		$('.dialog-wrapper').stop().animate({top: $('.dialog-wrapper').data('_top')+$(window).scrollTop() });
	})
	
	/*$(document).keydown(function(e) {
		if (e.which == 27) { $(container).fadeOut(500, function () { $(container).remove(); }); }
	});*/
}

function initOffices() {	
	$('.office').hide();
	$('.office').eq(0).show();

	$('.office .map').each(function () {
		var config = $(this).attr('rel');
		var self = this;
		var parent = $(this).parent();
		config = config.split(';');
		
		var src = 'http://maps.google.com/maps/api/staticmap?center='+config[0]+','+config[1];
		src += '&zoom='+config[2];
		src += '&size='+config[3];
		src += '&sensor=false';
		src += '&maptype=roadmap';
		src += '&markers=color:blue|label:Biuro|'+config[0]+','+config[1];
		
		$(this).empty();
		
		$('<img>', {'src': src, 'alt': 'Powiększ'}).appendTo(this).click(function (e) {
			dialog('<div class="title"><h3>Mapa</h3></div><div class="map-extra"></div><div id="office-map"></div>');
			
			$('.map-extra').append('<div class="clear"></div>');
			$('.map-extra').append($('.address', parent).clone());
			$('.map-extra').append($('.hours', parent).clone());
			$('.map-extra').append('<div class="clear"></div>');
			
			var latlng = new google.maps.LatLng(config[0], config[1]);
			var myOptions = { zoom: 14, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
			var map = new google.maps.Map(document.getElementById("office-map"), myOptions);
			var marker = new google.maps.Marker({
				position: latlng, 
				map: map
			});

			$(document).bind('keydown', function(e) {
				if (e.which == 27) {
					$('.dialog').fadeOut(500, function () {
						$('.dialog').remove();
						$(document).unbind('keydown');
					});
					e.stopPropagation();
					e.preventDefault();
				}
			});
			e.preventDefault();
		})
	})

	if ($('.office').size() <= 1) { return false; }

	var container = $('.office').parent()
	$('<div>', {'class': 'office-switcher'}).appendTo(container)
	$('<a>', {'class': 'office-previous', 'html': 'Poprzednie', 'title': 'Pokaż poprzednie biuro', 'href': '#'}).appendTo('.office-switcher').click(function (e) {
		var prev = $('.office:visible').prev('.office');
		if (prev.size() > 0) {
			$('.office').hide();
			prev.show();
		} else {
			$('.office').hide();
			$('.office:last').show();
		}
		e.preventDefault();
	})
	$('<a>', {'class': 'office-next', 'html': 'Następne', 'title': 'Pokaż następne biuro', 'href': '#'}).appendTo('.office-switcher').click(function (e) {
		var next= $('.office:visible').next('.office');
		if (next.size() > 0) {
			$('.office').hide();
			next.show();
		} else {
			$('.office').hide();
			$('.office:first').show();
		}
		e.preventDefault();
	})
	
}

function initPhotosEqualHeights(every) {
	$('ul.photos').each(function () {
		var parent = $(this);
		
		// ustaw startową wysokość
		var photoEqualHeights = 0;
	
		// startowy index elementu dla plasterka
		var lastIndex = 0;
		
		$('li', parent).each(function () {
			// porównaj i ustaw wysokości
			if ($(this).height() > photoEqualHeights) { photoEqualHeights = $(this).height(); }
	
			// co 4 elementy ustaw wysokość, wyzeruj początkową wysokość i ustaw początkowy index na następny element
			if (($(this).index()+1)%every == 0) {
				$(this).css({'margin-right': 0});
				$('li', parent).slice(lastIndex, $(this).index()+1).css({height: parseInt(photoEqualHeights)});
				photoEqualHeights = 0;
				lastIndex = $(this).index()+1
			}
		})
	})
}

function initGallery() {
	//var match = window.location.href.match('flickr_photoset_id=(.+)&photo_id=(.+)');
	if (flickr_photoset_id != 'None' && photo_id != 'None') {
		//var photoset_id = match[1];
		//var photo_id = match[2];
		flickrLoadSet(flickr_photoset_id, photo_id, 'ul.photoset');
	}
}

function galleryControls() {
	$('#single-photo .wrapper a').css({opacity: .5}).hover(
		function () { $(this).stop().animate({opacity: 1}, 90) },
		function () { $(this).stop().animate({opacity: .5}, 300) }
	);
	
	var arrowPos = Math.round($('#single-photo').width()/2-$('#photo-container img').width()/2)+10
	$('#link-photo-previous').css({'background-position': arrowPos+'px center', height: $('#photo-container img').height()})
	$('#link-photo-next').css({'background-position': ($('#link-photo-next').width()-arrowPos-65)+'px center', height: $('#photo-container img').height()})
}

