document.observe('dom:loaded', function () {
    Effect.Transitions.EaseFromTo = function (pos) {
        if ((pos /= 0.5) < 1) return 0.5 * Math.pow(pos, 4);
        return -0.5 * ((pos -= 2) * Math.pow(pos, 3) - 2)
    };
    Effect.Transitions.EaseFrom = function (pos) {
        return Math.pow(pos, 4)
    };
    Effect.Transitions.EaseTo = function (pos) {
        return Math.pow(pos, 0.25)
    };
    $tumblr = {};
    $tumblr.on_textchange = {
        setup: function (elmts, _function) {
            elmts.each(function (a) {
                $(a).lastValue = $(a).value;
                $(a).observe('keyup', $tumblr.on_textchange.handler);
                $(a).observe('cut', $tumblr.on_textchange.delayedHandler);
                $(a).observe('paste', $tumblr.on_textchange.delayedHandler);
                $(a).observe('input', $tumblr.on_textchange.delayedHandler);
                $(a).observe('tumblr:textchange', _function)
            })
        },
        delayedHandler: function (e) {
            var _elmt = e.element();
            setTimeout(function () {
                $tumblr.on_textchange.triggerIfChanged(_elmt)
            }, 25)
        },
        handler: function (e) {
            var _elmt = e.element();
            $tumblr.on_textchange.triggerIfChanged(_elmt)
        },
        triggerIfChanged: function (elmt) {
            var _current = elmt.value;
            if (_current !== elmt.lastValue) {
                elmt.fire('tumblr:textchange');
                elmt.lastValue = _current
            }
        }
    };
    $tumblr.startpage = {
        init: function () {
            this._interval = 4;
            this._slide_speed = 1;
            this._standard_height = 450;
            this._min_height = 250;
            this._max_height = 500;
            this._min_viewport_width = 900;
            this._check_if_tumblelog_name_is_available_delay = 1500;
            this._slideshow = $('slideshow_container') || false;
            this._slideshow_track = $('slideshow_track');
            this._slideshow_list = $('slideshow_list');
            this._slideshow_slides = $$('#slideshow_list li');
            this._form = $('register_form');
            this._current = 1;
            this._offset_top = this._slideshow.offsetTop;
            this._offset_bottom = $('footer').getHeight() * 2;
            this._is_active = true;
            this._reactivation_timeout = false;
            this._is_sliding = false;
            this._sliding_effect = false;
            this._sliding_interval = false;
            this._global_zindex = 1;
            this._is_small_layout = false;
            this._form_fade_effect = false;
            this._is_toggling = false;
            this._is_sliding_login = false;
            this._is_reason_layout = false;
            this._is_login_layout = false;
            this._is_checking_url = false;
            this.prepare_form();
            this.copy_last();
            this.set_width();
            this.set_height();
            Event.observe(window, 'resize', function () {
                if (this._is_sliding) {
                    if (this._sliding_effect) this._sliding_effect.cancel()
                }
                this.pause();
                if (this._reactivation_timeout) window.clearTimeout(this._reactivation_timeout);
                this._reactivation_timeout = window.setTimeout(function () {
                    this.resume()
                }.bind(this), 1000);
                this.set_width();
                this.set_height();
                if (this._is_login_layout) {
                    this.reposition_login()
                }
            }.bind(this));
            $('toggle_reasons').observe('click', function (e) {
                if (!this._is_toggling) this.toggle_reasons()
            }.bind(this));
            $$('a.home').first().observe('click', function (e) {
                e.stop();
                if (!this._is_toggling) this.toggle_reasons()
            }.bind(this));
            if ($$('body').first().hasClassName('login')) {
                this.show_login_form(_instantly = true)
            }
            if ($('error_container')) {
                this._slideshow_track.hide();
                $$('a.login').first().hide();
                this._min_height = 150;
                if (!$$('body').first().hasClassName('login')) {
                    $('error_container').setStyle('margin-top: -' + $('error_container').getHeight() / 2 + 'px;')
                }
            }
            $('footer_under_reasons').update($$('.footer_links').first().innerHTML)
        },
        copy_last: function () {
            this._slideshow_list.insert({
                top: '<li>' + this._slideshow_slides.last().innerHTML + '</li>'
            });
            this._slideshow_slides = $$('#slideshow_list li')
        },
        reposition_login: function () {
            var _vp = $(document).viewport.getHeight();
            var _h1_margin_top = ((_vp - 200) / 2 - 80);
            if (_h1_margin_top < 0) _h1_margin_top = 0;
            $$('#header h1').first().setStyle('margin-top: ' + _h1_margin_top + 'px;')
        },
        set_width: function () {
            var _vp = $(document).viewport.getWidth();
            if (_vp < this._min_viewport_width) _vp = this._min_viewport_width;
            this._slideshow_slides.invoke('setStyle', 'width: ' + _vp + 'px;');
            this._slideshow_list.setStyle('width: ' + (_vp * this._slideshow_slides.length) + 'px; left: -' + (_vp * this._current) + 'px;')
        },
        set_height: function () {
            var _vp = $(document).viewport.getHeight();
            var _slideshow_height = _vp - (this._offset_top + this._offset_bottom) + 10;
            if (_slideshow_height < this._min_height) {
                _slideshow_height = this._min_height;
                this.switch_layout('small')
            } else {
                this.switch_layout('large')
            }
            if (_slideshow_height > this._max_height) {
                _slideshow_height = this._max_height
            }
            this._slideshow.setStyle('height: ' + _slideshow_height + 'px;')
        },
        slide: function () {
            var _previous = this._current;
            if (this._current + 1 > this._slideshow_slides.length - 1) {
                if (!this._is_small_layout) this._slideshow_list.setStyle('left: 0;');
                this._current = 1
            } else {
                this._current += 1
            }
            if (!this._is_small_layout) {
                this._is_sliding = true;
                this._sliding_effect = new Effect.Morph(this._slideshow_list, {
                    style: 'left: -' + ($(document).viewport.getWidth() * this._current) + 'px;',
                    duration: this._slide_speed,
                    afterFinish: function () {
                        this._is_sliding = false
                    }.bind(this),
                    transition: Effect.Transitions.EaseFromTo
                })
            } else {
                this._is_sliding = true;
                this._slideshow_slides[_previous].fade({
                    to: 0.0001,
                    duration: (_is_ie ? 0 : 0.5),
                    afterFinish: function () {
                        this._slideshow_slides[_previous].setOpacity(1);
                        this._slideshow_slides[this._current].setOpacity(0);
                        this._slideshow_list.setStyle('left: -' + ($(document).viewport.getWidth() * this._current) + 'px;');
                        this._slideshow_slides[this._current].appear({
                            duration: (_is_ie ? 0 : 0.5),
                            afterFinish: function () {
                                this._is_sliding = false
                            }.bind(this)
                        })
                    }.bind(this)
                })
            }
        },
        set_timer: function () {
            if (!$('captcha_container') && !$('error_container')) {
                if (!this._sliding_interval) {
                    this._sliding_interval = window.setInterval(function () {
                        if (this._is_active) this.slide()
                    }.bind(this), this._interval * 1000)
                }
            }
        },
        unset_timer: function () {
            if (this._sliding_interval) {
                window.clearInterval(this._sliding_interval);
                this._sliding_interval = false
            }
        },
        pause: function () {
            this._is_active = false
        },
        resume: function () {
            this._is_active = true
        },
        stop: function () {
            this.unset_timer()
        },
        start: function () {
            this.set_timer()
        },
        switch_layout: function (to) {
            if (to == 'small' && !this._is_small_layout) {
                this._is_small_layout = true;
                this._form.hide();
                $$('body').first().addClassName('small_layout');
                if (this._form_fade_effect) this._form_fade_effect.cancel();
                this._form_fade_effect = new Effect.Appear(this._form, {
                    duration: 0.3,
                    delay: 0.1
                })
            }
            if (to != 'small' && this._is_small_layout) {
                this._is_small_layout = false;
                this._form.hide();
                $$('body').first().removeClassName('small_layout');
                if (this._form_fade_effect) this._form_fade_effect.cancel();
                this._form_fade_effect = new Effect.Appear(this._form, {
                    duration: 0.3
                })
            }
        },
        prepare_form: function () {
            $('register_form').addClassName('all_empty');
            $('reasons_form_container').insert({
                top: $('register_form_container').innerHTML
            });
            var _detect_input_interval = window.setInterval(function () {
                $$('form input').each(function (a) {
                    if ($(a).readAttribute('type') != 'hidden') {
                        this.detect_input($(a))
                    }
                }.bind(this))
            }.bind(this), 100);
            $$('input[data-ghostwriter]').each(function (a) {
                $(a).wrap('span', {
                    'class': 'ghostwriter_wrapper'
                });
                $(a).up('.ghostwriter_wrapper').insert({
                    bottom: '<span class="ghostwriter_input"><span class="ghostwriter_copy">' + $(a).value + '</span>' + $(a).readAttribute('data-ghostwriter') + '</span>'
                });
                $tumblr.on_textchange.setup([$(a)], function (e) {
                    e.element().up().select('.ghostwriter_copy').first().innerHTML = e.element().value
                })
            });
            window.setTimeout(function () {
                if (_detect_input_interval) window.clearInterval(_detect_input_interval)
            }, 5000);
            $$('form input').each(function (a) {
                if (!$(a).is_prepared && $(a).readAttribute('type') != 'hidden') {
                    $(a).is_prepared = true;
                    this.detect_input($(a));
                    $(a).observe('focus', function (e) {
                        $(a).up('.input_wrapper').addClassName('blurred');
                        this.detect_input($(a));
                        this.reset_form_error($(a), e)
                    }.bind(this));
                    $(a).observe('blur', function (e) {
                        $(a).up('.input_wrapper').removeClassName('blurred');
                        this.detect_input($(a));
                        this.check_for_errors($(a), e)
                    }.bind(this));
                    $(a).observe('keyup', function (e) {
                        this.detect_input($(a));
                        if ($(a).readAttribute('data-validation-type') == 'url') {
                            if (e.keyCode != Event.KEY_TAB && e.keyCode != Event.RETURN) {
                                this.validate_url($(a));
                                this.check_for_errors($(a), e)
                            }
                        }
                    }.bind(this));
                    $(a).observe('mouseup', function () {
                        this.detect_input($(a))
                    }.bind(this));
                    $(a).observe('keydown', function () {
                        this.detect_input($(a))
                    }.bind(this))
                }
            }.bind(this));
            $('login_form_container').hide();
            $$('a.login').first().observe('click', function (e) {
                e.stop();
                e.element().blur();
                if (!this._is_sliding_login) {
                    this._is_sliding_login = true;
                    if (e.element().hasClassName('sign_up')) {
                        this.hide_login_form()
                    } else {
                        this.show_login_form()
                    }
                }
            }.bind(this))
        },
        detect_input: function (elmt) {
            if ($(elmt).value != '') {
                $(elmt).up('.input_wrapper').addClassName('filled');
                $(elmt).up('form').removeClassName('all_empty')
            } else {
                $(elmt).up('.input_wrapper').removeClassName('filled')
            }
        },
        check_for_errors: function (elmt, e) {
            var _name = $(elmt).readAttribute('name');
            var _type = $(elmt).readAttribute('data-validation-type');
            var _val = $(elmt).value;
            var _wrapper = $(elmt).up('.input_wrapper');
            var _error = false;
            if ($(elmt).up('form').readAttribute('id') == 'login_form') return false;
            if (_val.length == 0) {
                this.reset_form_error($(elmt));
                return false
            }
            if (_type == 'email') {
                if (!/\@/.test(_val)) {
                    _error = $$('body').first().readAttribute('data-invalid-email')
                }
            }
            if (_type == 'password') {
                if (_val.empty() || _val.blank() || _val.length < 5) {
                    _error = $$('body').first().readAttribute('data-invalid-password')
                }
            }
            if (_type == 'url') {
                if ($(elmt).url_is_taken) {
                    if (e.type != 'blur') {
                        this.reset_form_error($(elmt));
                        $(elmt).url_is_taken = false
                    } else {
                        this.show_form_error($(elmt), $$('body').first().readAttribute('data-taken-url'));
                        return false
                    }
                }
                if (_val.endsWith('-')) {
                    _error = $$('body').first().readAttribute('data-invalid-url-ends-with-hyphen')
                }
                if (_val.startsWith('-')) {
                    _error = $$('body').first().readAttribute('data-invalid-url-starts-with-hyphen')
                }
            }
            _error_box = _wrapper.select('.error').first() || false;
            if (_error && !_error_box) {
                this.show_form_error($(elmt), _error)
            }
            if (!_error && _error_box) {
                this.reset_form_error($(elmt))
            }
            this.disable_form($(elmt), false, e)
        },
        reset_form_error: function (elmt, e) {
            var _wrapper = $(elmt).up('.input_wrapper');
            var _error_box = _wrapper.select('.error').first() || false;
            _wrapper.removeClassName('error');
            if (_error_box) _error_box.remove();
            if (!(e && e.type == 'focus')) this.disable_form($(elmt))
        },
        show_form_error: function (elmt, _error) {
            var _wrapper = $(elmt).up('.input_wrapper');
            var _error_box = _wrapper.select('.error').first() || false;
            _wrapper.addClassName('error');
            if (_wrapper.select('.error').length == 0) {
                _wrapper.insert({
                    'bottom': '<div class="error"><div>' + _error + '</div></div>'
                })
            }
        },
        validate_url: function (elmt) {
            var _val = $(elmt).value;
            var _wrapper = $(elmt).up('.input_wrapper');
            var _error = false;
            if (this._is_checking_url) {
                window.clearTimeout(this._is_checking_url)
            }
            if (_val.length == 0 || _val.startsWith('-') || _val.endsWith('-')) {
                $(elmt).url_is_taken = false;
                return false
            }
            this.disable_form($(elmt), true);
            this._is_checking_url = window.setTimeout(function () {
                new Ajax.Request('/check_if_tumblelog_name_is_available', {
                    method: 'post',
                    parameters: {
                        'name': $('tumblelog_name').value
                    },
                    onLoading: function () {
                        $(elmt).addClassName('loading')
                    },
                    onComplete: function (t) {
                        var _result = t.responseText;
                        if (_result == 0) {
                            _error = $$('body').first().readAttribute('data-taken-url');
                            $(elmt).url_is_taken = true;
                            this.show_form_error($(elmt), _error)
                        } else {
                            this.reset_form_error($(elmt));
                            $(elmt).url_is_taken = false
                        }
                        this.disable_form($(elmt));
                        $(elmt).removeClassName('loading')
                    }.bind(this)
                })
            }.bind(this), this._check_if_tumblelog_name_is_available_delay)
        },
        disable_form: function (elmt, override, e) {
            if ($(elmt).up('form').select('.error').length > 0) {
                $(elmt).up('form').addClassName('has_errors')
            } else {
                var _has_empty_fields = false;
                var _url_is_taken_error = false;
                var _all_empty = true;
                $(elmt).up('form').select('input').each(function (a) {
                    if ($(a).value.blank()) _has_empty_fields = true;
                    if ($(a).url_is_taken) _url_is_taken_error = true;
                    if (!$(a).value.blank()) _all_empty = false
                });
                if ((_has_empty_fields && !_all_empty) || _url_is_taken_error) {
                    $(elmt).up('form').addClassName('has_errors')
                } else {
                    if (_all_empty) {
                        $(elmt).up('form').addClassName('all_empty');
                        $(elmt).up('form').removeClassName('has_errors')
                    } else {
                        $(elmt).up('form').removeClassName('has_errors');
                        $(elmt).up('form').removeClassName('all_empty')
                    }
                }
            }
            if (override) $(elmt).up('form').addClassName('has_errors')
        },
        reset_forms: function () {
            $$('#register_form').each(function (a) {
                $(a).removeClassName('has_errors');
                $(a).addClassName('all_empty');
                $(a).select('.input_wrapper').each(function (b) {
                    $(b).removeClassName('error');
                    $(b).removeClassName('filled');
                    (_error_box = $(b).select('.error').first()) ? _error_box.remove() : false
                });
                $(a).reset()
            })
        },
        supports_history_push_state: function () {
            return ('pushState' in window.history) && window.history['pushState'] !== null
        },
        show_login_form: function (_instantly) {
            document.title = $$('body').first().readAttribute('data-page-title-login');
            if ($('language_redirect_to')) {
                $('language_redirect_to').value = $$('body').first().readAttribute('data-login-url')
            }
            if (this.supports_history_push_state()) {
                window.history.pushState('', $$('body').first().readAttribute('data-page-title-login'), '/login')
            }
            var _durations = [0.4, 0.3, 0.7];
            if (_instantly) _durations = [0, 0, 0];
            this.stop();
            $$('a.login').first().update($$('a.login').first().readAttribute('data-sign-up'));
            $$('a.login').first().addClassName('sign_up');
            $('register_form_container').hide();
            this._slideshow.hide();
            $('login_form_container').appear({
                duration: _durations[0]
            });
            new Effect.Morph('toggle_reasons', {
                style: 'height: 0px;',
                duration: _durations[1],
                transition: Effect.Transitions.linear
            });
            new Effect.Morph('footer', {
                style: 'margin-top: -25px; height: 25px;',
                duration: _durations[1],
                transition: Effect.Transitions.linear
            });
            var _h1_margin_top = ((($(document).viewport.getHeight() - 200) / 2 - 80));
            if (_h1_margin_top < 0) _h1_margin_top = 0;
            new Effect.Morph($$('#header h1').first(), {
                style: 'margin-top: ' + _h1_margin_top + 'px;',
                duration: _durations[2],
                transition: Effect.Transitions.EaseFromTo,
                afterFinish: function () {
                    this._is_sliding_login = false;
                    this._is_login_layout = true;
                    $$('body').first().removeClassName('login');
                    $('login_email').focus()
                }.bind(this)
            })
        },
        hide_login_form: function () {
            document.title = $$('body').first().readAttribute('data-page-title-register');
            if ($('language_redirect_to')) {
                $('language_redirect_to').value = $$('body').first().readAttribute('data-register-url')
            }
            if (this.supports_history_push_state()) {
                window.history.pushState('', $$('body').first().readAttribute('data-page-title-register'), '/register')
            }
            this.start();
            $$('a.login').first().update($$('a.login').first().readAttribute('data-log-in'));
            $$('a.login').first().removeClassName('sign_up');
            new Effect.Morph('toggle_reasons', {
                style: 'height: 114px;',
                duration: 0.3,
                transition: Effect.Transitions.linear,
                afterFinish: function () {
                    $('login_form_container').hide();
                    $('register_form_container').appear({
                        duration: 0.4
                    });
                    this._slideshow.appear({
                        duration: (_is_ie ? 0 : 0.4),
                        afterFinish: function () {
                            this._is_sliding_login = false;
                            this._is_login_layout = false
                        }.bind(this)
                    })
                }.bind(this)
            });
            new Effect.Morph('footer', {
                style: 'margin-top: -135px; height: 135px;',
                duration: 0.3,
                transition: Effect.Transitions.linear
            });
            new Effect.Morph($$('#header h1').first(), {
                style: 'margin-top: 0px;',
                duration: 0.3,
                transition: Effect.Transitions.linear
            })
        },
        toggle_reasons: function () {
            this._is_toggling = true;
            $$('body').first().addClassName('toggling');
            this.reset_forms();
            if (!this._is_reason_layout) {
                this.stop();
                this._is_reason_layout = true;
                $('reasons').show();
                $('easiest_way').setOpacity(0);
                $('reasons_header').setOpacity(0);
                $$('#toggle_reasons .words').first().fade({
                    to: 0.0001,
                    duration: 0.4
                });
                $$('#footer .footer_links').first().fade({
                    to: 0.0001,
                    duration: 0.4
                });
                $('wrap').setStyle('height: ' + $('wrap').getHeight() + 'px; overflow: hidden;');
                $('startpage').setStyle('height: ' + $('startpage').getHeight() + 'px; overflow: hidden;');
                if (!this._is_small_layout) {
                    $('reasons_header').hide();
                    window.setTimeout(function () {
                        $('register_form_container').addClassName('fixed')
                    }.bind(this), 500)
                }
                new Effect.Morph('startpage', {
                    style: 'margin-top: -' + ($('wrap').getHeight() - 190) + 'px;',
                    duration: 0.8,
                    afterFinish: function () {
                        if (this._is_small_layout) {
                            $('main').hide()
                        }
                        $('reasons_header').appear({
                            duration: (_is_ie ? 0 : 0.4),
                            afterFinish: function () {
                                this._is_toggling = false;
                                $$('body').first().removeClassName('toggling')
                            }.bind(this)
                        });
                        $('easiest_way').appear({
                            duration: 0.4
                        });
                        $$('#footer .lip').first().fade({
                            to: 0.0001,
                            duration: (_is_ie ? 0 : 0.4)
                        });
                        $$('#footer .shadow').first().fade({
                            to: 0.0001,
                            duration: (_is_ie ? 0 : 0.4)
                        })
                    }.bind(this),
                    transition: Effect.Transitions.EaseFromTo
                })
            } else {
                if (document.viewport.getScrollOffsets().top > 0) {
                    new Effect.Tween(null, document.viewport.getScrollOffsets().top, 0, {
                        duration: 0.7
                    }, function (p) {
                        scrollTo(0, p.round())
                    })
                }
                $('easiest_way').fade({
                    to: 0.0001,
                    duration: 0.4
                });
                $('reasons_header').fade({
                    duration: (_is_ie ? 0 : 0.1),
                    to: 0.0001,
                    afterFinish: function () {
                        $('main').show();
                        $('reasons_header').hide();
                        window.setTimeout(function () {
                            $('register_form_container').removeClassName('fixed')
                        }.bind(this), 250);
                        var _tmp_startpage_height = $(document).viewport.getHeight();
                        if (_tmp_startpage_height < 580) _tmp_startpage_height = 580;
                        $('wrap').setStyle('height: auto;');
                        $('startpage').setStyle('height: ' + $(document).viewport.getHeight() + 'px; margin-top: -' + (_tmp_startpage_height - 190) + 'px;');
                        new Effect.Morph('startpage', {
                            style: 'margin-top: 0px;',
                            duration: 0.8,
                            afterFinish: function () {
                                $('startpage').setStyle('height: 100%; min-height: 580px;');
                                $('reasons').hide();
                                $$('#toggle_reasons .words').first().appear({
                                    duration: 0.4
                                });
                                $$('#footer .footer_links').first().appear({
                                    duration: 0.4
                                });
                                this._is_toggling = false;
                                this._is_reason_layout = false;
                                $$('body').first().removeClassName('toggling');
                                this.start()
                            }.bind(this),
                            transition: Effect.Transitions.EaseFromTo
                        })
                    }.bind(this)
                });
                $$('#footer .lip').first().appear({
                    duration: (_is_ie ? 0 : 0.1)
                });
                $$('#footer .shadow').first().appear({
                    duration: (_is_ie ? 0 : 0.1)
                })
            }
        }
    };
    var _is_ie6 = /MSIE 6/i.test(navigator.userAgent);
    var _is_ie = /MSIE/i.test(navigator.userAgent);
    if (!_is_ie6) {
        $tumblr.startpage.init();
        Event.observe(window, 'load', function () {
            $tumblr.startpage.set_timer()
        })
    }
});
