/**
 *
 * BornToRoam
 * skrypty ogólne
 * 
 * @lastmodified 
 * @requires JQuery 1.4.2+
 *
 */

 
/**
 * http://javascript.crockford.com/prototypal.html
 * http://alexsexton.com/?p=51#comment-118)
 */
if (typeof Object.create !== 'function') {
	(function(){
		function F(){}
			Object.create = function( o ) {
			F.prototype = o;
			return new F();
		};
	})(); 
}
 
 
/**
 * Skrót dla cout()
 */ 
var cout =  (typeof window.console !== 'undefined') ? console.log : (function (args) { /* alert(args) */ });
  

/**
 * clicky
 * jQuery plugin
 * 
 * Make CONTAINER (or AREA) clickable
 *
 * @author Mateusz Janik
 *
 * @revision 5
 * @param href jq selector
 * @param area jq selector
 * @example $(CONTAINER).clicky() - CONTAINER clickble (first HREF inside)
 * @example $(CONTAINER).clicky(HREF) - CONTAINER clickable (HREF)
 * @example $(CONTAINER).clicky(HREF, AREA) - AREA (inside CONTAINER) clickable (HREF)
 */
(function($){
$.fn.clicky = function(href, area) {
	return this.each( function() {
		//cout('link: '+href+', area: '+area);
		var $t = $(this); 
		var $link;
		if (href) { 
			$link = $t.find(href).eq(0);
		} else {
			$link = $t.find('a'); 
			if ($link.length != 1) {
				$link = null;
			}
		}
		
		var $area = $t;
		if (area) { 
			var $f = $t.find(area);
			$area = ($f.length) ? $f : $t;
		}
		
		if ($link && $link.length) {
			$area.each( function() {
				//cout($(this));
				$(this)
				.click( function(e) {
					if (e.target.nodeName != 'a') {
						window.location = $link.attr('href');
					}
					e.preventDefault();
				})
				.css('cursor','pointer')
				.attr('title',$link.attr('title'));
			})
		}
	} );	
}
})(jQuery);
/**/ 
 
 
/**
 * showhide
 * jQuery plugin
 *
 * @author Mateusz Janik 
 * @revision 2 
 * @todo 
 * - obsługa cookie
 * - callbacks
 */
(function($){
$.fn.showhide = function(options) {

	// settings
	var s = $.extend(
		{
			prefix: 'showhide',
			effect: 0,
			enableCookie: false
		}, 
		options
	);
	
	var reaction = function() {
		this.toggleClass(s.prefix+'_collapsed').toggleClass(s.prefix+'_expanded');
	}
	 
	return this.each( function() {
	
		var 
		$root = $(this),
		$toggler = $root.find('.'+s.prefix+'-toggler').eq(0),
		$content = $root.find('.'+s.prefix+'-content').eq(0)
		;
				
		s.enableCookie = (s.enableCookie && (typeof $.cookie !== 'undefined') && $root.attr('id')) ? true : false;
		
		$toggler.bind('click', function () {
			switch (s.effect) {
				case 'slide': $content.slideToggle( 'fast', $.proxy(reaction, $root) ); 
					break;
				case 'fade': (function () {
					// @todo
				})();
					break;
				default: $content.toggle( 0, $.proxy(reaction, $root) ); 
					break;
			}
			return false
		});
		
	});	// each
}
})(jQuery); 
/**/
 
 
/*!
 * jQuery Tools dev - The missing UI library for the Web
 * 
 * tabs/tabs.js
 * tabs/tabs.slideshow.js
 * 
 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
 * 
 * http://flowplayer.org/tools/
 * 
 */
