var staticLink = 'http://static.akademianikona.pl/';
var staticLink = '/static/';
var errors = {
    'isEmpty': 'Pole wymagane nie może być puste.',
    'notSame': 'Wprowadzone wartości nie są takie same.',
    'notGreaterThan': 'Pole wymagane, musi być zaznaczone.',
    'emailExist': 'Ten adres już zarejestrowano.',
    'notAllowed': 'Wprowadzono nie dozwoloną wartość.',
    'stringLengthTooShort': 'Wprowadzona wartość jest za krótka.',
    'stringLengthTooLong': 'Wprowadzona wartość jest za długa.',
    'emailAddressInvalidFormat': 'Nieprawidłowy adres e-mail.',
    'notRecognized': 'Nieprawidłowa nazwa konta lub hasło.',
    'emailNewsletterExists': 'Podany adres jest już w bazie.',
    'emailDontExists': 'Nie znaleziono pasującego użytkownika.',
    'invalidPostcode': 'Nieprawidłowy kod pocztowy.',
    'invalidNip': 'Nieprawidłowy numer nip.',
    'invalidPhone': 'Nieprawidłowy numer telefonu.',
    'invalidUsername': 'Wprowadzono nie dozwoloną wartość.'
};

var enableAnmiation = true;

jQuery.fn.center = function(params) {
    var options = {vertical: true, horizontal: true}
    op = jQuery.extend(options, params);

   return this.each(function(){
        var $self = jQuery(this);
        var width = $self.width();
        var height = $self.height();
        var paddingTop = parseInt($self.css("padding-top"));
        var paddingBottom = parseInt($self.css("padding-bottom"));
        var borderTop = parseInt($self.css("border-top-width"));
        var borderBottom = parseInt($self.css("border-bottom-width"));

        var mediaBorder = parseInt((borderTop+borderBottom)/2);
        var mediaPadding = parseInt((paddingTop+paddingBottom)/2);
        var positionType = $self.parent().css("position");
        var halfWidth = parseInt((width/2)*(-1));
        var halfHeight = parseInt(((height/2)*(-1)) - (mediaPadding));

        var cssProp = {
            position: 'fixed'
        };

        if(op.vertical) {
            cssProp.height = height;
            cssProp.top = '50%';
            cssProp.marginTop = halfHeight;
        }
        if(op.horizontal) {
            cssProp.width = width;
            cssProp.left = '50%';
            cssProp.marginLeft = halfWidth;
        }
        if (positionType == 'static') {
            $self.parent().css("position","relative");
        }
        $self.css(cssProp);
   });
};

jQuery.fn.layer = function(options) {

    var defaults = {
        type: 'get',
        handler: 'href',
        overlay: 0.8,
        animation: 300,
        center: true,
        callbackOpen: false,
        callbackLoad: false,
        callbackClose: false,
        callbackError: false,
        customClass: ''
    };
    var settings = $.extend({}, defaults, options);
    var local = this.selector;
    var callback = function(name) {
        functionName = settings[name];
        if (typeof functionName === 'function') {
            functionName(local);
        }
    };

    var closeWindow = function() {

        $('#layer-overlay').animate({
            opacity: 0
        },
        settings.animate, function() {
            $(this).remove();
        });
        $('#layer-windows').animate({
            opacity: 0
        },
        settings.animate, function() {
            // $(document).unbind('keypress', close);
            callback('callbackClose');
            $(this).remove();
        });
        return false;
    };

    var bindClose = function(event) {
        if (event.keyCode == 27) {
            closeWindow();
            return false;
        }
    }

    var response = function(response) {
        var overlay = jQuery('<div id="layer-overlay"></div>');
        overlay.appendTo('body').addClass(settings.custom).css({
            width: $(document).width(),
            height: $(document).height(),
            opacity: 0
        }).animate({
            opacity: settings.overlay
        },
        settings.animation);
        var content = $('<div id="layer-windows"></div>');
        content.appendTo('body').addClass(settings.custom).css({opacity: 0}).html(response).animate({opacity: 1},settings.animation).center();

        // $(document).bind('keypress', bindClose);
        $('#layer-overlay, #layer-windows .terminate').live('click', closeWindow);
        return {
            content: content,
            overlay: overlay
        };
    };
    var request = function(address) {
        $.ajax({
            url: address,
            type: settings.type,
            data: (settings.data),
            global: false,
            dataType: "html",
            success: function(data) {
                response(data);
                callback('callbackLoad');
            },
            error: function(data) {
                callback('callbackError');
            }
        });
    };
    $(local).live('click', function() {
        callback('callbackOpen');
        request($(this).attr(settings.handler));
        return false;
    });

    return this;
};

jQuery.fn.defaults = function(a) {
    return this.each(function() {
        if (this.type != "text" && this.type != "password" && this.type != "textarea") {
            return;
        }
        var b = this;

        if (this.value == "") {
            this.value = a;
        } else {
            return;
        }
        $(this).bind("focus", function() {
            if (this.value == a || this.value == "") {
                this.value = "";
            }
        });
        $(this).bind("blur", function() {
            if (this.value == a || this.value == "") {
                this.value = a;
            }
        });
    });
};

