/* Scripts */
var regEmail = /^.+\@.+\..+$/;
var gallery_i = 0;

$(document).ready(function(){
	// navi
	$('#navi > li').not('.active').hover(
		function(){
			$(this).children('a').stop().animate({
				backgroundPosition:"(50% 0px)"},{duration:300,
				complete: function(){
					if($(this).parent().find('ul').length>0){
						$(this).parent().find('ul').fadeIn(100);
						$('#navi > li.active ul').fadeOut(100);
					}
				}
			});
		},
		function(){
			$(this).children('a').stop().animate({backgroundPosition:"(50% -84px)"},{duration:200});
			if($(this).find('ul').length>0){
				$(this).find('ul').fadeOut(100);
				$('#navi > li.active ul').fadeIn(100);
			}
		}
	);
	
	// new window
	$('a.new-window').click(function(){
		window.open(this.href);
		return false;
	});
	
	// pulse links
	$('#logo, .boxes a, .brands a img, .view-products .image a').mouseover(function(){
		$(this).fadeTo(200, 0.5).fadeTo(400, 1);
	});
	
	// slider
	$('.slider').slider();
	
	// invitations
	invitations();
	
	// comments
	comments();
	
	// photos
	photos();
	
	// team zone
	teamzone();
	
	// news
	news();
	
	// fancybox
	$('.preview-image').fancybox({
		'centerOnScroll'	: true,
		'overlayColor'		: '#000',
		'overlayOpacity'	: 0.7,
		'titleShow'			: false
	});
});


function invitations(){
	$(".invitation-link").click(function(){
		var url = $(this).attr("href");
		var id = $(this).attr("id").split("_")[1];
		$("#invitation-dialog_" + id).fadeToggle();
		$("#invitation-dialog_" + id + " form input[name=url]").val(url);
		return false;
	});
	
    $(".invitation-dialog form").submit(function(event){
    	event.preventDefault();
    	
		var form = $(this);
		var dialog = form.parent(".invitation-dialog");
		var id = dialog.attr("id").split("_")[1];
		var linkElement = $("#invitation-link_" + id);
		var action = form.attr("action");
		var url = form.find("input[name=url]");
		var email = form.find("input[name=friend_email]");
		var status = dialog.find('.status');
		
		status.html('<img src="/site_media/nowa/loader.gif" alt="" /> Wysyłanie...');
		status.fadeIn();
		
		if(!regEmail.test(email.val())){
			status.hide().html("Popraw adres e-mail!").fadeIn();
			return false;
		}
		
		$.post(action, {
			url: url.val(),
			friend_email: email.val()
		}, function(data, textStatus){
			status.hide();
			if(textStatus == "success"){
				status.html("Wysłano pomyślnie!");
				email.val('');
			} else
				status.html("Popraw błędy!");
			status.fadeIn();
		});
    });
};

function comments(){
	$("a.comments-link").click(function(event) {
		event.preventDefault();
		var commentsPart = $(this).parent().parent().find(".comments-part");
		
		if( commentsPart.children().length !== 0 ){
			commentsPart.html("");
		} else {
			var url = commentsPart.attr("id");
			commentsPart.html('<p><img src="/site_media/nowa/loader.gif" alt="" /></p>');
			$.get(url, {},
				function(data){
					commentsPart.html(data);
					commentForm(commentsPart.find('form'));
					$(".delete-comment-link").click(commentDelete);
            	}
            )
        }
	});
}

function commentForm(form){
	form.submit(function(){
		var form = $(this);
		var commentsPart = form.parents(".comments-part");
		var status = form.find('.status');
		var name = form.find('input[name=name]');
		var comment = form.find('textarea[name=comment]');
		var valid = 0;
		
		form.find('.error').removeClass('error');
		
		status.html('<img src="/site_media/nowa/loader.gif" alt="" /> Wysyłanie...');
		status.fadeIn();
		
		if(name.val().length == 0){ name.addClass('error'); valid = 1; }
		if(comment.val().length == 0){ comment.addClass('error'); valid = 1; }
		
		if(valid == 1){
			status.hide().html("Popraw pola!").fadeIn();
			return false;
		}
		
		$.post("/comments/post/ajax/",
			form.serialize(),
			function(data){
				commentsPart.html(data);
				commentForm(commentsPart.find('form'));
				$(".delete-comment-link").click(commentDelete);
			}
		);
		
		return false;
	});
}