(function(a){a.tools=a.tools||{version:"dev"},a.tools.tabs={conf:{tabs:"a",current:"current",onBeforeClick:null,onClick:null,effect:"default",initialIndex:0,event:"click",rotate:!1,history:!1},addEffect:function(a,c){b[a]=c}};var b={"default":function(a,b){this.getPanes().hide().eq(a).show(),b.call()},fade:function(a,b){var c=this.getConf(),d=c.fadeOutSpeed,e=this.getPanes();d?e.fadeOut(d):e.hide(),e.eq(a).fadeIn(c.fadeInSpeed,b)},slide:function(a,b){this.getPanes().slideUp(200),this.getPanes().eq(a).slideDown(400,b)},ajax:function(a,b){this.getPanes().eq(0).load(this.getTabs().eq(a).attr("href"),b)}},c;a.tools.tabs.addEffect("horizontal",function(b,d){c||(c=this.getPanes().eq(0).width()),this.getCurrentPane().animate({width:0},function(){a(this).hide()}),this.getPanes().eq(b).animate({width:c},function(){a(this).show(),d.call()})});function d(c,d,e){var f=this,g=c.add(this),h=c.find(e.tabs),i=d.jquery?d:c.children(d),j;h.length||(h=c.children()),i.length||(i=c.parent().find(d)),i.length||(i=a(d)),a.extend(this,{click:function(c,d){var i=h.eq(c);typeof c=="string"&&c.replace("#","")&&(i=h.filter("[href*="+c.replace("#","")+"]"),c=Math.max(h.index(i),0));if(e.rotate){var k=h.length-1;if(c<0)return f.click(k,d);if(c>k)return f.click(0,d)}if(!i.length){if(j>=0)return f;c=e.initialIndex,i=h.eq(c)}if(c===j)return f;d=d||a.Event(),d.type="onBeforeClick",g.trigger(d,[c]);if(!d.isDefaultPrevented()){b[e.effect].call(f,c,function(){d.type="onClick",g.trigger(d,[c])}),j=c,h.removeClass(e.current),i.addClass(e.current);return f}},getConf:function(){return e},getTabs:function(){return h},getPanes:function(){return i},getCurrentPane:function(){return i.eq(j)},getCurrentTab:function(){return h.eq(j)},getIndex:function(){return j},next:function(){return f.click(j+1)},prev:function(){return f.click(j-1)},destroy:function(){h.unbind(e.event).removeClass(e.current),i.find("a[href^=#]").unbind("click.T");return f}}),a.each("onBeforeClick,onClick".split(","),function(b,c){a.isFunction(e[c])&&a(f).bind(c,e[c]),f[c]=function(b){b&&a(f).bind(c,b);return f}}),e.history&&a.fn.history&&(a.tools.history.init(h),e.event="history"),h.each(function(b){a(this).bind(e.event,function(a){f.click(b,a);return a.preventDefault()})}),i.find("a[href^=#]").bind("click.T",function(b){f.click(a(this).attr("href"),b)}),location.hash&&e.tabs=="a"&&c.find("[href="+location.hash+"]").length?f.click(location.hash):(e.initialIndex===0||e.initialIndex>0)&&f.click(e.initialIndex)}a.fn.tabs=function(b,c){var e=this.data("tabs");e&&(e.destroy(),this.removeData("tabs")),a.isFunction(c)&&(c={onBeforeClick:c}),c=a.extend({},a.tools.tabs.conf,c),this.each(function(){e=new d(a(this),b,c),a(this).data("tabs",e)});return c.api?e:this}})(jQuery);
(function(a){var b;b=a.tools.tabs.slideshow={conf:{next:".forward",prev:".backward",disabledClass:"disabled",autoplay:!1,autopause:!0,interval:3e3,clickable:!0,api:!1}};function c(b,c){var d=this,e=b.add(this),f=b.data("tabs"),g,h=!0;function i(c){var d=a(c);return d.length<2?d:b.parent().find(c)}var j=i(c.next).click(function(){f.next()}),k=i(c.prev).click(function(){f.prev()});a.extend(d,{getTabs:function(){return f},getConf:function(){return c},play:function(){if(g)return d;var b=a.Event("onBeforePlay");e.trigger(b);if(b.isDefaultPrevented())return d;g=setInterval(f.next,c.interval),h=!1,e.trigger("onPlay");return d},pause:function(){if(!g)return d;var b=a.Event("onBeforePause");e.trigger(b);if(b.isDefaultPrevented())return d;g=clearInterval(g),e.trigger("onPause");return d},stop:function(){d.pause(),h=!0}}),a.each("onBeforePlay,onPlay,onBeforePause,onPause".split(","),function(b,e){a.isFunction(c[e])&&a(d).bind(e,c[e]),d[e]=function(b){return a(d).bind(e,b)}}),c.autopause&&f.getTabs().add(j).add(k).add(f.getPanes()).hover(d.pause,function(){h||d.play()}),c.autoplay&&d.play(),c.clickable&&f.getPanes().click(function(){f.next()});if(!f.getConf().rotate){var l=c.disabledClass;f.getIndex()||k.addClass(l),f.onBeforeClick(function(a,b){k.toggleClass(l,!b),j.toggleClass(l,b==f.getTabs().length-1)})}}a.fn.slideshow=function(d){var e=this.data("slideshow");if(e)return e;d=a.extend({},b.conf,d),this.each(function(){e=new c(a(this),d),a(this).data("slideshow",e)});return d.api?e:this}})(jQuery); 

 

