Cufon.replace('#homepage h4, #homepage h3, nav > ul > li > a, #head h2, .tabs a, #template.template-program h4, .button', { fontFamily: 'HelveticaRounded LT BoldCn', hover: true});

var lang, i18n = null;

(function($) {
    $.fn.defaultText = function() {
        this.each(function() {
            $(this).val($(this).data('default')).addClass('default-text');
        });

        $(this).focus(function(){
            if ($(this).data('default') == $(this).val()) {
                $(this).val('').removeClass('default-text');
            }
        });

        $(this).blur(function(){
            if ($(this).val() == '') {
                $(this).val($(this).data('default')).addClass('default-text');
            }
        });
    };
})(jQuery);

(function($) {
    $.fn.sortElements = (function() {
        var sort = [].sort;
        return function(comparator, getSortable) {
            getSortable = getSortable || function(){return this;};
            var placements = this.map(function(){
                var sortElement = getSortable.call(this),
                    parentNode = sortElement.parentNode,
                    nextSibling = parentNode.insertBefore(
                        document.createTextNode(''),
                        sortElement.nextSibling
                    );
                return function() {
                    if (parentNode === this) {
                        throw new Error(
                            "You can't sort elements if any one is a descendant of another."
                        );
                    }
                    parentNode.insertBefore(this, nextSibling);
                    parentNode.removeChild(nextSibling);
                };
            });
            return sort.call(this, comparator).each(function(i){
                placements[i].call(getSortable.call(this));
            });
        };
    })();
})(jQuery);

var translation = {
	pl: {
		subscribe: {
            600: 'Nieprawidłowy adres e-mail.',
            601: 'Wprowadzony adres jest już w bazie.',
			201: 'Adres został dodany.'
		},
		unsubscribe: {
            600: 'Nieprawidłowy adres e-mail.',
            601: 'Wprowadzony adres nie istnieje.',
			202: 'Adres został usunięty.'
		}
	},
	en: {
		subscribe: {
            600: 'Invalid e-mail address.',
            601: 'Entered e-mail already exists .',
			201: 'Address was added.'
		},
		unsubscribe: {
            600: 'Invalid e-mail address.',
            601: 'Entered e-mail don\'t exists .',
			202: 'Address was removed.'
		}
	}
}

var newsletter = {
	init: function() {
		$('button.subscribe').click(function() {
			$("#quick-newsletter input[name='email']").addClass('loading');
			newsletter.subscribe($(this).siblings('input[name="email"]').val());
			return false;
		});
		$('button.unsubscribe').click(function() {
			$("#quick-newsletter input[name='email']").addClass('loading');
			newsletter.unsubscribe($(this).siblings('input[name="email"]').val());
			return false;
		});
	},

	message: function(message) {
		$('#quick-newsletter .message').html(message);
	},

	subscribe: function(email) {
		$('#quick-newsletter .message').html('');
		$.getJSON('/' + lang + '/newsletter/subscribe/' + email, function(response) {
			$("#quick-newsletter input[name='email']").removeClass('loading');
			if (response.result) {
				result = $.parseJSON(response.result);
				newsletter.message(i18n.subscribe[result.kod]);
			};
		});
	},

	unsubscribe: function(email) {
		$('#quick-newsletter .message').html('');
		$.getJSON('/' + lang + '/newsletter/unsubscribe/' + email, function(response) {
			$("#quick-newsletter input[name='email']").removeClass('loading');
			if (response.result) {
				result = $.parseJSON(response.result);
				newsletter.message(i18n.unsubscribe[result.kod]);
			};
		});
	}
}