new function() {
    $.fn.validate = {
        init: function(element) {
            if ($(element).is("[type='text']") || $(element).is("[type='password']") || $(element).is("textarea")) {
                if ($(element).attr('required') == 'true') {
                    this.proced(element);
                } else if ($(element).attr('required') == 'false') {
                    return false;
                } else {
                    if (element.value.length == 0)
                        this.success(element);
                    else
                        this.proced(element);
                }
            }
            if ($(element).is("[type='checkbox']")) {
                if ($(element).attr('required') == 'true') {
                    if ($(element).is(':checked')) {
                        this.success(element);
                    } else {
                        this.error(element, 'notGreaterThan');
                    }
                }
            }
        },
        proced: function(element) {
            switch ($(element).attr('validate')) {
                case 'email':
                    this.email(element);
                    break;
                case 'phone':
                    this.phone(element);
                    break;
                case 'string':
                    this.string(element);
                    break;
                case 'postcode':
                    this.postcode(element);
                    break;
                case 'nip':
                    this.nip(element);
                    break;
            }
        },
        string: function(e) {
            var rule = /[(\*\(\)\[\]\+\,\?\:\;\'\"\`\~\\#\$\%\^\&\<\>)+]/;
            if (!(e.value.match(rule))) {
                if (e.value.length == 0) {
                    $.fn.validate.error(e, 'isEmpty');
                } else if (e.value.length < 3 && e.value.length > 0) {
                    $.fn.validate.error(e, 'stringLengthTooShort');
                } else {
                    $.fn.validate.success(e);
                }
            } else {
                $.fn.validate.error(e, 'notAllowed');
            };
        },
        phone: function(e) {
            var rule = /^[0-9 ]{9,12}$/;
            if (e.value.match(rule)) {
                // console.log('postcode match')
                $.fn.validate.success(e);
            } else {
                $.fn.validate.error(e, 'invalidPhone');
            };
        },
        postcode: function(e) {
            var rule = /^[0-9]{2}\-[0-9]{3}$/;
            if (e.value.match(rule)) {
                // console.log('postcode match')
                $.fn.validate.success(e);
            } else {
                $.fn.validate.error(e, 'invalidPostcode');
            };
        },
        email: function(e) {
            var rule = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (e.value.match(rule)) {
                $.fn.validate.success(e);
            } else {
                $.fn.validate.error(e, 'emailAddressInvalidFormat');
            };
        },
        nip: function(e) {
            if(!e.value.match( /^[0-9]{3}-[0-9]{2}-[0-9]{2}-[0-9]{3}$/ ) && !e.value.match( /^[0-9]{3}-[0-9]{3}-[0-9]{2}-[0-9]{2}$/ ) && !e.value.match( /^[0-9]{10}$/ )) {
                $.fn.validate.error(e, 'invalidNip');
            }
            var my_nums=e.value.replace(/-/g,'');
            var valid_nums="657234567";
            var sum=0;
            for (var temp=8;temp>=0;temp--) {
                sum += (parseInt(valid_nums.charAt(temp)) * parseInt(my_nums.charAt(temp)));
            }
            if ((sum % 11) == 10 ? false : ((sum % 11) == parseInt(my_nums.charAt(9)))) {
                $.fn.validate.success(e);
                return false;
            }
            $.fn.validate.error(e, 'invalidNip');
        },
        success: function(e) {
            row = $(e).parents('.row');
            row.find('.status').remove();
            row.append('<p class="status"><span class="icon">x</span> <span class="text">Poprawnie wypełnione</span></p>');
            return true;
        },
        error: function(e, message) {
            // console.log('error')
            row = $(e).parents('.row');
            row.find('.status').remove();
            row.append('<p class="status error"><span class="icon">x</span> <span class="text">'+errors[message]+'</span></p>');
            return false;
        },
        validate: function(e) {
        }
    };
};

Propagate = function() {
    this.status = true,

    this. start = function() {
        this.status = false;
    }

    this.stop = function() {
        this.status = true;
    }

    this.state = function() {
        return this.status;
    }
};

var isHomepage = function() {
    return document.getElementById('page-home') ? true : false;
};

var lightbox = {
    start: function() {

    },

    next: function() {
        $('#lightbox .description').fadeOut();
        $('#lightbox .image img').fadeOut('normal', function() { $(this).remove(); });
        index = $('#lightbox').attr('index');
        next = $('#gallery .list').find("li[rel='"+index+"']").next();
        next = next.length == 1 ? next : $('#gallery .list').find("li").eq(0);
        lightbox.load(next.attr('rel'));
        return false;
    },

    prev: function() {
        $('#lightbox .description').fadeOut();
        $('#lightbox .image img').fadeOut('normal', function() { $(this).remove(); });
        index = $('#lightbox').attr('index');
        prev = $('#gallery .list').find("li[rel='"+index+"']").prev();
        prev = prev.length == 1 ? prev : $('#gallery .list').find("li").eq(-1);
        lightbox.load(prev.attr('rel'));
        return false;
    },

    show: function(target) {
        var b = $('<div id="lightbox"></div>');
        b.append('<div class="content"><span class="image"></span></div>');
        b.append('<div class="description">Opis</div>')
        b.append('<div class="close"><a class="prev">< poprzednie</a> <a class="next">następne ></a><a class="terminate" href="#">zamknij</a></div>');
        var a = {height: $(document).height(), width: $(document).width()};
        $('<div id="overlay"></div>').animate({opacity: 0},0).prependTo("body").css(a).animate({opacity: 0.6},180, function() {
            $(b).animate({opacity: 0},0).prependTo("body").animate({opacity: 1},260, function() {
                lightbox.load(target, "#lightbox");
                lightbox.hide();
                $('#lightbox .next').click(function() {
                    lightbox.next();
                });
                $('#lightbox .prev').click(function() {
                    lightbox.prev();
                });
            }).center();
        });
    },

    hide: function() {
        $("#overlay, #lightbox .terminate").click(function() {
            $("#lightbox").fadeOut("120", function() {
                $("#overlay").fadeOut("60", function() {
                    $("#lightbox, #overlay").remove();
                });
            });
            return false;
        });
    },

    hash: function(hash) {
        return staticLink + 'upload/gallery/' + hash + '-b.jpg';
    },

    load: function(target, c) {
        var e = new Image();
        var a;
        e.onload = function() {
            var h = e.width;
            var f = e.height;
            if (h > f) {
                if (h > 900) {
                    f = f / (h / 900);
                    h = 900;
                }
            }
            if (f > h) {
                if (f > 500) {
                    h = h / (f / 500);
                    f = 500;
                }
            }
            var g = $('#lightbox').attr('index', target).find(".image");
            var i = $('<img src="' + lightbox.hash(target) + '" />');
            var d = $("#gallery .list li[rel='"+target+"']").attr('description');
            i.attr("width", h).attr("height", f).appendTo(g).hide(0);
            b(h, f, d);
            e.onload = function() {};
        };
        e.src = lightbox.hash(target);
        function b(i, f, d) {
            var h = i / 2;
            var g = f / 2;
            $('#lightbox').animate({width: i, height: f + 22, marginLeft: -h, marginTop: -g, left: "50%", opacity: 1}, 600, function() {
                $(this).find('.image img, .close, .description').fadeIn();
                $(this).find('.description').html(d);
            });
        }
    }
};

var common = {
    start: function() {
        this.cufon();
        this.corporate();
        setTimeout(function() { common.issue(); }, 680);
        setTimeout(function() { common.slide(); }, 720);
        this.hover('#readers li');
        this.hover('#slider li');
        this.calculate();
    },

    cufon: function() {
        Cufon.replace('#page h2, #home h2, #products .title h4, #location dt p, #slider .text h3, #editor .column-rowset h3, #location-window h3, #blog strong', { fontFamily: 'Square721 TL', fontWeight: '800' });
        Cufon.replace('#user h4, #expedition h4 span', { fontFamily: 'Square721 EU' });
        Cufon.replace('#expedition h3 span', { fontFamily: 'Square721 TL', wordSpacing: '-1px', letterSpacing: '-1px', fontWeight: '600' });
    },

    calculate: function() {
        if (document.getElementById('products')) {
            var width = 0;
            $('#products .date').each(function() {
                width = $(this).width() > width ? $(this).width() + 6 : width;
            }).css({'width': width});
        }
    },

    hover: function(target) {
        $(target).click(function() {
            document.location.href = $(this).find('a').eq(0).attr('href');
        })
    },

    issue: function() {
        if (isHomepage()) {
            $('#head').stop().animate({'height': 16}, 300);
        }

        $('#head').hover(function() {
            show();
        }, function() {
            hide();
        } );

        function hide() {
            $('#head').stop().animate({'height': 16}, 420);
        }

        function show() {
            $('#head').stop().animate({'height': 148}, 620);
        }
    },

    corporate: function() {
        $('#home .hide').click(function() {
            var home = $('#home');
            home.find('.commercial').fadeOut(180);
            home.find('.splash').animate({opacity: 0}, 210, function() {
                $(this).animate({height: '52px'}, 380, function() {
                    home.removeClass('expand');
                    $(this).animate({opacity: 1});
                });
            });
            return false;
        });

        $('#home h1, #home .show').click(function() {
            var home = $('#home');
            home.find('.splash').animate({opacity: 0}, 210, function() {
                $(this).animate({height: '130px'}, 380, function() {
                    home.addClass('expand');
                    $(this).animate({opacity: 1});
                    home.find('.commercial').fadeIn(180);
                });
            });
            return false;
        })
    },

    location: function() {
        var slide = $('.switch #slides').find('ul');
        count = slide.find('li').size();
        if (count == 0) {
            $('.switch #slides').append('<h3 class="blank">Brak zdjęć</h3>');
        }
        if (count > 1) {
            slide.find('li:first').addClass('active');
            slide.css({'position': 'absolute', 'left': 0, 'width': count * 414});
            control = ['list', 'prev', 'next', 'grid'];
            control.list = $('<div class="control"> <span class="grid"><span>01</span>/0'+count+'</span></div>').appendTo(slide.parents('#slides'));
            control.grid = $(control.list).find('.grid span');
            control.next = $('<span class="next"></span>').prependTo(control.list);
            control.prev = $('<span class="prev"></span>').prependTo(control.list);

            control.next.unbind().bind('click', function() {
                if ($(this).is('.blocked')) {
                    return false;
                }
                count = slide.find('li').size();
                active = slide.find('.active');
                index = active.index() + 1;
                $(this).parents('.control').find('.blocked').removeClass('blocked').animate({opacity: 1});
                if (index == count - 1) {
                    $(this).addClass('blocked').animate({opacity: 0.5});
                }
                $(this).parents('.control').find('.grid span').html('0' + (index + 1));
                slide.find('li').removeClass('active');
                slide.find('li').eq(index).addClass('active')
                slide.animate({'left': -(index * 414)}, 540);
            });

            control.prev.unbind().addClass('blocked').animate({opacity: 0.5}).bind('click', function() {
                if ($(this).is('.blocked')) {
                    return false;
                }
                count = slide.find('li').size();
                active = slide.find('.active');
                index = active.index() - 1;
                $(this).parents('.control').find('.blocked').removeClass('blocked').animate({opacity: 1});
                if (index == 0) {
                    $(this).addClass('blocked').animate({opacity: 0.5});
                }
                $(this).parents('.control').find('.grid span').html('0' + (index + 1));
                slide.find('li').removeClass('active');
                slide.find('li').eq(index).addClass('active')
                slide.animate({'left': -(index * 414)}, 540);
            });
        }

    },

    slide: function() {
        if (!(isHomepage())) {

            $('#user').css({'cursor': 'pointer'});

            var sidebar = {
                show: function() {
                    $('#user').css({'cursor': 'default'}).stop().animate({height: '154'}, 340, function() {
                        $('#user').addClass('expand');
                        $('#authorization .recovery').show();
                        $('#user').find('.active-basket').fadeIn();
                    });
                },

                hide: function() {
                    $('#user').stop().animate({height: '42'}, 420, function() {
                        $('#authorization .recovery').hide();
                        $('#user').removeClass('expand').css({'cursor': 'pointer'});
                        $('#user').find('.error').remove();
                        $('#user').find('.active-basket').fadeOut();
                    });
                }
            }

            var show = 0;
            $('#user').hover(function() {
                if (!($(this).hasClass('expand'))) {
                    show = setTimeout(function() {
                        sidebar.show();
                    }, 960);
                }
            }, function() {
                clearTimeout(show);
                sidebar.hide();
            });

            $('#user').click(function() {
                if (!($(this).hasClass('expand'))) {
                    sidebar.show();
                }
            })
        }
    }
};

var gallery = {
    start: function() {
        if (typeof gallery_resource == 'object') {
            this.setup();
            $('#gallery .list li').live('click', function(){
                gallery.image($(this).attr('rel'));
            });
            $('#gallery .entry').click(function() {
                lightbox.show($(this).attr('rel'));
            });
        }
    },

    setup: function() {
        if (gallery_resource.resource) {
            var container = $('#editor #gallery:first');
            container.empty();
            list = $('<ul class="list"></ul>').appendTo(container);
            entry = $('<div rel="'+gallery_resource.resource[0][0]+'" class="entry"></div>').prependTo(container);
            entry.prepend('<img src="'+staticLink+'upload/gallery/'+gallery_resource.resource[0][0]+'-m.jpg">');
            $(gallery_resource.resource).each(function(i, e) {
                var d = e[1] ? e[1] : '';
                t = '<li rel="'+e[0]+'" description="'+d+'"><img src="'+staticLink+'upload/gallery/'+e[0]+'-s.jpg" /></li>';
                list.append(t);
            });
            var size = list.find('li').size();
            if (size > 8) {
                list.wrap('<div class="slider"></div>');
                page = Math.ceil(size/8);
                list.css({width: (Math.ceil(size/2) * 105)});
                control = ['list', 'prev', 'next', 'grid'];
                control.list = $('<div class="control"> <span class="grid"><span>01</span>/0'+page+'</span></div>').insertAfter(list.parent());
                control.grid = $(control.list).find('.grid span');
                control.next = $('<span class="next"></span>').prependTo(control.list);
                control.prev = $('<span class="prev"></span>').prependTo(control.list);
                var index = 0;
                control.next.bind('click', function() {
                    if ($(this).is('.blocked')) { return false; }
                    index++;
                    control.list.find('.blocked').removeClass('blocked').animate({opacity: 1});
                    if (index == page - 1) {
                        $(this).addClass('blocked').animate({opacity: 0.5});
                    }
                    control.list.find('.grid span').html('0' + (index + 1));
                    list.animate({'left': -((index * 414) + (index * 6))}, 540);
                })
                control.prev.addClass('blocked').animate({opacity: 0.5}).bind('click', function() {
                    if ($(this).is('.blocked')) { return false; }
                    index--;
                    control.list.find('.blocked').removeClass('blocked').animate({opacity: 1});
                    if (index == 0) {
                        $(this).addClass('blocked').animate({opacity: 0.5});
                    }
                    control.list.find('.grid span').html('0' + (index + 1));
                    list.animate({'left': -((index * 414) + (index * 6))}, 540);
                })
            }
        }
    },

    image: function(source) {
        var entry = $('#gallery .entry');
        entry.attr('rel', source).find('img').fadeOut();
        $('<img class="prepend" src="'+staticLink+'upload/gallery/'+source+'-m.jpg">').appendTo(entry).fadeIn();
    }
};

var decorator = {
    start: function() {
        this.common();
        this.select();
        this.checkbox();
        this.radio();
    },

    common: function() {
        $("#user input[name='newsletter']").defaults('Podaj swój adres e-mail');

        $("#contact-form input[name='name']").defaults('Twoje imię i nazwisko');
        $("#contact-form input[name='email']").defaults('Twój adres e-mail');

        $(".rowset").find(".row:first").addClass("first");

        $("input[type='checkbox'], input[type='radio']").each(function(i, e) {
            if ($(this).is(':checked')) {
                $(this).parent().addClass('checked');
            }
        });
    },

    checkbox: function() {
        function check(target) {
            if (target.is(':checked')) {
                target.removeAttr('checked');
                target.parent().removeClass('checked');
            } else {
                target.attr('checked', true);
                target.parent().addClass('checked');
            }
            return false;
        }
        $('.wraper-checkbox').click(function() {
            check($(this).find('input'));
        });
        $('.wraper-checkbox').siblings('label').not('.disabled').click(function() {
            check($('input#' + $(this).attr('for')));
        });
    },

    radio: function() {
        function check(target) {
            name = target.attr('name');
            if (!target.is(':checked')) {
                $(".wraper-radio input[name='"+name+"']").each(function(i, e){
                    if (e.checked)
                        $(e).removeAttr('checked').parent().removeClass('checked');
                });
                target.attr('checked', true).parent().addClass('checked');
            }
            return false;
        }
        $('.wraper-radio').click(function() {
            check($(this).find('input'));
            return false;
        });
        $('.wraper-radio').siblings('label').click(function() {
            check($('input#' + $(this).attr('for')));
            return false;
        });
    },

    select: function() {
        $('.wraper-select select').each(function() {
            var $current = $(this);
            $current.hide();
            var $wrapper = $current.parent();
            var content = '';
            content += '<div class="selectover">';
            content += '<div class="selected"></div>';
            content += '<div class="overlay">';
            content += '<div class="content">';
            content += '<ul></ul>';
            content += '</div>';
            content += '<div class="border"></div>';
            content += '</div>';
            content += '</div>';
            $(this).after(content);
            $wrapper.find('.selectover').addClass($current.attr('class'));
            var $list = $wrapper.find('.overlay');
            var $ul = $list.find('ul');
            var count = 0;
            $wrapper.find('option').each(function(i){
                if (this.value == 0) {
                    $wrapper.find('.selected').html(this.text);
                } else {
                    $ul.append('<li><a index="'+ this.value +'">'+ this.text +'</a></li>');
                }
                if ($(this).attr('selected')) {
                    $wrapper.find('.selected').html(this.text);
                    $ul.find("a[index='"+this.value+"']").parent().addClass('active');
                }
            });
            var size = $wrapper.find('li').size();
            $wrapper.find('.selected').unbind().click(function() { slide(this); });
            $wrapper.find('li a').click(function() {
                var option = $(this);
                var e = {};
                e.text  = option.text();
                e.value = option.get(0).rel;
                e.index = option.attr('index');
                $wrapper.find("option[value='"+e.index+"']").attr('selected', true);
                $('.select li a').removeClass('selected');
                $wrapper.find('.selected').html(e.text);
                slide(option);
                return false;
            });
        });

        function slide(element) {
            $wrapper = $(element).parents('.selectover');
            $list = $wrapper.find('.overlay');
            $ul = $wrapper.find('ul');
            if ($(element).is(".selected")) {
                if ($list.is(':visible')) {
                    $list.slideUp('fast', function() {});
                    $('body *').unbind('click', close);
                } else {
                    $list.slideDown('fast', function() {
                        $('body *').bind('click', close);
                    });
                }
            } else {
                $list.slideUp('fast', function() {
                    $(element).parent().addClass('active').siblings('li').removeClass('active');
                });
                $('body *').unbind('click', close);
            }
        };

        function close() {
            var close = true;
            $(this).parents().map(function () { return this.className; }).each(function(e) {
                if (this == 'selectover') {
                    close = false;
                }
            });
            if (close == true) { slide(false); }
            return close;
        }
    }
};

var basket = {
    start: function() {
        $('#products .price .button').not('.disabled').click(function() {
            basket.create(this);
            return false;
        });

        $('#expedition #products .price .button').unbind('click').attr('target', '_blank');

        $('.page-locations .order a').not('.disabled').click(function() {
            basket.create(this);
            return false;
        });

        $('#basket .remove').live('click', function() {
            basket.remove(this);
            return false;
        });

        $('.basket-products .remove').live('click', function() {
            var id = $(this).parents('li').attr('rel');
            $.post('/koszyk/usun/', {'product': id}, function() {
                document.location.href = '/koszyk/';
            });
            return false;
        });

        $('.basket-products .overlay a').bind('click', function() {
            var id = $(this).parents('ul').parents('li').attr('rel');
            var count = $(this).attr('index');
            $.post('/koszyk/aktualizuj/', ({'product': id, 'quantity': count}), function() {
                document.location.href = '/koszyk/';
            });
        });
    },

    create: function(target) {
        var id = $(target).attr('rel');
        var option = $(target).parents('li').find('option:selected').val();
        option = option == 'yes' ? 1 : 0;
        $.scrollTo('#head', 180);
        $('#user').stop().animate({height: '154'}, 220, function() { $('#user').addClass('expand'); });
        $('#basket .info').empty()
        $('#basket small').empty().addClass('loading');
        $.post('/koszyk/dodaj/', {'product': id, 'option': option}, function(response) {
            basket.get(response);
            $('<div class="active-basket"></div>').appendTo('#user').fadeIn();
        }, "json");
        return false;
    },

    remove: function(target) {
        var id = $(target).parent().attr('rel');
        $('#user').stop().animate({height: '154'}, 220, function() { $('#user').addClass('expand'); });
        $('#basket .info').empty();
        $('#basket small').empty().addClass('loading');
        $.post('/koszyk/usun/', {'product': id}, function(response) {
            basket.get(response);
        }, "json");
        return false;
    },

    get: function(response) {
        root = $('#basket');
        root.find('small').removeClass("loading");
        if (response.total > 0) {
            root.removeClass('empty');
            root.find('small').eq(0).html('suma: <strong>'+response.total+' PLN</strong>');
            p = response.products;
            for (i in p) {
                e = p[i];
                var li = '';
                li += '<li rel="'+e.id+'">';
                li += e.name + ', '
                if (response.count[e.id] > 1)
                    li += response.count[e.id] + 'x '
                li += '<strong>'+e.price+' PLN</strong> '
                li += '<span class="remove"></span></li>';
                root.find('ul.info').prepend(li);
            }
            if ($(response.count).size() >= 4)
                root.find('ul.info').append('<li class="more">...</li>');
        } else {
            root.find('ul.info').append('<li>Koszyk jest pusty.</li>');
            root.addClass('empty');
        }

    }
};

var slider = {
    start: function() {
        if (isHomepage()) {
            $('#slider .entry').each(function() {
                slide = $(this).find('ul');
                count = slide.find('li').size();
                slide.find('li:first').addClass('active');
                slide.css({'position': 'absolute', 'left': 0, 'width': count * 300}).wrap('<div class="wrap"></div>');
                control = ['list', 'prev', 'next', 'grid'];
                control.list = $('<div class="control"> <span class="grid"><span>01</span>/0'+count+'</span></div>').appendTo(slide.parents('.entry'));
                control.grid = $(control.list).find('.grid span');
                control.next = $('<span class="next"></span>').prependTo(control.list);
                control.prev = $('<span class="prev"></span>').prependTo(control.list);
                control.next.bind('click', function() {
                    if ($(this).is('.blocked')) {
                        return false;
                    }
                    slide = $(this).parents('.entry').find('ul');
                    count = slide.find('li').size();
                    active = slide.find('.active');
                    index = active.index() + 1;
                    $(this).parents('.control').find('.blocked').removeClass('blocked').animate({opacity: 1});
                    if (index == count - 1) {
                        $(this).addClass('blocked').animate({opacity: 0.5});
                    }

                    $(this).parents('.control').find('.grid span').html('0' + (index + 1));
                    slide.find('li').removeClass('active');
                    slide.find('li').eq(index).addClass('active')
                    slide.animate({'left': -(index * 300)}, 540);
                })
                control.prev.addClass('blocked').animate({opacity: 0.5}).bind('click', function() {
                    if ($(this).is('.blocked')) {
                        return false;
                    }
                    slide = $(this).parents('.entry').find('ul');
                    count = slide.find('li').size();
                    active = slide.find('.active');
                    index = active.index() - 1;
                    $(this).parents('.control').find('.blocked').removeClass('blocked').animate({opacity: 1});
                    if (index == 0) {
                        $(this).addClass('blocked').animate({opacity: 0.5});
                    }
                    $(this).parents('.control').find('.grid span').html('0' + (index + 1));

                    slide.find('li').removeClass('active');
                    slide.find('li').eq(index).addClass('active')
                    // slide.animate({opacity: 0}, 320).animate({'left': -(index * 308)}, 1).animate({opacity: 1}, 320);
                    slide.animate({'left': -(index * 300)}, 540);
                })
            });
            if (enableAnmiation) {
                this.slide();
            }
        }
    },

    slide: function() {
        var time  = 0;
        $('#slider .entry .control').stop().animate({opacity: 0}, 1);
        function slider() {
            time = setInterval(function() {
                $('#slider .entry').each(function() {
                    $(this).find('.blocked').removeClass('blocked').animate({opacity: 1});
                    slide = $(this).find('ul');
                    count = slide.find('li').size();
                    active = slide.find('.active');
                    index = active.index() + 1;
                    if (index == count || index == 0) {
                        animate = count * 320;
                    } else {
                        animate = 540;
                    }
                    index = index == count ? 0 : index;
                    $(this).find('.grid span').html('0' + (index + 1));
                    slide.find('li').removeClass('active');
                    slide.find('li').eq(index).addClass('active')

                    // slide.animate({opacity: 0}, 380).animate({'left': -(index * 308)}, 0).animate({opacity: 1}, 380);
                    slide.animate({'left': -(index * 300)}, animate);
                    if (index == count - 1) {
                        $(this).find('.next').addClass('blocked').animate({opacity: 0.5});
                    }
                    if (index == 0) {
                        $(this).find('.prev').addClass('blocked').animate({opacity: 0.5});
                    }
                });
            }, 6200);
        }
        slider();
        $('#slider .entry').mouseover(function() {
            clearInterval(time);
            $(this).find('.control').stop().animate({opacity: 1}, 120);
        })
        $('#slider .entry').mouseout(function() {
            slider();
            $(this).find('.control').stop().animate({opacity: 0}, 120);
        })
    }
};

$().ready(function() {
    // $.ga.load("'UA-10432522-1");
    var propagate = new Propagate();

	$("a[rel*='external']").attr('target', '_blank');

    decorator.start();
    common.start();
    gallery.start();
    calendar.start();
    basket.start();
    slider.start();

    $("#login-form").submit(function() {
        if (propagate.state()) {
            form = $(this);
            form.find('.errors').fadeOut(120, function() {$(this).remove();});
            propagate.start();
            $('<span id="loading-form"></span>').insertAfter(".wraper-submit");
            $.post('/logowanie/', $(this).serialize(), function(response) {
                placeLoading("input[name='email'], input[name='password']");
                if (response.status == true) {
                    document.location.href = form.attr('action');
                } else {
                    placeError("input[name='email'], input[name='password']", response.errors);
                }
                $("#loading-form").remove();
                propagate.stop();
            }, "json");
        }
        return false;
    });

    $("#recovery-form").submit(function() {
        $("#recovery-form input[name='email']").trigger('blur');
        if ($(this).find('.status.error').size() == 0) {
            if (propagate.state()) {
                form = $(this);
                propagate.start();
                $('<span id="loading-form"></span>').insertAfter(".wraper-submit");
                $.post('/reset-hasla/', $(this).serialize(), function(response) {
                    if (response.status == true) {
                        document.location.href = form.attr('action');
                    } else {
                        $.fn.validate.error($("#recovery-form input[name='email']"), response.errors);
                    }
                    $("#loading-form").remove();
                    propagate.stop();
                }, "json");
            }
        }
        return false;
    });

    $("#recovery-form input[name='email']").blur(function() {
        $(this).validate.init(this);
    });

    $("#recovery-form .submit").click(function() {
        $("#recovery-form").submit();
        return false;
    });

    var cache = {};

    function placeError(field, error) {
        row = $(field).parents('.row');
        row.find('.errors').remove();
        row.append('<ul class="errors">'+errors[error]+'</ul>');
    }

    function placeLoading(field, remove) {
        row = $(field).parents('.row');
        row.find('.errors').remove();
        row.append('<div class="errors loading"></div>');
    }

    $("#quick-authorization .submit").click(function() {
        $("#quick-authorization").submit();
        return false;
    });

    $("#quick-authorization").submit(function() {
        if (propagate.state()) {
            $('#quick-authorization .submit').addClass('loading');
            $("#authorization .error").fadeOut(120, function() {$(this).remove();});
            propagate.start();
            $.post('/logowanie/', $(this).serialize(), function(response) {
                if (response.status == true) {
                    document.location.href = document.URL;
                } else {
                    $('#authorization .recovery').hide();
                    $("#authorization h4").after('<p class="error"><em></em> Błąd logowania.</p>');
                }
                 $('#quick-authorization .submit').removeClass('loading');
                propagate.stop();
            }, "json");
        }
        return false;
    });

    // newsletter-signin

    $('#newsletter-signin #submit').click(function() {
        $('#newsletter-signin').submit();
        return false;
    });

    $("#newsletter-signin input[name='email']").blur(function() {
        $(this).validate.init(this);
    });

    $("#newsletter-signin").submit(function() {
        $("#newsletter-signin input[name='email']").trigger('blur');
        $('#newsletter-signin .status').remove();
        if ($(this).find('.status.error').size() == 0) {
            if (propagate.state()) {
                form = $(this);
                propagate.start();
                $('<span id="loading-form"></span>').insertAfter(".wraper-submit");
                $.post('/newsletter/', $(this).serialize(), function(response) {
                    if (response.status == true) {
                        $('#newsletter-signin').parent().append('<p class="response">Witamy w gronie subskrybentów newslettera serwisu „Akademia Nikona”.</p>').parent().find('form').remove();
                        // document.location.href = form.attr('action');
                    } else {
                        $.fn.validate.error($("#newsletter-signin input[name='email']"), response.error);
                    }
                    $("#loading-form").remove();
                    propagate.stop();
                }, "json");
            }
        }
        return false;
    });

    // newsletter-signout

    $('#newsletter-signout .submit').click(function() {
        $('#newsletter-signout').submit();
        return false;
    });

    $("#newsletter-signout input[name='email']").blur(function() {
        $(this).validate.init(this);
    });

    $("#newsletter-signout").submit(function() {
        $("#newsletter-signout input[name='email']").trigger('blur');
        if ($(this).find('.status.error').size() == 0) {
            if (propagate.state()) {
                form = $(this);
                propagate.start();
                $('<span id="loading-form"></span>').insertAfter(".wraper-submit");
                $.post('/newsletter/zrezygnuj/', $(this).serialize(), function(response) {
                    if (response.status == true) {
                        document.location.href = form.attr('action');
                    } else {
                        $.fn.validate.error($("#newsletter-signout input[name='email']"), response.errors);
                    }
                    $("#loading-form").remove();
                    propagate.stop();
                }, "json");
            }
        }
        return false;
    });

    // $("#authorization input[name='password']").bind('focus', function() {
    //     if (this.type == 'password')
    //         $(this).unbind('focus');
    //     $(this).after('<input type="password" name="password" />').remove();
    //     $("#authorization input[name='password']").focus();
    // });

    function invoice() {
        if ($('#payment-document-invoice').is(':checked')) {
            $('#invoice').show();
            $('#invoice input').each(function() {
                $(this).attr('required', true)
            });
            $('#receipt input, #invoice input').each(function(){
                $(this).validate.init(this);
            });
        } else {
            $('#invoice').hide();
            $('#invoice input').each(function() {
                $(this).attr('required', false);
            });
            $('#receipt input, #invoice input').each(function(){
                $(this).validate.init(this);
            });
        }
    }

    invoice();

    $("input[name='payment-document']").parent().click(invoice).siblings('label').click(invoice);

    $('#order-form input').each(function(i,e) {
        $(e).blur(function() {
            $(this).validate.init(this);
        });
    });

    $('#action-realize').click(function() {
        if (propagate.state()) {
            $('#order-form input').each(function() {
                $(this).validate.init(this);
            });
            propagate.start();
            if ($('#order-form .status.error').size() == 0) {
                $.post('/zamowienie/nowe/', $('#order-form').serialize(), function(response) {
                    $.scrollTo('#order-form', 180);
                    if (response.status == true) {
                        var price = $('.total .amount').html();
                        var notes = [];
                        $('.basket-products li a.name').each(function(i, e) {
                            t = $(e).html() + ', ' + $(e).siblings('strong').html();
                            notes.push(t);
                        });
                        var note  = notes.join('|');
                        var url = '/tracker/order/price/' + price + '/note/' + note + '/';
                        $.get(url, function(request) {
                            if (request.tracker) {
                                $.get(request.tracker, function() {
                                    document.location.href = response.redirect;
                                });
                            };
                        });
                    }
                }, "json");
            } else {
                $.scrollTo($('.error').eq('0').parents('.rowset'), 180);
                propagate.stop();
            }
        }
        return false;
    });

    $('#action-payment').click(function() {
        $('#form-payment').submit();
        return false;
    })

    $('#location-switch li a').click(function() {
        document.location.href = $(this).attr('index');
    })

    $('.status.error .icon').live('mouseover', function() {
        $(this).siblings('.text').show();
    }).live('mouseout', function() {
        $(this).siblings('.text').hide();
    });

    // registration validate

    $('#register-form input').each(function(i,e) {
        $(e).blur(function() {
            $(this).validate.init(this);
        });
    });

    $('#register-form #submit').click(function() {
        $('#register-form').submit();
        return false;
    })

    $('#register-form').submit(function() {
        if (propagate.state()) {
            propagate.start();
            $('#register-form .status').remove();
            $('<span id="loading-form"></span>').insertAfter(".wraper-submit");
            $('#register-form input').each(function(i,e) {
                $(e).blur(function() {
                    $(this).validate.init(this);
                });
            });
            if ($('#register-form .status.error').size() == 0) {
                $.post(document.URL, $(this).serialize(), function(response) {
                    if (response.status == true) {
                        $.get('/tracker/registration/', function(request) {
                            if (request.tracker) {
                                $.get(request.tracker, function() {
                                    $('#register-form').parent().append('<p class="response">' + response.message + '</p>').parent().find('form').remove();
                                });
                            };
                        });

                    } else {
                        var error = response.errors;
                        for (i in error) {
                            if (error[i].length > 0) {
                                $.fn.validate.error($("input[name='"+i+"']"), error[i][0]);
                            }
                        }
                    }
                    $("#loading-form").remove();
                    propagate.stop();
                }, "json");
            } else {
                $.scrollTo('#register-form', 180);
                propagate.stop();
                $("#loading-form").remove();
            }
        }
        return false;
    });

    // contact form

    $('#contact-form input, #contact-form textarea').blur(function() {
        $(this).validate.init(this);
    });

    $('#contact-form').submit(function() {
        if (propagate.state()) {
            propagate.start();
            $('#contact-form .status').remove();
            $('<span id="loading-form"></span>').insertAfter(".wraper-submit");
            $('#contact-form input, #contact-form textarea').trigger('blur');
            if ($('#contact-form .status.error').size() == 0) {
                $.post(document.URL, $(this).serialize(), function(response) {
                    if (response.status == true) {
                        $.get('/tracker/contact/', function(request) {
                            if (request.tracker) {
                                $.get(request.tracker, function() {
                                    $('#contact-form').parent().append('<div class="response"><p>Dziękujemy</p></div>').parent().find('form').remove();
                                });
                            };
                        });
                    } else {
                        var error = response.errors;
                        for (i in error) {
                            if (error[i].length > 0) {
                                $.fn.validate.error($("input[name='"+i+"']"), error[i][0]);
                            }
                        }
                    }
                    $("#loading-form").remove();
                    propagate.stop();
                }, "json");
            } else {
                $.scrollTo('#contact-form', 180);
                propagate.stop();
                $("#loading-form").remove();
            }
        }
        return false;
    });

    $('.title .button-down').click(function() {
        $.scrollTo('#products', 320);
        return false;
    });

    $('.location-details').layer({callbackLoad: function() {
        Cufon($('#location-window h3'));
        common.location();
    }});

    $('.options-switch a').click(function() {
        var parent = $(this).parents('.price');
        var price = $(this).parents('.wraper-select').find('option').filter("[value='"+$(this).attr('index')+"']").attr('-data-price');
        parent.find('.switch-price').html(price);
        if ($(this).parents('.options-switch').hasClass('option-member')) {
            switch ($(this).attr('index')) {
                case 'yes':
                    parent.find('.switch-description').html('2 osoby');
                    break;
                case 'no':
                    parent.find('.switch-description').html('osobę');
                    break;
            }
        }
    });

    $("input[validate='phone']").keypress(function(e) {
        var correctly = [8, 9, 13, 37, 39];
        var s = String.fromCharCode(e.which);
        if ($(this).val().length >= 12)
            return false;
        if (!($.inArray(e.keyCode, correctly) == -1))
            return true;
        if ((/\d+/.test(s)))
            return true;
        return false;
    });

    $('#expedition .scroll').click(function() {
        $.scrollTo('#navi', 180);
    });

    $('.tabs .navi li').live('click', function() {
        var rel = $(this).attr('rel');
        $('.tabs #' + rel).show().siblings('div').hide();
        $(this).addClass('active').siblings('li').removeClass('active');
    })

    if ($('.page-locations').size() > 0) {
        hash = window.location.hash;
        hash = hash.split("-");
        if (hash[1]) {
            target = $("a[rel='location-"+hash[1]+"']").eq(0);
            target.trigger('click');
            return false;
        }
    }

    function update(input) {
        method = input.attr('name');
        action = input.is(':checked') ? 'zapisz' : 'wypisz';
        $.get('/konto/' + method + '/' + action + '/');
    }

    $('.page-update input').parent().click(function() {
        update($(this).find('input'));
    });
});

var calendar = {
    start: function() {
        if (document.getElementById('calendar')) {
            calendar.setup();
            calendar.tooltip();
        }
    },

    setup: function() {
        contents = $('#calendar .products');
        products = contents.find('li');
        first = ($('#calendar .body li.empty:first').index()) + 1;
        var position = [];
        $('#calendar .body li.empty').each(function() {
            position.push($(this).position());
        });
        $(products).each(function() {
            group = $(this).attr('class');
            mod = $(this).hasClass('category-1') ? 33 : 0;
            mod = $(this).hasClass('category-3') ? 17 : mod;
            index = $(this).attr('start') -1;
            offse = position[index];
            $(this).css({'left': offse.left, 'top': (offse.top + 33 + mod)});
            width = ($(this).attr('duration') * 132) - 10;
            $(this).width(width).attr('w', width);
        });

        $('#calendar .products .category-2').each(function() {
            offse = $(this).position().left;
            width = parseInt($(this).attr('w')) + parseInt(10);
            total = (parseInt(offse) + parseInt(width));
            $(this).attr('total', total);
            if (total > 924) {
                current = ((924 - offse) - 10);
                $(this).width(current);
                next =  width - current;
                var t = $(this).html();
                $('<li class="category-2">'+t+'</li>').insertAfter(this).css({'width': (next -20), 'top': ($(this).position().top + 131)});
            }
        });

        $('#calendar .products .category-3').each(function() {
            offse = $(this).position().left;
            width = parseInt($(this).attr('w')) + parseInt(10);
            total = (parseInt(offse) + parseInt(width));
            $(this).attr('total', total);
            if (total > 924) {
                current = ((924 - offse) - 10);
                $(this).width(current);
                next =  width - current;
                var orgNext = next;
                next = next > 934 ? 934 : next;
                var t = $(this).html();
                var newNext = $('<li class="category-3">'+t+'</li>').insertAfter(this).css({'width': (next -20), 'top': ($(this).position().top + 132)});
                if (orgNext > 934) {
                    current = orgNext - 934;
                    var t = $(this).html();
                    $('<li class="category-3">'+t+'</li>').insertAfter(this).css({'width': (current - 10), 'top': ($(this).position().top + 264)});
                };
            }
        });
    },

    tooltip: function() {
        $('.calendar .products li').hover(function() {
            $(this).find('.tooltip').fadeIn(300);
        }, function() {
            $(this).find('.tooltip').fadeOut(300);
        });
    }
}