//var App = App || {
//$.extend(config, nowe, nowe, ...)
var App = window.App || {
	generateFilters: function () {
		var 
			$container = $('.taxonomy-drilldown-lists'),
			$reset = $container.find('.taxonomy-drilldown-reset'),
			markup = '<div class="filter"><ul>',
			active = false
		;
		
		$container.find(' > div').each(function () { // dla każdej grupy
			var 
				$t = $(this), 
				label,
				tax,
				on, // czy filtrowanie jest aktywne
				terms = []
			;
				
			label = $t.find('h4').contents().filter(function () {
				return this.nodeType == 3
			}).text();
			
			tax = $t.attr('id').replace(/term-list-/,'');
			$.each( $('h1 .'+tax), function () {
				terms.push($(this).text());
			});
			var len = terms.length;
			
			var showall_href = $t.find('h4 > a');
			// @todo: co to kurde jest? bazujemy na term
			on = showall_href.length ? true : false; 
			
			markup += '<li class="'+tax+(len ? '' : ' inactive')+'"><label>'+label+'</label><dl><dt><span>';
			markup += on ? terms.join(', ') : 'wszystkie';
			markup += '</span><a href="#" title="rozwiń"></a></dt><dd>';
			
			if (!on) {
				markup += '';
			} else {
				active = true;
			
				markup += '<p><a href="'+showall_href.attr('href')+'">&laquo; pokaż wszystkie '+label.toLowerCase()+'</a></p>';
				
				if (len > 1) {
					//markup += '<p><a href="'+$t.find('a.remove-term').attr('href')+'">&laquo; pokaż nie tylko '+terms[len-1]+'</a></p>';
					markup += '<p><a href="'+$t.find('a.remove-term').attr('href')+'">&laquo; pokaż '+terms[len-2]+'</a></p>';
				}
				
			}
			if (!$t.find('ul > li:first-child').hasClass('current-term')) {
				markup += '<ul>'+$t.find(' > ul').html()+'</ul>';
			}
			
			markup += '</dd></dl></li>';
			
		});
		
		markup += '</ul>';
		markup += active ? '<a class="reset" href="'+$reset.attr('href')+'">wszystkie</a>' : '';
		
		$container.empty().append(markup+'</div>').fadeIn('slow');
	},

	
	/**
	 * Picasa API 1.1
	 * @author Mateusz Janik
	 */
	PicasaAPI: {
		init: function (feedURL, thumbSize, onSuccess) {
			var self = this; 
			
			var imageSize = site_cfg.picasa.imageSize ? site_cfg.picasa.imageSize : 800;
			
			self.xhr = $.ajax({
				//url: feedURL+'&callback=?',
				url: feedURL,
				dataType: 'jsonp',
				method: 'GET', 
				global: true,
				async: true,
				beforeSend: function () {
					//cout('before send');
				},
				success: function(json) { 

					self.url = feedURL;
					self.title = json.feed.title.$t;
					self.link = json.feed.link[1].href;
					self.quantity = json.feed.gphoto$numphotos.$t;
					self.photos = []; // trzeba czyścić bo coś takiego dzieje się z (tylko) tablicami we wzorcu Prototypal Inheritance
					
					/* 
						zdjęcie: 
						feed.entry[i].media$group.media$content[0].url
						miniatura: 
						feed.entry[i].media$group.media$thumbnail[tablica-rozmiarow].url // [72, 144, 288]
						
						http://lh5.ggpht.com/_hKbpnWs1T7A/TOvaBF0hLdI/AAAAAAAAZfs/d4NqQwbZr4E/s144/IMG_3144-2.jpg = standard
						http://lh5.ggpht.com/_hKbpnWs1T7A/TOvaBF0hLdI/AAAAAAAAZfs/d4NqQwbZr4E/s100-c/IMG_3144-2.jpg = 100px cropped
					*/					
					$.each(json.feed.entry, function(i,item){
						self.photos.push({
							//0 url: item.media$group.media$content[0].url,
							url: item.content.src+'?imgmax='+imageSize,
							link: item.link[1].href,
							//0 thumb: item.media$group.media$thumbnail[0].url.replace('s72','s'+(thumbSize ? thumbSize : 100)+'-c')
							thumb: function () {
								var t = item.media$group.media$thumbnail[1];
								var longer = ( t.height > t.width ) ? t.height : t.width;
								//;;console.log(t.url.replace('s'+t.height,'s'+(thumbSize ? thumbSize : 100)+'-c'));
								return t.url.replace('s'+longer, 's'+(thumbSize ? thumbSize : 100)+'-c')
							}(),
							desc: item.media$group.media$description.$t
						})
					});
					if (typeof(onSuccess) === 'function' ) onSuccess()
					
				},
				error: function() {
					//App.overlay.hide()
					//cout('error gallery load')
				},
				complete: function () {
					//App.overlay.hide()
					
				}
			});
			return self.xhr
		},
		photos: [],
		
		
		
		onComplete: function () {
			
		},
		
		/* @test */
		render: function ($container, albumURL, onComplete) {
			
			var feed = App.picasaAlbumTest(albumURL);
			if (!feed) return;
			var 
				$this = $container,
				album = this,
				/* 
				@FIXME: Object.create nie tworzy kopii, a referencje do App.PicasaAPI, 
				tak więc np. push do tablicy photos w drugim albumie będzie dokładał do tych z pierwszego... 
				*/
				html = ''
			;
			//cout(html);
			
			$this.addClass('picasa').append('<span class="loader">Ładowanie</span>');
			
			var xhr = album.init(feed, site_cfg.picasa.thumbSize, function () {});

			xhr
			.success(function () {
				//cout(album.url);
			})
			.complete(function () {
			
				html += '<div class="h"><h3>'+album.title+'</h3><a class="external" target="_blank" href="'+album.link+'">link</a></div>';
				html += '<ul class="photos">';		
				$.each(album.photos, function (i, item) {
 
					html += '<li>';
					html += '<a target="_blank" title="'+item.desc+'" rel="gallery-picasa" href="'+item.url+'"><img src="'+item.thumb+'" alt="'+item.desc+'" /></a>';
					html += '<div class="meta"></div>';
					html += '</li>';
							
				});
				
				html += '</ul>';
				$this.html(html);
				 
				_activateViewer();
				
			})
			.complete(onComplete || function(){});

				
			function _activateViewer() {
				//$("a[rel^='gallery']").colorbox(site_cfg.colorbox);	 
				$("a[rel^='gallery']").colorbox($.extend(site_cfg.colorbox,{
					onComplete: function () {
						//console.log('asadasd',$(this));
					}
					//title: 'adads'
				}));	
			}		
			
			return true
						
		} // App.PicasaAPI.render
		
	}, // App.PicasaAPI

		
	/**
	 * Jeśli funkcja wykryje album Picasa, np: http://picasaweb.google.com/NAZWA_USERA/NAZWA_ALBUMU
	 * zwróci adres feeda JSON: http://picasaweb.google.com/data/feed/api/user/NAZWA_USERA/album/NAZWA_ALBUMU?alt=json
	 * testy http://jsfiddle.net/6rxtN/
	 */		
	picasaAlbumTest: function (albumURL) {

		var re = /^(?:(?:http|https):\/\/)?picasaweb\.google\.(?:com|pl)\/(.*?)\/(.*?)(?:[#\s].*|$)/g; 
		/* @fixme regexp alternatywa http|https - zrobione (ale czy działa?) */ 
		
		//if (!re.test(albumURL)) {/* alert('ERROR. nie znaleziono feeda') */}
		return re.test(albumURL) ? albumURL.replace(re, "https://picasaweb.google.com/data/feed/api/user/$1/album/$2?alt=json") : false

	} // App.picasaAlbumTest
	
	 
	 
	
}
 
 
/* ************************************************
   Document ready 
*/
$(function(){

	// drafts, old
	if ($('#single-product')[0]) {
		$.getScript(site_cfg.url.js+'jquery.colorbox-min.js',function(){		

			if (typeof $.fn.colorbox !== 'undefined') {
				$("#single-product .gallery a")
				.attr('rel','gallery')
				.colorbox(site_cfg.colorbox);
			}
			
			$('.thumb a').click(function(){
				var alt = $(this).find('img').attr('alt');
				$('.gallery').find('img[alt='+alt+']').click();
				return false
			})
		})
	}
	
	
	/**
	 * Wygenerowanie użytecznego filtra
	 */
	App.generateFilters();
	
	
	/**
	 * Klikalne ostatnie komentarze
	 */
	$('.recent-comments li').clicky();
	
	
	/**
	 * Renderowanie galerii (wycieczka)
	 */
	$('#trip-gallery li').each(function () {
		/*
 		App.renderGallery($(this), $(this).find('a').attr('href'), function () {
			cout('gotowe')
		}); 
		*/
		 
		var album = Object.create(App.PicasaAPI);
		album.render($(this), $(this).find('a').attr('href'), function () {
			//cout('gotowe')
		});
	});
	


	
	/**
	 * Obsługa strony z galerią
	 */
	(function () {
		$("a[rel^='gallery']").colorbox($.extend(site_cfg.colorbox,{
			onComplete: function () {
				document.location.hash = '_'+$(this).closest('a').attr('id');
			}
		}));
		var hash = new String(document.location).indexOf("#");
		if (hash > 0) {
			pid = new String(document.location).substring(hash + 1); 
			if ((pid.length > 1) && (/^_pid-\d/.test(pid))) {
				//console.log('uruchomiono z hasha');
				var id = pid.replace(/_/,'');
				$('#'+id).click();
			} else {
			  
			}
		}	
	})();
	 
	 
	/**
	 * Renderowanie galerii (lista wycieczek)
	 *
	 * @todo inny wariant kolejkowania ajaksów gdy mamy więcej albumów przy wycieczce (wykorzystać Jquery Deferrd)
	 */	
	$('.trips-galleries ul.trips > li').each(function () {
		var $this = $(this);
		var $container = $this.find('.secondary');
		var picasaAlbumsNum = 0;
		var picasaLoaded = false;
		var count = 0;
		
		$this.find('h3 a, .toggler a').click(function (e) {
		
			picasaAlbumsNum = 0;
			$container.find('> ul > li').each(function () {
				picasaAlbumsNum +=  App.picasaAlbumTest($(this).find('a').attr('href')) ? 1 : 0;
			});
			
			// cout(picasaAlbumsNum);
			
			// @FIXME dwa razy $.each to średni pomysł... no ale roboczo niech będzie
			
			if (!picasaLoaded && picasaAlbumsNum) {
				if (count == 0) {
					$this.addClass('loading');
				}
				$container.find('> ul > li').each(function () {
					 
					var album = Object.create(App.PicasaAPI);
					//App.renderGallery($(this), $(this).find('a').attr('href'), function () {
					album.render($(this), $(this).find('a').attr('href'), function () {
					
						if (++count == picasaAlbumsNum) {
							picasaLoaded = true;
							_expandPhotos($this, $container);
						}
					}); 
				});				
			} else {
				_expandPhotos($this, $container);
			}
		
			e.preventDefault();
		});
	});
	/* Rozwijanie zdjęć */
	function _expandPhotos($root, $child){
		$child.fadeToggle(function () {
			$root.removeClass('loading').toggleClass('opened');
		});
	}
	
	
	/**
	 * Prezentacja "szczególnie polecamy"
	 * @requires jquery.tools.min.js [tabs]
	 */
	$('#sidebar .home-hot-trips').each(function () {
		var 
			$root = $(this)
			$panes = $root.find('ul > li')
		;
		
		var h = '<p class="jump">';
		$panes.each(function () {
			h += '<a href="#">'+$(this).find('.num').html()+'</a>';
		});
		h += '</p>';
		
		var $tabs = $(h).appendTo($root);
		
		$tabs.tabs($panes, {
			effect: 'fade', 
			rotate: true
		}).slideshow({
			autoplay: true,
			interval: 6000,
			clickable: false
		});
		
		var tabs = $tabs.data('tabs');
		
		$root.find('.prev').click(function () {
			tabs.prev();
			return false
		});
		$root.find('.next').click(function () {
			tabs.next();
			return false
		});
				
	});	
	
	 
		
}) // Document ready


var site_cfg = site_cfg || {};

site_cfg.colorbox = {
	opacity: .85,
	transition: 'elastic',
	current: "{current} / {total}",
/* 	title: function(){
		var url = $(this).attr('href');
		return '<a href="'+url+'" target="_blank">[+]</a>';
	}, */
	/* maxWidth: '90%',
	maxHeight: '90%', */
	scalePhotos: true 
}

site_cfg.fancybox = {

	transitionIn: 'none',
	transitionOut: 'none',
	changeSpeed: 0,
	changeFade: 0,
	autoScale: false,
	centerOnScroll: true,
	scrolling: 'yes',
	titlePosition: 'inside',
	overlayColor: ''
	
}

site_cfg.picasa = {
	thumbSize: 81,
	imageSize: 1200
}