var engine = {
    start: function() {
		newsletter.init();
        this.navigation();
		this.search();
        this.pager('#homepage .main', true);
        this.pager('#homepage .news');
        this.tabs();
        this.fixes();
        this.resize('#news dd .text', true);
        this.resize('#movie .wrap');
        this.resize('#prizes dd', true);
        this.resize('article .text, article .lead', true);
        this.resize('.template-2 .text', false, 130);
        this.resize('.template-4 .column-rowset', true, 34);
        this.select();
        this.gallery();
        this.sortMovies();
        this.resize('#body'); // zawsze na końcu!!!
    },

    pager: function(root, auto) {
		var interval = false;
        var $root = $(root);
        var $list = $root.find('ul > li');
        $list.filter(':gt(0)').hide();
        var index = 0;

        $root.find('.pager .prev').click(function() {
            index = ((index - 1) < 0) ? ($list.size() - 1) : (index -1);
            $list.hide().eq(index).show();
            $root.find('.pager .index').html(index + 1);
        });

        $root.find('.pager .next').click(function() {
            index = ((index + 1) >= $list.size()) ? 0 : (index +1);
            $list.hide().eq(index).show();
            $root.find('.pager .index').html(index + 1);
        });

		if (auto) {
			interval = setInterval(function() {
				$root.find('.pager .next').trigger('click');
			}, 6000);
			$(root).find('.pager').bind('mouseenter, mouseover', function() {
				clearInterval(interval);
			}).bind('mouseleave', function() {
				interval = setInterval(function() {
					$root.find('.pager .next').trigger('click');
				}, 6000);
			});
		};
    },

	search: function() {
		$('#quick-search').submit(function() {
			var url = $(this).attr('action');
			url += decodeURI($(this).find("input[name='query']").val());
			document.location.href = url;
			return false;
		})
	},

    fixes: function() {
        Cufon.replace('#homepage h4, #homepage h3, nav > ul > li > a, #head h2, .tabs a, #template.template-program h4, .button', { fontFamily: 'HelveticaRounded LT BoldCn', hover: true});
        $('#news dt:odd').addClass("odd");
    },

    resize: function(target, margin, diff) {
        $(target).each(function(i, e) {
            $(e).height('auto');
            $(e).height(((Math.ceil($(e).height() / 130)) * 130) - ((margin ? 1 : 0) + (diff ? diff : 0)));
        });
    },

    tabs: function() {
        var tabs = $('#tabs .wrap > div');
        var link = $('#tabs .tabs li a');
        link.each(function() {
            if (tabs.filter($(this).attr('href')).size() == 0) {
                $(this).addClass('disabled').parent().hide();
            }
        });
        $('#tabs .tabs li').filter(':visible').each(function(i, e) {
            $(e).addClass('child-' + i);
        });
        tabs.filter(':gt(0)').hide();
        $('#tabs .tabs li a').click(function() {
            if ($(this).hasClass('disabled')) {
                return false;
            }
            link.filter('.active').removeClass('active');
            $(this).addClass('active');
            tabs.filter($(this).attr('href')).show().siblings().hide();
            engine.resize('#movie .wrap');
            engine.resize('#body');
            return false;
        });
    },

    navigation: function() {
        var $subnav = $('nav > ul > li > ul > li')
        $subnav.filter(':first-child').addClass('first-child');
        $subnav.filter(':last-child').addClass('last-child');
        $('nav > ul > li > .label').parent().addClass('hoverable');
        $('nav .hoverable').each(function() {
            var $hover = $(this).find('ul');
			var $self = $(this);
            if ($hover.size() > 0) {
                var height = $hover.innerHeight();
                var $elem = $hover.find('li');
                var start = (height - ($elem.eq(0).innerHeight() * ($elem.size() - 1))) - 130;
                $hover.css({'top': -(height)}).data('height', -(height));
                $self.bind('mouseover', function() {
                    if (!($self.is('.hover'))) {
						$self.addClass("hover");
                        $hover.stop().animate({'top': -(start)}, 1, function() {
                            $(this).animate({'top': 130}, 600, 'easeOutExpo');
                        });
						$self.siblings('li').find('ul').each(function() {
                            $(this).stop().animate({'top': $(this).data('height')}, 40);
                        });
                        Cufon.replace('nav .label');
                    };
                }).bind('mouseleave', function() {
					$self.removeClass("hover");
                    $hover.stop().animate({'top': -(height)}, 600, 'easeOutExpo');
					setTimeout(function() {
						Cufon.replace('nav .label');
					}, 1);

                });
            } else {
                $self.bind('mouseover', function() {
					$self.addClass("hover");
					Cufon.replace('nav .label');
                }).bind('mouseleave', function() {
					$self.removeClass("hover");
                    Cufon.replace('nav .label');
                });
			};
        });
    },

    select: function() {
        $('#options .select dd').hide();
        $('#options .select dt').click(function() {
            $(this).toggleClass('selected').siblings('dd').not('.active').slideToggle(120);
        });
    },

    sortMovies: function() {
        var order = null;
        $('#sort-movies a').click(function() {
            order = $(this).data('order');
            $('#sort-movies dt .text').html($(this).html());
            $(this).parent().addClass('active').css({'display': 'none'}).siblings('dd').removeClass('active').css({'display': 'block'});
            $('#sort-movies dt').click();
            $('#program li').sortElements(function(a, b){
                return $(a).data(order) > $(b).data(order) ? 1 : -1;
            });
            return false;
        });
    },

    gallery: function() {
        var $root = $('#tab-gallery');
        var $list = $('#gallery-preview li');

		if ($list.size() <= 1) {
			$root.find('.next, .prev').hide();
		};
        $list.filter(':gt(0)').hide();

		$('#tab-gallery .prev, #tab-gallery .next').hover(function() {
			$(this).addClass('hover');
		}, function() {
			$(this).removeClass('hover');
		});

        $root.find('.next').click(function() {
            var $next = $list.filter(':visible').next();
            var $elem = null;
            if ($next.length > 0) {
                $elem = $next;
            } else {
                $elem = $list.filter(':eq(0)');
            }
            $list.filter(':visible').hide();
            $elem.show();
            return false;
        });

        $root.find('.prev').click(function() {
            var $next = $list.filter(':visible').prev();
            var $elem = null;
            if ($next.length > 0) {
                $elem = $next;
            } else {
                $elem = $list.eq(($list.size() - 1));
            }
            $list.filter(':visible').hide();
            $elem.show();
            return false;
        });
    }
}
$(document).ready(function() {
	lang = $('html').attr('lang');
	i18n = translation[lang];
    engine.start();
    $('.quick input').defaultText();
});