function commentDelete(event){
	event.preventDefault();
    var url = $(this).attr("href");
    var commentsPart = $(this).parents(".comments-part");
    $.get(url,
        function(data){
			commentsPart.html(data);
			commentForm(commentsPart.find('form'));
			$(".delete-comment-link").click(commentDelete);
        }
    );
    return false;
}


function photos(){
	$('.view-photos .links a').click(function(){
		window.open(this.href);
		return false;
	});
	
	$('.view-photos img').mouseover(function(){
		$(this).stop().fadeTo(200, 0.5).fadeTo(400, 1);
	});
	
	$('.view-gallery .preview').find('.prev, .next').click(function(){
		var images = $(this).parent().find('.images a');
		
		if($(this).attr('class') == 'next')
			gallery_i = (gallery_i + 1) % images.size();
		else
			gallery_i = (gallery_i - 1) % images.size();
			
		images.stop(true,true).fadeOut();
		images.eq(gallery_i).fadeIn();
		
		return false;
	});
	
	$('.view-gallery .preview').find('.prev, .next').hover(
		function(){ $(this).fadeTo(200,0.3); },
		function(){ $(this).fadeTo(200,1); }
	);
	
	$('.view-gallery .small-images a, .view-gallery .link a, .gallery a').hover(
		function(){ $(this).fadeTo(300,0.4); },
		function(){ $(this).fadeTo(200,1); }
	);
}

function teamzone(){
	$(".submenu-teamzone a.link-team").click(function(){
		if($(this).hasClass('selected'))
			$(this).removeClass('selected');
		else
			$(this).addClass('selected');
		$(this).next().slideToggle(200);
		return false;
    });
}

function news(){
	$(".submenu a.year").click(function(){
		var year = $(this).attr('title');
		$(this).parents('ul').find('.news-'+year).slideToggle(200);
		return false;
    });
}

// Rotator
(function($){
	// slide show elements
	$.fn.extend({
		slider: function(options) {
			var defaults = {
				time: 4000,
				fade: 1000,
				mousestop: false
			};

			var o = $.extend(defaults, options);

			return this.each(function() {
				var obj = $(this);
				var interval;
				var time = o.time;
				var current = 0;
				var old = 0;
				var fade_time = o.fade;
				var mousestop = o.mousestop;
				var images = obj.find(".images");
				var count = images.find("a").size();
				var click = 0;
				
				images.find("a").hide();
				images.find("a:first").show();
				
				slider();

				if(mousestop){
					obj.hover(function() {
						window.clearInterval(interval);
					}, function() {
						slider();
					});
				};
				
				function slider(){
					if(count > 1){
						window.clearInterval(interval);
						interval = "";
						interval = window.setInterval(change_slide, time);
					}
				}
				
				obj.find('.menu a').click(function(){
					if(click === 0){
						click = 1;
						window.clearInterval(interval);
						
						if($(this).attr('class') == 'next')
							current = (current + 1) % count;
						else
							current = (current - 1) % count;
							
							
						images.find("a").eq(old).stop(true,true).fadeOut(fade_time);
						images.find("a").eq(current).stop(true,true).fadeIn(fade_time,function(){
							click = 0;
							old = current;
							interval = "";
							interval = window.setInterval(change_slide, time);
						});
					};
					
					return false;
				});

				function change_slide(){
					current = (current + 1) % count;
					images.find("a").eq(old).stop(true,true).fadeOut(fade_time);
					images.find("a").eq(current).stop(true,true).fadeIn(fade_time);
					old = current;
				}
			})
		}
	})
})(jQuery);


/**
 * @author Alexander Farkas
 * v. 1.02
 */
(function($) {
	$.extend($.fx.step,{
	    backgroundPosition: function(fx) {
            if (fx.state === 0 && typeof fx.end == 'string') {
                var start = $.curCSS(fx.elem,'backgroundPosition');
                start = toArray(start);
                fx.start = [start[0],start[2]];
                var end = toArray(fx.end);
                fx.end = [end[0],end[2]];
                fx.unit = [end[1],end[3]];
			}
            var nowPosX = [];
            nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
            nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];
            fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

           function toArray(strg){
               strg = strg.replace(/left|top/g,'0px');
               strg = strg.replace(/right|bottom/g,'100%');
               strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
               var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
               return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
           }
        }
	});
})(jQuery);
