(function($) {
	$.fn.fontResizer = function(settings) {
		var config = {
			attachTo: null,	
			sizes: [13, 15, 18.5]		
		};
		var settings = $.extend(config, settings); 
		
		this.each(function() {
			var self = $('.text', this).first();				 
			
			//Inicjalizacja			
			var incSize = $('a[href=#inc-font-size]', this);
			var decSize = $('a[href=#dec-font-size]', this);
			var resetSize = $('a[href=#reset-font-size]', this);
			
			incSize.click(function() {
				self.css('font-size', settings.sizes[2]);					
				return false;
			});
			decSize.click(function() {				
				self.css('font-size', settings.sizes[0]);	
				return false;
			});
			resetSize.click(function() {
				self.css('font-size', settings.sizes[1]);
				return false;
			});
		});
		return this;
	};	
}) (jQuery);

var flow = null;

function initCategoriesTree() {
	$('#categories-tree li').each(function() {
		if(!$('> ul', this).size()) {
			return ;			
		}	
		
		if($('> ul', this).first().children().size() > 0)
		{		
			// Tworzymy przycisk "zwin/rozwin"
			var expandBtn = $('<a>', { 
				'class' : 'expander' 
			});
			expandBtn.click(function() {
				var self = $(this);
				if (self.text() == '-') {
					self.parent().parent().children('ul').slideUp('fast', function() {
						self.text('+');					
					});				
				}
				else {
					self.parent().parent().children('ul').slideDown('fast', function() {
						self.text('-');					
					});
				}	
			});
			
			// Markup
			$(' > a', this).wrap('<div></div>');
			
			$('> div', this).prepend(expandBtn);
			
			if (!$(this).hasClass('selected')) {
				expandBtn.text('+');
				$('ul', this).css({'display' : 'none'});
			}		
			else
				expandBtn.text('-');
		}
	});
	$('#categories-tree li:first-child a.expander').click();
}

function initTabs(selector) {
	if(!selector)
		selector = $('.tabs');
	selector.each(function() {
		var tabs = $(this);
		
		$('> div:not(:first)', tabs).hide();
		$('> ul li', tabs).removeClass('active');
		$('> ul li:first', tabs).addClass('active');
		
		$('> ul li a', tabs).click(function() {
			$('> ul li.active', tabs).removeClass('active');						
			var li = $(this).parent().addClass('active');									
						
			var tabId = $(this).attr('href');
			var active = document.getElementById(tabId);
			
			var index = $('> ul li', tabs).index(li);	
			$('> div', tabs).hide();
			
			$(active).fadeIn(function() {
				tabs.trigger('tabChanged', active);
			});			
			
			return false;
		});
	}).bind('tabChanged', function(tabs, active) {		
		if(flow && !$.browser.msie) {						
			flow.resize();
		}	
	});
}

function initSliders() {
	$('.slider').each(function() {
		var slider = $(this),
			li = $('li', slider);
		
		$('li', slider).eq(0).addClass('active');
						
		function nextSlide() {
			try {			
				var c 		= $('li.active', slider);
				var cId 	= 'img#' + $('> h2 a', c).attr('id');
				var index 	= li.index(c);						
				
				if(index + 1 < li.size())
					index++;
				else
					index = 0; 
				var nId = 'img#' + li.eq(index).children('h2').children('a').attr('id');						
				
				c.removeClass('active');			
				li.eq(index).addClass('active');
				
				$('img', slider).stop(false, true);
				if($(nId, slider).size() > 0) {				
					$('img', slider).hide();
					$(nId, slider).fadeIn();
				}
				else {				
					li.eq(index).css('background', 'none');
				}
			}
			catch (e) {}
		}
		
		var interval = setInterval(nextSlide, 5000);
				
		li.hover(function() {
			clearInterval(interval);						
			$('img', slider).stop(false, true);
			
			var current  	= $('li.active', slider); 
			var next 		= $(this);						
			var nextImg		= $('img#' + $('> h2 a', next).attr('id'), slider);
			
			next.addClass('active');
			current.removeClass('active');			
			
			$('img', slider).stop(false, true);
			if(nextImg.size() > 0) {
				$('img', slider).hide();															
				nextImg.fadeIn();
			}
			else {				
				li.eq(index).css('background', 'none');
			}			
		}, function () {
			interval = setInterval(nextSlide, 5000);
		});
	});
}

