/**
 * Odpoczne.pl
 * skrypty ogólne
 * 
 * @requires JQuery 1.4.2+
 * @lastmodified 13:21 2010-05-27
 */


/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
* 
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);


/**
 * clicky
 * jQuery plugin
 * 
 * Make CONTAINER (or AREA) clickable
 *
 * @revision 3
 * @param href jq selector
 * @param area jq selector/s
 * @example $(CONTAINER).clicky() - CONTAINER clickable (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() {
		//console.log('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) {
			$area.each( function() {
				//console.log($(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);
/**/ 


/**
 * Modal dialogs wrapper
 *
 * @requires jquery.simplemodal
 */
var ModalDialog = {
	open: function(el, opt) {
		if ( typeof($.fn.modal) === 'function' ) {
			if (typeof(opt) === 'object') {
				if (opt.onCloseEffect) {
					opt.onClose = function(dialog) {
						dialog.data.fadeOut('slow', function () {
							dialog.container.hide(0, function () {
								dialog.overlay.fadeOut('fast', function () {
									$.modal.close();
								});
							});
						});
					}
				}
				$(el).modal(opt);
			} else {
				$(el).modal();
			}
		}		
	},
	close: function() {
		$.modal.close();
	}
};
/**/


/**
 * picViewer
 * jQuery plugin
 *
 * @author Mateusz Janik 
 * @version 1.1 odpoczne
 * @revision 6
 * @todo revision 7: 
 *   - if array length == 1 slideshow off
 * @todo revision 8:  
 *   - inne zliczanie interwałów pomiędzy zdjęciami (od momentu załadowania)
 */
(function($) {
	$.fn.picViewer = function(settings) {

		var defaults = {
			clNext: '.pv-next',
			clPrev: '.pv-prev',
			clBank: '.pv-bank',
			clNum: '.pv-num',
			clPicLink: '.pv-pic',
			clPicImg: '.pv-pic img',
			time: 4000
		};
		var opts = $.extend('',defaults, settings);
		
		return this.each( function() {
			var $this = this;
			var $arr = $(opts.clBank+' > li' ,$this);
			var $picLink = $(opts.clPicLink, $this);
			var $picImg = $(opts.clPicImg, $this);
			
			var total = $arr.length;
			if (total == 0) return;
			
			var config = {
				lang: site_cfg.lang
			}
			
			$('.pv-panel').remove();
			var inject = '<p class="pv-panel"> <a href="#" class="pv-next">'+config.lang.nastepne+'</a> <a href="#" class="pv-prev">'+config.lang.poprzednie+'</a> <span class="pv-num"><em></em></span> </p>';
			$(inject).insertAfter($picLink); 
			var $loader = $('<span class="loader" />').appendTo($picLink);
			
			/* @todo */
			// Check loading state of #1 image
			/* if ($container.find("img:first")[0].complete) {
				$.fn.showcase.start($container, opt);
			}
			else {
				$container.find("img:first").load( function() {
					$.fn.showcase.start($container, opt);
				});
			} */			
 			$picImg.load( function () {
				$picLink.removeClass('loading');
				//$loader.hide();
				//$picImg.fadeIn('slow')
				$picImg.show();
			} );
			
			var $num = $(opts.clNum,$this);			
			var current = 0;
			setText(1,total,$num);
			
			var bank_arr = [];
			$arr.each( function(i,$li) {
				bank_arr.push( {
					href: $(' a', $li).attr('href'),
					src: $(' img', $li).attr('src')
				});
			}); 
			
			$(opts.clNext,this).bind('click slide', function (e, auto) {
				
				/* if (!auto) {
					// jeśli funkcja nie jest odpalana przez slideshow (interval), to zatrzymujemy interval
					clearInterval(slideshow);
				}  */
				// http://docs.jquery.com/Events/trigger#examples
				if (e.type == 'click') clearInterval(slideshow);
				
				$picImg.hide(0,
					function () {
						
						//setTimeout( function() { $picLink.addClass('loading') }, 2000);
						//$loader.show();
						$picLink.addClass('loading');
						
						if (++current > total-1) {current = 0}
						setText(current+1,total,$num);
						
						$picImg.attr('src',bank_arr[current].href)
						//$picLink.attr('href',bank_arr[current].href)
						 
					}
				);
				e.preventDefault();
			})
			/* .text('następne') */.attr('title','następne zdjęcie').show();

			$(opts.clPrev,this).bind('click slide', function (e, auto) {
				
				/* if (!auto) {
					// jeśli funkcja nie jest odpalana przez slideshow (interval), to zatrzymujemy interval
					clearInterval(slideshow);
				}  */
				if (e.type == 'click') clearInterval(slideshow);
				
				$picImg.hide(0,
					function () {
						$picLink.addClass('loading');
					
						if (--current < 0) {current = total-1}
						setText(current+1,total,$num);
						
						$picImg.attr('src',bank_arr[current].href)
						//$picLink.attr('href',bank_arr[current].href)
					}
				);
				e.preventDefault();
			})
			/* .text('poprzednie') */.attr('title','poprzednie zdjęcie').show();

			/* Włączenie auto-pokazu */
			/**/
			var $next = $(opts.clNext, $this);
			if ( typeof(opts.time) === 'number' ) {
				var slideshow = setInterval(function() { 
					$next.trigger('slide');
				}, opts.time); 
			}
			/**/
			
		}); // each
	
	} // $.fn

	function setText(i, n, $el) {
		$el.html( i+' <em>/ '+n+'</em>');		
	}
	
})(jQuery);
 

