$(document).ready(function () {
	
	$('.info .close').css({'cursor':'pointer'}).click(function () {
		$(this).parents('.info').hide(300);
	});
	
	$('.error.active').click(function () {$(this).remove();});

//	if (jQuery.browser.msie && jQuery.browser.version > 7 && jQuery.browser.version < 9 ) $('.easter-contest .cutter').css('overflow', 'auto !important');

	
});

var addFrame = function(url) {
	
	var frame = '<iframe src="' + url + '" style="visibility:hidden" width="1" height="1" frameborder="0"></iframe>';
	$('body').append(frame);
};

(function( $ ){

var Slider = function (slideList) {
	
	var th = this;
	
	this.fixSlider = function () {
		
		var elemsNumber = this.elems.lists.eq(0).find('li').size();
		this.length = Math.ceil(elemsNumber / this.perPosition);
		
		var width = this.elemWidth * (this.length * this.perPosition);
		this.elems.slider.width(width);
		
		if (this.loadingNewPosition) {
			this.elems.slider.addClass('loading');
			this.elems.slider.find('.ajax-load').show();
			this.length = this.length + 1;
			this.elems.slider.css('padding-right', (this.elemWidth * this.perPosition) + 'px');
		} else {
			this.elems.slider.removeClass('loading');
			this.elems.slider.find('.ajax-load').hide();
			this.elems.slider.css('padding-right', 0);
		}
		
		if (this.position > this.length - 1) {
			this.gotoPosition(this.length - 1);
		}
		
		this.fixArrows();
		
	};

	this.fixArrows = function () {
		
		if (this.position == 0) {
			this.elems.larr.addClass('inactive');
		} else {
			this.elems.larr.removeClass('inactive');
		}
		
		if (this.position == (this.length - 1)) {
			this.elems.rarr.addClass('inactive');
		} else {
			this.elems.rarr.removeClass('inactive');
		}
		
	};

	this.perPosition = 6;
	this.useAjax = true;
	this.ajaxUrlTemplate = null;
	this.elemWidth = 0;
	this.length = 0;
	this.position = 0;
	this.positionGap = 2;

	this.gotoPosition = function (newPosition) {
		
		if (newPosition < 0) newPosition = 0;
		if (newPosition > this.length - 1) newPosition = this.length - 1;
		
		var left = this.elemWidth * this.perPosition * newPosition;
		
		this.elems.slider.stop().animate({left : '-' + left + 'px'});
		
		this.position = newPosition;
		
		if (this.useAjax) {
			if (newPosition >= this.length - this.positionGap - 1) {
				this.startLoadingNewPosition();
			}
		}
		
		this.fixArrows();
	};

	this.loadingNewPosition = false;

	this.startLoadingNewPosition = function () {
		
		if (this.loadingNewPosition) return;
		
		this.loadingNewPosition = true;
		this.useAjax = false;
		
		var newPosition = this.length + 1;
		
		var url = this.ajaxUrlTemplate.replace('{page}', newPosition);
		
		var th = this;
		
		$.ajax({
			url : url,
			success : function (data) {
				th.loadNewPosition(data);
			},
			error : function () {
				th.unloadNewPosition();
			}
		});
		
		this.fixSlider();
		
	};

	this.loadNewPosition = function (data) {
		var th = this;
		this.loadingNewPosition = false;
		data = $(data);
		if (data.attr('data-all-elems') != '1') this.useAjax = true;
		
		data.find('ul').each(function (i) {
			var ul = $(this);
			th.elems.lists.eq(i).append(ul.find('li'));
			
		});
		
		this.fixSlider();
		
		if (this.useAjax) {
			if (this.position >= this.length - this.positionGap - 1) {
				this.startLoadingNewPosition();
			}
		}

	};

	this.unloadNewPosition = function () {
		
		this.loadingNewPosition = false;
		this.useAjax = true;

		this.fixSlider();
		
	};

	this.left = function () {
		if (this.position > 0) {
			this.gotoPosition(this.position - 1);
		}
	};

	this.right = function () {
		if (this.position < this.length - 1) {
			this.gotoPosition(this.position + 1);
		}
	};

	this.elems = {};
	
	this.elems.container = slideList;
	this.elems.slider = slideList.find('.slide-slider');
	this.elems.lists = this.elems.slider.find('ul');
	this.elems.rarr = $(slideList).find('.slide-rarr');
	this.elems.larr = $(slideList).find('.slide-larr');
	
	this.ajaxUrlTemplate = slideList.attr('data-ajax-url');
	
	if (slideList.attr('data-all-elems') == '1' || !this.ajaxUrlTemplate) {
		this.useAjax = false;
	}
	
	var oneElem = this.elems.lists.eq(0).find('li').eq(0);
	this.elemWidth = oneElem.outerWidth(true);
	
	var cuterWidth = slideList.find('.slide-cuter').width();
	this.perPosition = Math.floor((cuterWidth + (parseInt(oneElem.css('margin-right')) || 0)) / this.elemWidth);
	
	this.elems.rarr.click(function (e) {
		e.preventDefault();
		th.right();
	});
	
	this.elems.larr.click(function (e) {
		e.preventDefault();
		th.left();
	});
	
	th.fixSlider();
	th.fixArrows();
	
};


$.fn.slider = function() {
	
	this.each(function () {
		
		$(this).data('slider', new Slider($(this)));
		
	});
	
	return this;

};
})( jQuery );