function initAccordions() {
	$('.accordion').each(function() {
		var self = this;
		$('> h4', self).click(function() {									
			var index  = $('> h4', self).index(this); 			
			var active = $('> div', self).eq(index); 			
			
			$('> h4', self).removeClass('active');
			$('> div', self).not(active).slideUp('fast');
			
			
			$('> h4', self).eq(index).addClass('active');
			active.slideDown('fast');
		}).eq(0).click(); 
	});
}

function initExpander() {
	$('.expander').each(function() {
		var self = $(this);		
		$('> h4', self).addClass('active').click(function() {
			var content = $('> div.widget-content', self);			
			content.slideToggle();
			$('> h4', self).toggleClass('active');
		});
	});
}

function IEFixes() {
	if($.browser.msie) {
		$('input').each(function() {
			var type = $(this).attr('type');
			$(this).addClass(type);
		});
		
		$('input[type=checkbox] + label').addClass('inline');
		
		$('.horizontal-menu:first-child li:last-child').css({
			background: 'none'
		});
		
		$('.details .row:odd').add('odd');
	}
}

function initSearchAutoComplete(field)
{
	if(!$(field).autocomplete)
		return ;
	$(field).autocomplete({		
			source: function(request, response) {
			var type = $('input[name=type]:selected').val();
			$.ajax({
				url: url.site('search/autocomplete/'),
				data: request,
				dataType: 'json',
				success: function(data) {
					response(data);
				}
			});
		},
		dataType: 'jsonp'		
	});
}

$(document).ready(function() {
	initCategoriesTree();
	initTabs();
	initSliders();
	initExpander();
	initSearchAutoComplete($('input[name=query]'));
	
	$('#article').fontResizer();
	$('#profile-page').fontResizer();
	$('#product-desc').fontResizer();
	
	$('.date-picker').each(function() {
		var field = $(this);
		field.DatePicker({
			format: 'Y-m-d',
			date: field.val(),
			current: field.val(),
			onBeforeShow: function() {
				if(field.val())
					field.DatePickerSetDate(field.val(), true);
			},
			onChange: function(formated, dates){
				field.val(formated);
				field.DatePickerHide();
			},
			locale: {
				days: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota", "Niedziela"],
				daysShort: ["Nd.", "Pn.", "Wt.", "Śr.", "Czw.", "Pt.", "Sob.", "Nd."],
				daysMin: ["Nd", "Pn", "Wt", "Śr", "Cz", "Pt", "So", "Nd"],
				months: ["Styczeń", "Luty", "Marzec", "Kwiecień", "Maj", "Czerwiec", "Lipiec", "Sierpień", "Wrzesień", "Październik", "Listopad", "Grudzień"],
				monthsShort: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"],
				weekMin: ' '
			}			
		});
	});
		
	if($.fn.tinyTips)
		$('acronym').add('.show-tinytip').tinyTips('title');
	

	if($("a[rel^='prettyPhoto']").prettyPhoto)
		$("a[rel^='prettyPhoto']").prettyPhoto();
	
	if($('#photo-gallery').size()) {
		flow = new ContentFlow('photo-gallery', {
			maxItemHeight: 180,
			reflectionHeight: 0,
			circularFlow: false,
			endOpacity: 1
		});	
	}	
	
	/**
	 * Podpowiadanie zapytania do wyszukiwarki
	 */
	var search = null;
	if(search = $('#main-search')) {
		$('input', search).focus(function() {
			if($(this).val() == 'Szukaj...')
				$(this).val('');
		}).blur(function() {
			if(!$(this).val())	
				$(this).val('Szukaj...');
		});
		search.submit(function() {
			window.location = url.site('search#query='+$('input[name=query]', search).val()+'&type=all');
			return false;
		});
	}
	
	/** Ocenianie **/
	var rating = $('#rating-form');
	if(rating && $(rating).ratings) {
		// Aktualna ocen 
		var initial = parseFloat($('input[type=hidden]', rating).val());
		if(!initial) initial = 3;		
		var action = $(rating).attr('action');
		// Zastępujemy formularz gwiazdkami
		$(rating).children().remove();		
		$(rating).ratings(6, initial)
			.bind("ratingchanged", function (e, data) 
			{			
				$.post(action, { rating: data.rating }, function() 
				{
					$(rating).html('<span><b>Dziękuemy za ocenę!</b></span>');
				});
			});
	}	
	
	IEFixes();
});