/* ************************************************

   Document ready 

*/
$(function(){


	/**
	 * Przełączanie trybu wyszukiwarki
	 */
	var $searchbox = $('#searchbox');
	$searchbox.find('.toggler a, h2').click(function () {
		var $exts = $searchbox.find('.ext')
	
		$exts.slideToggle( 222, function () { 
			if ($exts.filter(':animated').length <= 1) {
				$searchbox.toggleClass('extended') 
			}
		});
		
		return false
	} );

	/**
	 * Pola realtime
	 */
	$searchbox.find(".realtime select").change(function(){
		$('#total-loader').show();
		$searchbox.find('form').submit();
		return false;
	});

	
	
	/**
	 * Opóźnienie rozwijania menu
	 */
	$('#nav > ul > li:not(".current")').hoverIntent( {
		sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
		interval: 50, // number = milliseconds for onMouseOver polling interval
		timeout: 250, // number = milliseconds delay before onMouseOut
		over: function() { 
			$t = $(this);
			$t.addClass('h');
			$(' div.sub', this).show().css('z-index','999'); 
		}, 
		out: function() {
			$t = $(this);
			$t.removeClass('h');
			$(' div.sub', this).fadeOut('fast', function () {
				$(this).css('z-index','');
				$t.parent().find('li.current > ul').show();
			} ); 
		}
	} );
	
	
	/**
	 * Date picker
	 */	
	$.tools.dateinput.localize("pl", {
		months: 'Styczeń,Luty,Marzec,Kwiecień,Maj,Czerwiec,Lipiec,Sierpień,Wrzesień,Październik,Listopad,Grudzień',
		shortMonths: 'Sty,Lut,Mar,Kwi,Maj,Cze,Lip,Sie,Wrz,Paź,Lis,Gru',
		days: 'Niedziela,Poniedziałek,Wtorek,Środa,Czwartek,Piątek,Sobota',
		shortDays: 'Ni,Po,Wt,Śr,Cz,Pt,So'
	});
	// Inicjalizacja 
	$(".datepicker :text").dateinput({
		lang: 'pl',
		format: 'yyyy-mm-dd', 
		min: 1,
    firstDay: 1,
		selectors: true
	});
	// Pokazywanie kalendarza po kliknięciu ikony
	$('.datepicker').each(function () {
		var cal = $(':text', this).eq(0).data('dateinput');
		$(this).find('img').toggle(
			function () {
				cal.show();
				return false
			},
			function () {
				cal.hide();
				return false
			}
		)
	});
	// Aktualizowanie drugiego pola (powrót) po wybraniu daty wyjazdu
	/*
	$('#searchbox .datepicker:first :text').data("dateinput").change(function() {
		$("#searchbox .datepicker:last :text").data("dateinput").setMin(this.getValue(), true);
	});	
	*/
	
	
	/**
	 * Rotowanie numerów telefonu
	 */	
	$("#infoline .switch").tabs("#infoline .pane", {
		effect: 'fade',
		fadeOutSpeed: 600,
		fadeInSpeed: 400,
		// start from the beginning after the last tab
		rotate: true
	})
	.slideshow({
		autoplay: true,
		interval: 3000
	});

	/**
	 * Rotowanie numerów telefonu
	 */	
	$("#consult-box .switch").tabs("#consult-box .pane", {
		effect: 'fade',
		fadeOutSpeed: 600,
		fadeInSpeed: 400,
		// start from the beginning after the last tab
		rotate: true
	})
	.slideshow({
		autoplay: true,
		interval: 3000
	});
	
	
	/**
	 * Zakładki na stronie głównej
	 * @requires JQuery Tools
	 */
	$("#home-dayoffers .nav ul").tabs("#home-dayoffers .box > .panes > div", {
		effect: 'fade',  
		rotate: true,
		tabs: 'li'
	});
	$("#home-dayoffers .pager").tabs('> .panes .pane', {
		effect: 'fade',
		rotate: true
	})
	.slideshow({
		autoplay: true,
		interval: 5000,
		clickable: false
	});
	
	
	/**
	 * Zakładki na stronie kategorii
	 * @requires JQuery Tools
	 */
	$("#cat-teaser .pager").tabs("#cat-teaser .panes > div", {
		effect: 'fade', 
		// start from the beginning after the last tab
		rotate: true
		//tabs: 'li'
	});
	/* .slideshow({
		autoplay: true
	});	 */
	$("#cat-cols .pager-thick").tabs("#cat-cols .panes > div", {
		effect: 'fade',  
		rotate: true,  
		onBeforeClick: function(event, i) {
	
			// get the pane to be opened
			var pane = this.getPanes().eq(i);
	
			// only load once. remove the if ( ... ){ } clause if you want the page to be loaded every time
			if (pane.is(":empty")) {
				// load it with a page specified in the tab's href attribute 
				pane.html('<div class="loader"><i></i><span>pobieranie ofert...</span></div>');
				pane.load(this.getTabs().eq(i).attr("href"));
			}
		}
	});	
	

	/**
	 * Zakładki pod ofertą
	 * @requires JQuery Tools
	 */	
	$("#offer-tabs .tabs").tabs('#offer-tabs .panes > div', { 
		tabs: 'li',
		effect: 'fade',
		onBeforeClick: function(event, i) {
	
			// get the pane to be opened
			var pane = this.getPanes().eq(i);
			pane.type = pane.hasClass('pane_photos') ? 'photos' : pane.hasClass('pane_reviews') ? 'reviews' : pane.hasClass('pane_map') ? 'map' : null;
			if (pane.type) pane.data('type',pane.type);
			
			// AJAX
			// only load once. remove the if ( ... ){ } clause if you want the page to be loaded every time
			if (pane.is(':empty')) {
				pane.html('<div class="loader"><i></i><span>wczytywanie...</span></div>');
				pane.load(this.getTabs().eq(i).find('a').attr("href"), function () {

					/*
					// podzakładki, sposób 1:
					if (pane.type === 'photos') {
						pane.append('<div class="loader"><i></i><span>wczytywanie...</span></div>');
						$.getScript(site_cfg.url.js+'/jquery.colorbox-min.js',function(){
							pane.find('.loader').remove();
							$(".pane_photos .pager").tabs(".pane_photos .data > .list", {
								effect: 'fade',  
								rotate: true,  
								onBeforeClick: function(event, i) {
									// get the pane to be opened
									var pane = this.getPanes().eq(i);

									// only load once. remove the if ( ... ){ } clause if you want the page to be loaded every time
									if (pane.is(":empty")) {
										// load it with a page specified in the tab's href attribute 
										//pane.html('<div class="loader"><i><img src="'+site_cfg.url.images+'ajax-loader.gif" /></i><span>wczytywanie...</span></div>');
										pane.html('<div class="loader"><i></i><span>wczytywanie...</span></div>');
										pane.load(this.getTabs().eq(i).attr("href"), function(){
											$(".pane_photos a[rel='hotelgallery']").colorbox({transition:"fade"});
										});
									}
								} 		
							});
						});
					}
					*/ 

					// podzakładki, sposób 2: 
					if (pane.type === 'photos') {
						pane.append('<div class="loader"><i></i><span>wczytywanie...</span></div>');
					
						$.getScript(site_cfg.url.js+'jquery/colorbox-min.js',function(){
							pane.find('.loader').remove();
							$(".pane_photos a[rel='hotelgallery']").colorbox({transition:"fade"});
							$('.pane_photos').delegate('.pager a', 'click', function(){
								var href = $(this).attr('href');
								pane.html('<div class="loader"><i></i><span>wczytywanie...</span></div>');
								pane.load(href, function(){                  
									$(".pane_photos a[rel='hotelgallery']").colorbox({transition:"fade"});                  
								})
								return false      
							})
						});
					}
					else if (pane.type === 'reviews') {
						$('.pane_reviews').delegate('.pager a', 'click', function(){
							var href = $(this).attr('href');
							pane.html('<div class="loader"><i></i><span>wczytywanie...</span></div>');
							pane.load(href, function(){

							})
							return false      
						})
					}
					else if (pane.type === 'map') {
						initialize()
					}
					
				});
			} // pane.is(':empty') 
			else {
				switch (pane.type) {
					case 'photos' : 
						pane.append('<div class="loader"><i></i><span>wczytywanie...</span></div>');
					
						$.getScript(site_cfg.url.js+'jquery/colorbox-min.js',function(){
							pane.find('.loader').remove();
							$(".pane_photos a[rel='hotelgallery']").colorbox({transition:"fade"});
							$('.pane_photos').delegate('.pager a', 'click', function(){
								var href = $(this).attr('href');
								pane.html('<div class="loader"><i></i><span>wczytywanie...</span></div>');
								pane.load(href, function(){                  
									$(".pane_photos a[rel='hotelgallery']").colorbox({transition:"fade"});                  
								})
								return false      
							})
						});
					break
					case 'reviews' :
						$('.pane_reviews').delegate('.pager a', 'click', function(){
							var href = $(this).attr('href');
							pane.html('<div class="loader"><i></i><span>wczytywanie...</span></div>');
							pane.load(href, function(){

							})
							return false      
						})
					break
				}
			} // !pane.is(':empty') 
		},
		onClick: function (e, i) {
			var pane = this.getPanes().eq(i);
			if (pane.data('type') === 'map') { 
				initialize()
			};
		}
	} );

	
	/**
	 * In-field label
	 */
	$(':input[title]').each(function() {
		var $this = $(this);
		if($this.val() === '') {
			$this.val($this.attr('title'));
		}
		$this.focus(function() {
			if($this.val() === $this.attr('title')) {
				$this.val('');
			}
		});
		$this.blur(function() {
			if($this.val() === '') {
				$this.val($this.attr('title'));
			}
		});
	});	
	
	
	/**
	 * Konfigurator oferty
	 * @required 
	 */


	/**
	 * Obsługa tabelki z uczestnikami wyjazdu
	 */
	(function() {
		var
			min = $('#participants-min_num').html(),
			max = $('#participants-max_num').html(),
			$people = $('#offer-bookingform #participants'),
			$tpl_row = $people.find('> li.template')
		;
		
		$tpl_row.removeClass('template').detach();
		
		var num = $people.children(":not('.template')").length;
		if (num < min || num == 0) {
			$tpl_row.clone().appendTo($people)
		}
		
		$people
		.delegate('.btn-add', 'click', function () {
			if ($people.children().length < max) {
				$tpl_row.clone().hide().appendTo($people).fadeIn();
			} else {
				alert('Dodano maksymalną ilość osób.')
			}
			return false
		})
		.delegate('.btn-del', 'click', function () { 
			if ($people.children().length > min) { 
				$(this).closest('li').fadeOut().remove()
			}
			return false
		});
		
	})(); 
	/**/	 

	
	/**
	 * Tooltip
	 *  
	 */
	$('.offers-list .from .more a').tooltip({
		// tweak the position
		offset: [10, 2],
		effect: 'slide'
	}).dynamic({ bottom: { direction: 'down', bounce: true } });
	
	$('.has-tooltip').tooltip({
		// tweak the position
		//offset: [10, 2]
	})
	
	
	/**
	 * Lightbox
	 * @required jquery.colorbox
	 */
	if ( typeof($.fn.colorbox) === 'function' ) {
		$('div.product .thumb a').colorbox();
	}
	

	/* Aktywacja przeglądarki zdjęć */
	$('.picviewer').picViewer({time:false});
	

	/**
	 * Pseudo ukrywanie 
	 */
	$('.fauxshowhide-toggler a').live('click', function () {
		$(this).parent('.fauxshowhide-toggler').toggleClass('fauxshowhide-toggler-collapsed');
		$($(this).attr('href')).toggleClass('fauxshowhide-content-collapsed');
		return false
	} );
	
	
	/**
	 * Klikalne obszary
	 */	
	$('.weather-days li.city .h').clicky();
	
	
	/**
	 * Ola kręci
	 */	
	/*
	$('p#staff').toggle(function () {
		var $el = $('#logo .logo');
		var t = 0,
		deg;
		setInterval(function () {
			t++;
			deg = (t*t)/5;
			//console.log(t*t);
			(deg < 720) ? $el.css({'-moz-transform':'rotate('+deg+'deg)'}) : $el.css({'-moz-transform':'rotate(0.0deg)'})
		}, 30)
		
	}, function () {  
		$el.css({'-moz-transform':'rotate(0.0deg)'})
	});
	*/
	
	
}) // Document ready
/* ************************************************ */


if (typeof(site_cfg) === 'undefined') var site_cfg = {};
/* do rozszerzania config'a można też użyć narzedzia: $.extend(config, nowe, nowe, ...); */

site_cfg.lang = {
	zwin: 'zwiń',
	poprzednie: 'poprzednie',
	nastepne: 'następne'
}

function number_format (number, decimals, dec_point, thousands_sep) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // +      input by: Amirouche
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    // *    example 13: number_format('1 000,50', 2, '.', ' ');
    // *    returns 13: '100 050.00'
    // Strip all characters but numerical ones.
    number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}