var cardsVisuals = {
	counter : 0, 
	init : function () {
		this.flashIt($('img.card-visual'));
	},
	flashIt : function (imgs) {
		var th = this;
		imgs.each(function () {
			
			th.counter++;
			
			var img = $(this);
			if (img.data('flashed')) return;
			
			var width = img.attr('width') || 230;
			var height = img.attr('height') || 162;
			var src = img.attr('src');
			var type = img.attr('data-type');
			
			img.css('display', 'none');
			
			var id = 'card-visual-' + th.counter;
			
			var div = $('<div></div>');
			div.attr('id', id).insertAfter(img);
			
			var attributes = {};
			var flashvars = {};
			flashvars.pattern = src;
			flashvars.type = type;
			var params = {};
			params.scale =  "noscale";
			//params.bgcolor = "#FFFFFF";
			params.allowScriptAccess = "sameDomain";
			params.wmode = "transparent";
			
			//console.log(baseUrl + "swf/EasterCard.swf", id, width, height);
			
			swfobject.embedSWF ( baseUrl + "swf/EasterCard.swf", id, width, height, "10.0.0", "", flashvars, params, attributes );
			
		});
	}
};

$(document).ready(function() {
    
	$('.ap').height($(document).height());
	
	
	if ($.browser.opera) {
		
		var cutter = $('.easter-contest .cutter');
		
		cutter.css('overflow', 'visible');
		
		var shadow = $('#menu .menu-gradient');
		shadow.hide();
		
	}
	/*if ($.browser.opera) {
	
		var cutter = $('.easter-contest .cutter');
		
		cutter.css('overflow', 'hidden');
		
		var cutterHeight = cutter.height();
		
		var messages = $('.message.active');
		
		messages.each(function () {
			cutterHeight = cutterHeight - $(this).outerHeight(true);
		});
	
		alert(cutterHeight);
		
		var fixCutter = function () { 
		
			if (cutter) {
				
				if (cutterHeight < $(window).height()) {
					cutter.height($(window).height());
				} else {
					cutter.height(cutterHeight);
				}
				
			}
		};
		
		fixCutter();
	
		$(window).resize(function() {
			fixCutter();
		});
	
	}*/
	
	$('.slide-list').slider();
    
    if ($.colorbox) {
    	
    	var messages = $('.messages.active');
	    $('.messages .btn-message-x, .messages .btn-x').click(function (e) {
	    	e.preventDefault();
	    	$.colorbox.close();
	    });
	    
	    $(document).bind('cbox_load', function(){
	    	$('#cboxClose').remove();
	    });
	    
	    $(document).bind('cbox_cleanup', function(){
	        $('.messages.active').removeClass('active');
	    });
	    
	    if (messages.size() == 1) {
	    	//setTimeout(function() {$.colorbox({inline: true, href: '.messages.active', overlayClose: false});}, 10);

		    if (jQuery.browser.msie && jQuery.browser.version < 8) {
				$('.messages.active').colorbox({overlayClose: false});
			}
			else {
				$.colorbox({inline: true, href: '.messages.active', overlayClose: false});
			}
	    }
    }
    
    var shareMessage = $('.message-podziel-sie-kanapka');
    
    if (shareMessage.size() == 1) {
    	shareMessage.find('input').focus(function (e) {e.preventDefault();this.select();});
	    $('.btn-podziel-sie').click(function(e) {
	    	e.preventDefault();
	    		
			shareMessage.addClass('active');
			$.colorbox({inline: true, href: '.message-podziel-sie-kanapka', overlayClose: false});
	    	
	    });
	}
    
    var commonShareMessage = $('.message-podziel-sie');
    
    if (commonShareMessage.size() == 1) {
    	commonShareMessage.find('input').focus(function (e) {e.preventDefault();this.select();});
	    $('.btn-podziel-sie').click(function(e) {
	    	e.preventDefault();
	    		
			commonShareMessage.addClass('active');
			$.colorbox({inline: true, href: '.message-podziel-sie', overlayClose: false});
	    	
	    });
	}
        
    $('.box-changer-front').click(function() {
        $('.box-slider').animate({'left':'0px'});
        return false;
    });
    $('.box-changer-top').click(function() {
        $('.box-slider').animate({'left':'-445px'});
        return false;
    });
    $('.box-changer-side').click(function() {
        $('.box-slider').animate({'left':'-890px'});
        return false;
    });
    
    
    var recipeCategories = {};
    
    recipeCategories.elements = null;
    recipeCategories.init = function () {
    	
    	var th = this;
    	
    	this.elements = $('.recipe-categories');
    	this.elements.children('span').click(function (e) {
    		e.preventDefault(); 
    		th.openList($(this).parent());
    	});
    	
    	var lists = this.elements.find('ul');
    	lists.mouseenter(function () {
    		th.mouseInList = true;
    	});
    	
    	lists.mouseleave(function () {
    		th.mouseInList = false;
    		if (th.delayedCloseTimeout) clearTimeout(th.delayedCloseTimeout);
    		th.delayedCloseTimeout = setTimeout(function () {th.delayedCloseList();}, 750);
    	});
    	
    	var labels = lists.find('label').click(function (e) {
    		e.preventDefault();
    		e.stopPropagation();
    		th.select($(this));
    	});
    };
    
    recipeCategories.select = function (label) {
    	
    	recipeCategories.currentCategory.children('span').text(label.text());
    	recipeCategories.currentCategory.find('input').attr('checked', false);
    	var input = label.find('input');
        input.attr('checked', true);
    	this.closeList();
    	
    };
    
    recipeCategories.currentCategory = null;
    
    recipeCategories.mouseInList = false;
    
    recipeCategories.openList = function (category) {
    	this.closeLists();
    	this.currentCategory = category;
    	this.currentCategory.find('ul').show();
    	this.currentCategory.addClass('active');
    	this.mouseInList = true;
    };
    
    recipeCategories.delayedCloseTimeout = null;
    
    recipeCategories.delayedCloseList = function () {
    	if (!this.mouseInList) {
    		this.closeList();
    	}
    };
    
    recipeCategories.closeList = function () {
    	if (!this.currentCategory) return;
    	this.currentCategory.find('ul').hide();
    	this.currentCategory.removeClass('active');
    	this.currentCategory = null;
    	this.mouseInList = false;
    };
    
    recipeCategories.closeLists = function () {
    	this.elements.find('ul').hide();
    	this.elements.removeClass('active');
    	this.currentCategory = null;
    	this.mouseInList = false;
    };
    
    recipeCategories.init();
    
   
    
    cardsVisuals.init();

    
    var stat = function () {
    	
    	if (typeof(pageTracker) == 'undefined') return;
    	
    	var menuTitles = ['Produkty', 'Przepisy', 'Konkurs', 'Odżywianie', 'Kontakt', 'Ekologia', 'Reklamy'];
    	
    	$.each(menuTitles, function () {
    		var title = this;
    		$('ul.navigation a[title="' + title + '"]').click(function () {pageTracker._trackEvent('Menu', title);});
    	});
    	
    	$('.ta_cards_contest .btn-pokoloruj-kartke').click(function () {pageTracker._trackEvent('w11_Strona_konkursu_kartkowego', 'Koloruj');});
    	$('.ta_cards_contest .send-from-fb .send').click(function () {pageTracker._trackEvent('w11_Strona_konkursu_kartkowego', 'Wyslij kartke znajomym');});
    	
    	$('.ta_home .btn-pokoloruj-kartke').click(function () {pageTracker._trackEvent('Strona_glowna', 'Koloruj');});
    	$('.ta_home .send-from-fb .send').click(function () {pageTracker._trackEvent('Strona_glowna', 'Wyslij kartke znajomym');});
    	$('.ta_home .home-names a').click(function () {pageTracker._trackEvent('Strona_glowna', 'Lece na fejsa zeby wziac udzial - imiona kanapek');});
    	
    	$('.ta_cards_gallery .send-from-fb .send').click(function () {pageTracker._trackEvent('w11_galeria_kartek', 'Wyslij kartke znajomym');});
    	
    	$('.ta_card .btn-pokaz-kartke-znajomym').click(function () {pageTracker._trackEvent('wk11_strona_jednej_kartki', 'Pochwal sie kartka');});
    	$('.ta_card .send-from-fb .send').click(function () {pageTracker._trackEvent('wk11_strona_jednej_kartki', 'Wyslij kartke znajomym');});
    	$('.ta_card .send-from-fb .send').click(function () {pageTracker._trackEvent('wk11_strona_jednej_kartki', 'Wyslij kartke znajomym');});
    	
    	$('.easter-contest .message-extra .btn-x').click(function () {pageTracker._trackEvent('wk11_thank_you_page', 'zamknij');});
    	$('.easter-contest .message-extra input.link').click(function () {pageTracker._trackEvent('wk11_thank_you_page', 'link do kanapki klikniecie');});
    	$('.ta_card .btn-sprobuj-jeszcze-raz').click(function () {pageTracker._trackEvent('wk11_thank_you_page', 'sprobuj jescze raz');});
    	
    	$('.ta_home .facebook-feed .next').click(function () {pageTracker._trackEvent('Strona_glowna', 'Facebook feed', 'starsza notka', 0);});
    	$('.ta_home .facebook-feed .prev').click(function () {pageTracker._trackEvent('Strona_glowna', 'Facebook feed', 'nowsza notka', 0);});
    	$('.ta_home .home-crumbs .btn-biore-udzial').click(function () {pageTracker._trackEvent('klikniecie_banner_OkrPamieci_hellmanns_pl', 'kliknal');});
    	
    };
    
    stat();
    
    var facebookFeed = {
    	position: 0,
    	list: null,
    	prev: null,
    	next: null,
    	itemWidth: 0,
    	itemsCount: 0,
    	init: function () {
    		
    		var feedContainer = $('.facebook-feed');
    	
    		if (feedContainer.size() < 1) return;
    			
    		var cutter = feedContainer.find('.cutter');
    		cutter.css({position: 'relative', overflow: 'hidden'});
    		
    		this.list = feedContainer.find('ul');
    		this.list.css({position: 'absolute', left: 0, top: 0});
    			
    		var th = this;
    		
    		var items = this.list.find('li');
    		this.itemsCount = items.size();
    		this.itemWidth = parseInt(items.eq(0).outerWidth(true), 10) || 0;
    		this.list.width(this.itemsCount * this.itemWidth);
    		this.loadItems();
    		
    		this.next = feedContainer.find('.next');
    		this.next.css({cursor: 'pointer'});
    		
    		this.next.click(function (e) {
    			e.preventDefault();
    			th.gotoPosition(th.position + 1);
    		});
    		
    		this.prev = feedContainer.find('.prev');
    		this.prev.css({cursor: 'pointer'});
    		
    		this.prev.click(function (e) {
    			e.preventDefault();
    			th.gotoPosition(th.position - 1);
    		});
    		
    	},
    	gotoPosition: function(position) {
    		
    		if (position >= this.itemsCount) position = this.itemsCount - 1;
    		if (position < 0) position = 0;
    		
    		if (position == this.position) return;
    		
    		if (position >= this.itemsCount - 1) {
    			this.next.hide();
    		} else {
    			this.next.show();
    		}
    		
    		if (position == 0) {
    			this.prev.hide();
    		} else {
    			this.prev.show();
    		}
    		
    		this.list.stop();
    		this.position = position;
    		this.list.animate({left: (-position * this.itemWidth) + 'px'}, 350);
    	},
    	loadItems : function () {
    		var th = this;
    		$.ajax({
    			url: baseUrl + 'content/facebookfeed',
    			success: function (data) {
    				var itemsHtml = '';
    				$.each(data, function () {
    					var itemData = this;
    					var itemHtml = '';
    					var templ;
    					
    					var photoTemplate = 'photo';
    					var headerTemplate = 'header';
    					
    					
    					
    					if (typeof(itemData.link) !== 'undefined') {
    						var photoTemplate = 'photoLink';
        					var headerTemplate = 'headerLink';
    					}
    					
    					if (typeof(itemData.photo) !== 'undefined') {
    						templ = th.templates[photoTemplate];
    						
    						$.each(itemData, function (index, val) {
        						templ = templ.replace('{' + index + '}', val);
        					});
    						
    						itemHtml = itemHtml + templ;
    					}
    					
    					if (typeof(itemData.name) !== 'undefined') {
    						templ = th.templates[headerTemplate];
    						
    						$.each(itemData, function (index, val) {
        						templ = templ.replace('{' + index + '}', val);
        					});
    						
    						itemHtml = itemHtml + templ;
    					}
    					
    					templ = th.templates['message'];
						
						$.each(itemData, function (index, val) {
    						templ = templ.replace('{' + index + '}', val);
    					});
						
						itemHtml = itemHtml + templ;
						
						itemHtml = th.templates.wrapper.replace('{content}', itemHtml);
    					
    					itemsHtml = itemsHtml + itemHtml;
    				});
    				th.list.html(itemsHtml);
    				
    				cufonize('.facebook-feed .stymie');
    				
    				var items = th.list.find('li');
    	    		th.itemsCount = items.size();
    	    		th.itemWidth = parseInt(items.eq(0).outerWidth(true), 10) || 0;
    	    		th.list.width(th.itemsCount * th.itemWidth);
    	    		
    	    		th.prev.hide();
    	    		
    	    		if (th.itemsCount == 0) {
    	    			th.next.hide();
    	    		}
    	    		
    	    		th.position = 0;
    	    		
    			},
    			dataType: 'json'
    		});
    		
    	},
    	templates: {
    		header: '<p class="name stymie">{name}</p>',
    		photo: '<p class="img"><img alt="{name}" src="{photo}"></p>',
    		headerLink: '<p class="name stymie"><a href="{link}" target="_blank">{name}</a></p>',
    		photoLink: '<p class="img"><a href="{link}" target="_blank"><img alt="{name}" src="{photo}"></a></p>',
    		message: '<p>{message}</p><p class="time">{date}</p>',
    		wrapper: '<li><div class="vc">{content}</div></li>'
    	}
    };
    
    facebookFeed.init();
    
});


