/*  ==========================================================================================================  */
/*  target="_blank" per Javascript anfuegen
/*  ==========================================================================================================  */

function externalLinks() {
    var anchors = $$('a[rel=external], #twitter_div a');

    anchors.each(function(a) {
        a.target = "_blank";
    });
}

/*  ==========================================================================================================  */
/*  Login Form
/*  ==========================================================================================================  */

function changeLoginForm(event) {
    Event.stop(event);
    var loginForm = $('login');
    this.blur();
    if (loginForm.style.display == 'none') {
        loginForm.show();
    } else {
        loginForm.hide();
    }
}


/*  ==========================================================================================================  */
/*  Input fields: value toggling
/*  ==========================================================================================================  */

var inputValueHash = new Hash();

function init_input_toggle() {
    var fields = $$('.toggle'); /* @TODO: Doesnt work in IE */

    fields.each(function(feld) {
        if (feld.value == '') {
            return false;
        }
        if (feld.id == '') {
            feld.id = feld.getAttribute('name');
        }
        inputValueHash.set(feld.id, feld.value);
        feld.observe('focus', inputFocus);
        feld.observe('blur', inputBlur);
    });
}
function inputFocus(event) {
    if (this.value == inputValueHash.get(this.id)) {
        this.value = '';
    }
}
function inputBlur(event) {
    if (this.value == '') {
        this.value = inputValueHash.get(this.id);
    }
}

/*  ==========================================================================================================  */
/*  Status Box Toggler
/*  ==========================================================================================================  */

function toggleStatusBox(e, originalText, closeText) {
    Event.stop(e); // Stop default behaviour of clicked hyperlink
    var trigger = Event.element(e);
    var container = $('status-form');

    container.toggle();
    if (trigger.innerHTML == originalText) {
        trigger.innerHTML = closeText;
    } else {
        trigger.innerHTML = originalText;
    }
}

/*  ==========================================================================================================  */
/*  Rezensionen schreiben
/*  ==========================================================================================================  */

function toggleCommentForms(e, tgtEl) {
    Event.stop(e); // Stop default behaviour of clicked hyperlink
    tgtEl.toggle();
}


/*  ==========================================================================================================  */
/*  Kommentar schreiben
/*  ==========================================================================================================  */

var CommentForm = Class.create({

    initialize: function(cForm, triggerClass, tgtClass, closeClass) {
        this.triggerClass = triggerClass;
        this.tgtClass     = tgtClass;
        this.closeClass   = closeClass;

        this.cForm     = cForm;
        this.trigger   = this.cForm.down('.'+this.triggerClass);
        this.target    = this.cForm.down('.'+this.tgtClass);
        this.closeLink = this.target.down('.'+this.closeClass);

        this.target.hide();
        this.cForm.observe('click', this.delegateClicks.bindAsEventListener(this));
    },

    delegateClicks: function(e) {
        var clickedEl = Event.element(e);
        if (!clickedEl.hasClassName(this.triggerClass) && !clickedEl.hasClassName(this.closeClass)) {
            return;
        }
        Event.stop(e);
        this.toggleForm();
    },

    toggleForm: function() {
        this.target.toggle();
    }
});

/*  ==========================================================================================================  */
/*  ibSlider v 1.0
/*  ==========================================================================================================  */

var SlidingBox = Class.create({

    // Don't like the CSS classnames? Change'em here...
    classNames : {
        slider          : 'slider',         //
        slideLeft       : 'slide-left',     //
        slideRight      : 'slide-right',    //
        slideMask       : 'slide-mask',     //
        slideContent    : 'slide-content'   //
    },

    setOptions: function(opt) {
        this.options = {
            infinite: false,
            increments: null,
            duration: 1,
            autoslide: false,
            delay: 3
        };
        Object.extend(this.options, opt || {});
    },

    initialize: function(sbox, opt) {
        // Set the options
        this.setOptions(opt);
        if (this.options.autoslide === true) this.options.infinite = true;

        // set up some vars
        this.slider         = sbox;
        this.container      = this.slider.down('.'+this.classNames.slideContent);
        this.mask           = this.slider.down('.'+this.classNames.slideMask);
        this.item           = this.slider.down('li');
        this.itemCount      = this.slider.select('li').size();
        this.itemWidth      = this.getItemWidth();
        this.increments     = this.getIncrements();
        this.scroll_offset  = this.itemWidth * this.increments;
        this.triggerLeft    = this.slider.down('.'+this.classNames.slideLeft);
        this.triggerRight   = this.slider.down('.'+this.classNames.slideRight);

        this.triggerLeft.style.visibility = 'visible';
        this.triggerRight.style.visibility = 'visible';
        // set up the slide-container width
        this.setSlidingContainer();
        // initially disable triggers, slideLeft always...
        this.triggerLeft.addClassName('inactive');
        // ... and slideRight, if there are too few items in the slider
        if (this.itemCount <= this.increments) {
            this.triggerRight.addClassName('inactive');
        }
        if (this.options.autoslide === true) {
            this.horizontal_slider();
        }
    },

    getItemWidth: function() {
        var itemWidth = (this.item.getWidth()) + (parseInt(this.item.getStyle('margin-right'))) + (parseInt(this.item.getStyle('margin-left')));
        return itemWidth;
    },

    // how many items to move at a time
    getIncrements: function() {
        // Either it's declared by options
        if (this.options.increments !== null) {
            this.increments = this.options.increments;
        // or increment is set to the number of visible items
        }else {
            var maskWidth = this.mask.getWidth();
            this.increments = Math.round(maskWidth / this.itemWidth);
        }
        return this.increments;
    },

    setSlidingContainer: function() {
        var containerWidth  = (this.itemWidth * this.itemCount);
        this.container.setStyle({
            left: 0,
            width: containerWidth + 'px'
        });
        // now, bind event handler to the box
        this.slider.observe('click', this.slideBoxEvents.bindAsEventListener(this));
    },

    // figure out which element was clicked and say what happens next
    slideBoxEvents: function(event) {
        var trigger = event.element();
        if ((trigger.match('.'+this.classNames.slideLeft) || trigger.match('.'+this.classNames.slideRight))) {
            Event.stop(event); // stop default behaviour of trigger element
            if (!trigger.hasClassName('inactive')) {
                this.horizontal_slider(trigger);
            }
        } else return;
    },


    // Same as slideRight, but separated to run in it's own scope (effect queue)
    autoSlide: function(ctx, trigger, scroll_offset, duration, lastMargin, max_position, maskSize, startOver) {
        var triggerLeft = ctx.triggerLeft;
        if (ctx.options.autoslide) {
            window.clearTimeout(ctx.timeoutId);
        }

        new Effect.Move(ctx.container, {
            x: -(scroll_offset),
            y: 0,
            ctx:ctx,
            mode: 'relative',
            duration: duration,
            queue: {
                position: 'end', 
                scope: 'autoslide', 
                limit: 1
            },
            afterFinish: function() {
                max_position = max_position - scroll_offset - lastMargin;
                // toggle triggers inactive-state
                if (max_position <= maskSize) {
                    trigger.addClassName('endpoint');
                }
                triggerLeft.removeClassName('inactive');
                this.ctx.horizontal_slider();
            }
        });
    },

    slideRight: function(trigger, scroll_offset, duration, lastMargin, max_position, maskSize, startOver) {
        var triggerLeft = this.triggerLeft;

        if (this.options.autoslide) {
            window.clearTimeout(this.timeoutId);
        }
        new Effect.Move(this.container, {
            x: -(scroll_offset),
            y: 0,
            ctx:this,
            mode: 'relative',
            duration: duration,
            queue: {
                position: 'end', 
                scope: 'anims', 
                limit: 1
            },
            afterFinish: function() {
                max_position = max_position - scroll_offset - lastMargin;
                // toggle triggers inactive-state
                if (max_position <= maskSize) {
                    if (startOver === true) {
                        trigger.addClassName('endpoint')
                    } else {
                        trigger.addClassName('inactive');
                    }
                }
                triggerLeft.removeClassName('inactive');
                if (this.ctx.options.autoslide) {
                    this.ctx.horizontal_slider();
                }
            }
        });
    },

    slideLeft: function(trigger, scroll_offset, duration) {
        var triggerRight    = this.triggerRight;
        var scroll_target   = this.container;

        if (this.options.autoslide) {
            window.clearTimeout(this.timeoutId);
        }
        new Effect.Move(scroll_target, {
            x: scroll_offset,
            y: 0,
            mode: 'relative',
            duration: duration,
            ctx: this,
            queue: {
                position: 'end', 
                scope: 'anims', 
                limit: 1
            },
            afterFinish: function() {
                actual_position = parseInt(scroll_target.getStyle('left'));
                // toggle triggers inactive-state
                if (actual_position >= 0) {
                    trigger.addClassName('inactive');
                }
                triggerRight.removeClassName('inactive').removeClassName('endpoint');
                if (this.ctx.options.autoslide) {
                    this.ctx.horizontal_slider();
                }
            }
        });
    },

    slideBack: function(duration, ctx) {
        if (ctx == '' || ctx === undefined) {
            ctx = this;
        }
        var triggerLeft = ctx.triggerLeft;
        var triggerRight= ctx.triggerRight;
        var auto_slide  = ctx.options.autoslide;

        new Effect.Move(ctx.container, {
            x: 0,
            y: 0,
            ctx:ctx,
            mode: 'absolute',
            duration: duration,
            queue: {
                position: 'end', 
                scope: 'anims', 
                limit: 1
            },
            afterFinish: function() {
                triggerRight.removeClassName('endpoint').removeClassName('inactive');
                triggerLeft.addClassName('inactive');
                if (auto_slide === true) {
                    this.ctx.horizontal_slider();
                }
            }
        });
    },

    horizontal_slider: function(trigger) {
        var maskSize        = this.mask.getWidth();
        var lastMargin      = parseInt(this.item.getStyle('margin-right'));
        var startOver       = this.options.infinite;
        var duration        = this.options.duration;
        var scroll_offset   = this.scroll_offset;
        var actual_position = (Math.abs(parseFloat(this.container.style.left)));
        var max_position    = parseInt(this.container.getStyle('width')) - actual_position;
        var containerWidth  = (this.itemWidth * this.itemCount);
        // auto slide
        if (this.options.autoslide === true && trigger === undefined) {
            var delay   = this.options.delay;
            ctx     = this;
            if (max_position <= (maskSize + lastMargin)) {
                slideBack       = this.slideBack;
                this.timeoutId  = window.setTimeout(function() {
                    slideBack(duration, ctx)
                }, delay*1000);
            } else {
                trigger         = this.triggerRight;
                autoSlide       = this.autoSlide;
                this.timeoutId  = window.setTimeout(function() {
                    autoSlide(ctx, trigger, scroll_offset, duration, lastMargin, max_position, maskSize, startOver)
                }, delay*1000);
            }
        }
        // Slide right
        else if (trigger.hasClassName(this.classNames.slideRight)) {
            var newOffset = containerWidth - maskSize - actual_position;
            if (scroll_offset > newOffset) {
                var newInc = Math.round(newOffset / this.itemWidth);
                scroll_offset = this.itemWidth * newInc;
            }
            // if set to infinite, start over
            if (startOver === true && trigger.hasClassName('endpoint')) {
                this.slideBack(duration);
            }
            // standard movement
            if (max_position > maskSize) {
                this.slideRight(trigger, scroll_offset, duration, lastMargin, max_position, maskSize, startOver);
            }
        // Slide left
        } else if (trigger.hasClassName(this.classNames.slideLeft)) {
            if (actual_position < scroll_offset) {
                this.slideBack(duration);
            } else if (actual_position != '0') {
                this.slideLeft(trigger, scroll_offset, duration);
            }
        }
    }
});

/*  ==========================================================================================================  */
/*  Scroll To
/*  ==========================================================================================================  */
function myScrollTo(container, element) {

    if (document.all) {
        container.scrollLeft = element.offsetLeft;
        container.scrollTop = element.offsetTop;
    } else {
        var containerXY = container.cumulativeOffset();
        var targetXY    = element.cumulativeOffset();

        container.scrollLeft = targetXY[0] - containerXY[0];
        container.scrollTop  = targetXY[1] - containerXY[1];
    }
}


/*  ==========================================================================================================  */
/*  Textarea Character Counter
/*  ==========================================================================================================  */

var TextCounter = Class.create({

    setOptions: function(options) {
        this.options = {
            minimum: 0,
            maximum: 200
        };
        Object.extend(this.options, options || {});
    },

    initialize: function(textArea, options) {
        this.setOptions(options);
        this.textArea   = textArea;
        this.counterEl  = textArea.up().down('.counter');
        this.counter();

        this.textArea.observe('keydown', this.counter.bindAsEventListener(this));
        this.textArea.observe('keyup', this.counter.bindAsEventListener(this));
    },

    // MW
    // More sophiscticated counter for min/max display
    counter: function() {
        var current_size    = this.textArea.value.length;
        var chars_left      = this.options.maximum - current_size;
        // Find submit button of the form
        var submit          = (this.textArea.up('form').down('button')) ? this.textArea.up('form').down('button') : this.textArea.up('form').down('input[type="submit"]');

        if (chars_left >= 0 || this.options.maximum == 0) {
            if (this.options.minimum > 0) {
                if(submit) {
                    // If minimum is set disable submit button until minimum is reached
                    if (this.options.minimum >= this.textArea.value.length) {
                        submit.setAttribute('disabled', 'disabled');
                        submit.addClassName('btn-inactive');
                    } else {
                        submit.removeAttribute('disabled');
                        submit.removeClassName('btn-inactive');
                    }
                }
                if (this.options.maximum > 0) {
                    if (this.textArea.value.length >= 1) {
                        var chars_must = (this.textArea.value.length <= this.options.minimum) ? (this.options.minimum-this.textArea.value.length) : 0;
                        this.counterEl.update('(noch min. '+chars_must+' Zeichen, noch max. '+chars_left+' Zeichen)');
                    } else {
                        this.counterEl.update('(min. '+this.options.minimum+' Zeichen, max. '+chars_left+' Zeichen)');
                    }
                } else {
                    if (this.textArea.value.length >= 1) {
                        var chars_must = (this.textArea.value.length <= this.options.minimum) ? (this.options.minimum-this.textArea.value.length) : 0;
                        this.counterEl.update('(noch min. '+chars_must+' Zeichen)');
                    } else {
                        this.counterEl.update('(min. '+this.options.minimum+' Zeichen)');
                    }
                }
            } else {
                this.counterEl.update('(noch max. '+chars_left+' Zeichen)');
            }
        } else {
            this.textArea.value = this.textArea.value.slice(0, this.options.maximum);
        }
    }
});

function watchPseudonym(event) {
    var trigger = Event.element(event);

    if ($F(trigger) != $F('manuscript_pseudonym_initial')) {
        $('pseudonym_warning').innerHTML = '<ul class="error_list"><li>Die Änderung wird nicht automatisch auf ein bestehendes Cover übernommen!</li></ul>';
    }else {
        $('pseudonym_warning').innerHTML = '';
    }
}

function watchManuscriptTitle(event) {
    var trigger = Event.element(event);

    if ($F(trigger) != $F('manuscript_pseudonym_initial')) {
        $('manuscript_title_warning').innerHTML = '<ul class="error_list"><li>Die Änderung wird nicht automatisch auf ein bestehendes Cover übernommen!</li></ul>';
    } else {
        $('manuscript_title_warning').innerHTML = '';
    }
}

function changeChapter(event, url_base, tgtContainer) {
    initChapterMovement();

    // Ajax required data
    var trigger   = Event.element(event);
    var url_id    = $F(trigger);
    var url_full  = url_base + url_id;
    // CKEditor data
    var areaID    = tgtContainer.down('textarea').getAttribute('id');
    if (CKEDITOR.instances[areaID]) {
        CKEDITOR.instances[areaID].destroy();
    }
    new Ajax.Updater(tgtContainer, url_full, {
        evalScripts: true
    });
}

function changeCategory(event, url_base) {
    var tgtContainer = $('genre_select');
    var trigger   = Event.element(event);
    var url_id    = $F(trigger);
    
    var url_full  = url_base + url_id;
    console.log(url_full);
    new Ajax.Updater(tgtContainer, url_full);
}

function changeFormStep3Panel2LabelDescription(event, url_base) {
    var tgtContainer = $('form_step3_panel2_label_description');
    var trigger   = Event.element(event);
    var url_id    = $F(trigger);
    var url_full  = url_base + url_id;
    new Ajax.Updater(tgtContainer, url_full);
}

function changeFormStep3Panel2LabelExpose(event, url_base) {
    var tgtContainer = $('form_step3_panel2_label_expose');
    var trigger   = Event.element(event);
    var url_id    = $F(trigger);
    var url_full  = url_base + url_id;

    new Ajax.Updater(tgtContainer, url_full);
}

function changeFormStep3Panel2LabelFigures(event, url_base) {
    var tgtContainer = $('form_step3_panel2_label_figures');
    var trigger   = Event.element(event);
    var url_id    = $F(trigger);
    var url_full  = url_base + url_id;

    new Ajax.Updater(tgtContainer, url_full);
}

/*  ==========================================================================================================  */
/*  Countdown
/*  ==========================================================================================================  */

var Countdown = Class.create({

    setOptions: function(options) {
        this.options = {
            leadingZero: false
        };
        Object.extend(this.options, options || {});
    },

    initialize: function(container, futureDate, pEx, options) {
        this.container = container;
        this.setOptions(options);

        this.currentDate = new Date();
        this.currentTime = this.currentDate.getTime();

        this.futureDate = new Date(futureDate);
        this.futureTime = this.futureDate.getTime();

        this.timeSpan = this.futureTime - this.currentTime;

        this.total_sec = Math.floor(this.timeSpan / 1000);

        var remainingDays = this.getChunks(86400, 100000);
        var remainingHrs  = this.getChunks(3600, 24);
        var remainingMin  = this.getChunks(60, 60);
        var remainingSec  = this.getChunks(1, 60);

        if (this.total_sec > 0) {
            this.container.update('<p>'+remainingDays+' t : '+remainingHrs+' s : '+remainingMin+' m : '+remainingSec+' s</p> <em>bis Wettbewerbsende</em>');
        }else {
            this.container.update('<p>Dieser Wettbewerb ist beendet!</p>');
            pEx.stop();
        }
    },

    getChunks: function(num1, num2) {
        var resultStr = Math.floor( (this.total_sec / num1) % num2).toString();

        if (this.options.leadingZero === true && resultStr.length < 2) {
            resultStr = '0' + resultStr;
        }
        return resultStr;
    }

});

/*  ==========================================================================================================  */
/*  TabView
/*  ==========================================================================================================  */

var TabView = Class.create({

    initialize: function(container, headerClass, bodyClass) {
        this.container = container;
        this.headEls   = this.container.select('.'+headerClass);
        this.bodyEls   = this.container.select('.'+bodyClass);
        this._prefix   = container.getAttribute('id');

        this.createHTML();

        this.changeTabs($(this.tabLinks[0].hash.substr(1)));

        this.attachEvents();
    },

    createHTML:function() {
        // Create Nav
        this.tabNav = new Element('ul', {
            id: this._prefix+'_tabnav'
        }).addClassName('tabnav'); // IE8 needs "addClassName"

        this.headEls.each(function(el, i) {
            var itemLI = new Element('li');
            var itemA  = new Element('a', {
                href: '#'+this._prefix+'_tabcontent_'+i
            }).update(el.innerHTML);
            itemLI.update(itemA);
            this.tabNav.insert(itemLI);
        }.bind(this));

        // Create Content
        this.tabContainer = new Element('ul', {
            id: this._prefix+'_tabcontainer'
        }).addClassName('tabcontainer'); // IE8 needs "addClassName"

        this.bodyEls.each(function(el, i) {
            var itemLI      = new Element('li', {
                id: this._prefix+'_tabcontent_'+i
            }).addClassName('tabContent'); // IE8 needs "addClassName"
            var itemContent = el.innerHTML;
            itemLI.update(itemContent);
            this.tabContainer.insert(itemLI);
        }.bind(this));

        this.container.update(this.tabNav).insert(this.tabContainer);
        this.tabLinks        = this.tabNav.select('a');
        this.tabContentItems = this.tabContainer.select('.tabContent');
    },

    attachEvents: function() {
        this.tabNav.observe('click', this.delegateClicks.bindAsEventListener(this));
    },

    delegateClicks: function(e) {
        Event.stop(e);
        this.trigger = Event.element(e);

        if (!this.trigger.match('a')) {
            return;
        }
        this.targetContainer = $(this.trigger.hash.substr(1));
        this.changeTabs(this.targetContainer);
    },

    changeTabs: function(targetContainer) {

        if (!this.trigger) {
            this.trigger = this.tabLinks[0];
        }
        if (!this.tabNavItems) {
            this.tabNavItems = this.tabNav.select('li');
        }
        this.tabContentItems.invoke('hide');
        targetContainer.show();

        this.tabNavItems.invoke('removeClassName', 'active');
        this.trigger.up('li').addClassName('active');
    }
});

/*  ==========================================================================================================  */
/*  Rating Stars
/*  ==========================================================================================================  */

var Rating = Class.create({

    initialize: function(ratingBox) {
        this.ratingBox = ratingBox;
        this.ratingLinks = this.ratingBox.select('a');
        this.hiddenField = $('rating');
        this.attachEvents();
    },

    attachEvents: function() {
        this.ratingBox.observe('click', this.delegateClicks.bindAsEventListener(this));
    },

    delegateClicks: function(e) {
        Event.stop(e);
        this.trigger = Event.element(e);

        if (!this.trigger.match('a')) {
            return;
        }
        this.changeRating();
    },

    changeRating: function() {
        this.ratingLinks.invoke('removeClassName', 'active');
        this.trigger.addClassName('active');
        this.hiddenField.setAttribute('value', this.trigger.hash.substr(1));
    }
});


/*  ==========================================================================================================  */
/*  Social bookmarks
/*  ==========================================================================================================  */

function socialize(container) {
    var url   = location.href;
    var title = document.title;

    Element.insert(container, '<li class="delicious"><a target="_blank" title="Delicious" href="http://del.icio.us/post?url='+ url +'&amp;title='+ title +'">Link auf Delicious teilen</a></li>');
    Element.insert(container, '<li class="stumple-upon""><a target="_blank" title="Stumble Upon" href="http://www.stumbleupon.com/submit?url='+ url +'&amp;title='+ title +'">Link auf StumbleUpon teilen</a></li>');
    Element.insert(container, '<li class="dig"><a target="_blank" title="Digg" href="http://digg.com/submit?phase=2&url='+ url +'&amp;title='+ title +'">Link auf Digg teilen</a></li>');
    Element.insert(container, '<li class="technorati"><a target="_blank" title="Technorati" href="http://www.technorati.com/faves?add='+ url +'">Link auf Technorati teilen</a></li>');
    Element.insert(container, '<li class="linkedin"><a target="_blank" title="Linkarena" href="http://linkarena.com/bookmarks/addlink/?url='+ url +'&title='+ title +'">Link auf Linkarena teilen</a></li>');
    Element.insert(container, '<li class="mr-wong"><a target="_blank" title="Mr. Wong"href="http://www.mister-wong.de/index.php?action=addurl&bm_url='+ url +'&amp;bm_description='+ title +'">Link auf Mr.Wong teilen</a></li>');
    Element.insert(container, '<li class="google"><a target="_blank" title="Google Bookmarks" href="http://www.google.com/bookmarks/mark?op=add&hl=de&amp;bkmk='+ url +'&title='+ title +'">Link auf Google teilen</a></li>');
}
/*  ==========================================================================================================  */
/*  Twitter
/*  ==========================================================================================================  */

/*
 * @package Twitter
 * @param   twitters (json file)
 * @return  <string> of twitter entrys
 */
function twitterCallback(twitters) {
    var statusHTML = [];
    var liclass = ' ';
    for (var i=0; i < twitters.length ; i++){

        if(i == 3){
            break;
        }
        if(i == 0 || i == 2 ){
            liclass = 'variant';
        }else{
            liclass = ' ';
        }
        var username = twitters[i].user.screen_name;
        var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
            return '<a href="'+url+'">'+url+'</a>';
        }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
            return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
        });
        statusHTML.push('<li class="clearfix '+liclass+'">'+status+' <p><a href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'">'+relative_time(twitters[i].created_at)+'</a></p></li>');
    }
    document.getElementById('twitter_update_list').innerHTML = statusHTML.join('');
}

/*  ==========================================================================================================  */
/*  Community
/*  ==========================================================================================================  */
// MW
var CommunityHelper = Class.create({

    initialize: function() {
    },

    updateAnnouncementState: function(selector) {
        $(selector).reset();
        initCharacterCounter();
        Shadowbox.open({
            content:    '/myneobooks/my_social_feed_publish',
            player:     "iframe",
            width:      700,
            height:     450,
            handleOversize: 'none'
        });
    }
});
var Community = new CommunityHelper();

/*
 * @package Twitter
 * @param time_value
 * @return <string> of relative time in german
 */
function relative_time(time_value) {
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);

    if (delta < 60) {
        return 'vor weniger als einer Minute';
    } else if(delta < 120) {
        return 'vor ungefähr einer Minute';
    } else if(delta < (60*60)) {
        return 'vor '+(parseInt(delta / 60)).toString() + ' Minuten';
    } else if(delta < (120*60)) {
        return 'vor ungefähr einer Stunde';
    } else if(delta < (24*60*60)) {
        return 'vor ungefähr ' + (parseInt(delta / 3600)).toString() + ' Stunden';
    }else if(delta < (48*60*60)) {
        return 'gestern';
    } else {
        return 'vor '+(parseInt(delta / 86400)).toString() + ' Tagen';
    }
}

function updatePublishingState(id) {
    var panel = $('panel7');
    var uri   = '/manuscript/CheckPublishStatus?id='+id;

    new Ajax.Updater(panel, uri, {
        onComplete: function() {
            initManuscriptPreview();
        }
    });
}


function initManuscriptPreview()
{
    if ($('showManuscriptPreview')) {
        var prev_sb_link  = $('showManuscriptPreview');
        var prev_sb_uri   = $('showManuscriptPreview').href;
        Shadowbox.setup(prev_sb_link, {
            content: prev_sb_uri,
            player: 'iframe',
            title: 'Vorschau',
            height: 542,
            width: 710
        });
    }
}

function initCategoryLoader()
{
    // Category Loader
    if ($('manuscript_category_id')) {
        if (!Prototype.Browser.IE) {
            $('manuscript_category_id').observe('change', changeCategory.bindAsEventListener(this, '/manuscript/ajax_genre_select?category_id='));
            $('manuscript_category_id').observe('change', changeFormStep3Panel2LabelDescription.bindAsEventListener(this, '/manuscript/ajaxFormStep3Panel2LabelDescription?category_id='));
            $('manuscript_category_id').observe('change', changeFormStep3Panel2LabelExpose.bindAsEventListener(this, '/manuscript/ajaxFormStep3Panel2LabelExpose?category_id='));
            $('manuscript_category_id').observe('change', changeFormStep3Panel2LabelFigures.bindAsEventListener(this, '/manuscript/ajaxFormStep3Panel2LabelFigures?category_id='));
        } else {
            $('manuscript_category_id').observe('click', changeCategory.bindAsEventListener(this, '/manuscript/ajax_genre_select?category_id='));
            $('manuscript_category_id').observe('click', changeFormStep3Panel2LabelDescription.bindAsEventListener(this, '/manuscript/ajaxFormStep3Panel2LabelDescription?category_id='));
            $('manuscript_category_id').observe('click', changeFormStep3Panel2LabelExpose.bindAsEventListener(this, '/manuscript/ajaxFormStep3Panel2LabelExpose?category_id='));
            $('manuscript_category_id').observe('click', changeFormStep3Panel2LabelFigures.bindAsEventListener(this, '/manuscript/ajaxFormStep3Panel2LabelFigures?category_id='));
        }
    }
}

function initPseudonymAutocompleter()
{
    if ($('manuscript_pseudonym')) {
        new Ajax.Autocompleter('manuscript_pseudonym', 'update_pseudonym', '/manuscript/autocompletePseudonym');
    }
}

function initPseudonymWatcher()
{
    if ($('manuscript_pseudonym')) {
        $('manuscript_pseudonym').observe('keyup', watchPseudonym.bindAsEventListener(this));
    }
}
function initManuscriptTitleWatcher()
{
    if ($('manuscript_title')) {
        $('manuscript_title').observe('keyup', watchManuscriptTitle.bindAsEventListener(this));
    }
}
function initCharacterCounter()
{
    // MW
    // Generic Chracter-Counter
    if ($$('textarea[class*=limited-]').size() >= 1 || $$('input[class*=limited-]').size() >= 1) {
        $$('textarea[class*=limited-]','input[class*=limited-]').each(function(txtfield) {
            var is_range = txtfield.readAttribute('class').match(/limited-(\d+)-(\d+)(.*)/img);
            if (is_range) {
                var minimum = txtfield.readAttribute('class').replace(/(.*)?limited-(\d+)(.*)/img,'$2');
                var maximum = txtfield.readAttribute('class').replace(/(.*)?limited-(\d+)-(\d+)(.*)/img,'$3');
            } else {
                var minimum = 0;
                var maximum = txtfield.readAttribute('class').replace(/(.*)?limited-(\d+)(.*)/img,'$2');
            }
            new TextCounter(txtfield, {
                minimum: minimum,
                maximum: maximum
            });
        });
    }
}
function initChapterEditor()
{
    // Manuscript loader
    if ($('chapterList')) {
        $('chapterList').select('input[type=radio]').each(function(r) {
            var url_base = '/manuscript/selectChapter?id=';
            var tgtContainer = $('panel4_chapter');
            if (!Prototype.Browser.IE) {
                r.observe('change', changeChapter.bindAsEventListener(this, url_base, tgtContainer));
            } else {
                r.observe('click', changeChapter.bindAsEventListener(this, url_base, tgtContainer));
            }
        });
    }
}
var chapter_movement_initialized = false;
// MW
// Chapter Movement with AJAX
function initChapterMovement() {
    //console.log('#######################');
    if (!chapter_movement_initialized) {
        $$('.chapter-item').each(function(chapter_item) {
            var item = chapter_item;
            var chapter_nav_items = new Array();
            if (item.down('span.down')) chapter_nav_items.push(item.down('span.down'));
            if (item.down('span.up')) chapter_nav_items.push(item.down('span.up'));
            if (chapter_nav_items) {
                //console.log('---------------');
                chapter_nav_items.each(function(chapter_nav_item) {
                    var move_direction = chapter_nav_item.readAttribute('class');
                    //console.log(chapter_nav_item);
                    //console.log(move_direction);
                    //console.log(item.readAttribute('id').replace(/chapter-(\d+)/img,'$1'));
                    chapter_nav_item.observe('click', function(e) {
                        e.preventDefault();
                        chapter_movement_initialized = false;
                        // ?rand='+Math.random() is important for IE that dumb a**
                        new Ajax.Request('/manuscript/moveChapter?rand='+Math.random(), {
                            method:'get',
                            parameters: {
                                id: item.readAttribute('id').replace(/chapter-(\d+)/img,'$1'), 
                                direction: move_direction
                            },
                            onSuccess: function(transport){
                                // Reload Chapter-Nav
                                var response = transport.responseText;
                                //console.log(response);
                                $('chapterList').replace(response);
                                //console.log($('chapterList'));
                                // Reset CKEditor
                                var id = item.readAttribute('id').replace(/chapter-(\d+)/img,'$1');
                                var url_base = '/manuscript/selectChapter?id=';
                                var tgtContainer = $('panel4_chapter');
                                var url_full  = url_base + id;
                                if (CKEDITOR.instances[id]) {
                                    CKEDITOR.instances[id].destroy();
                                }
                                new Ajax.Updater(tgtContainer, url_full, {
                                    evalScripts: true
                                });
                                initChapterEditor();
                                initChapterMovement();
                            }
                        });
                    });
                });
            }
        });
    }
    chapter_movement_initialized = true;
}

function renewAjaxInplaceEditorForAnnouncementComments(view) {
    if ($$('#announcements .kommentar').length > 0) {
        $$('#announcements .kommentar').each(function(comment) {
            var comment_id = comment.readAttribute('id');
            var id = comment.readAttribute('rel');
            var view_url = (view == 'more') ? '/user/moreRecentAnnouncements/' : '/user/recentAnnouncements/';
            new Ajax.InPlaceEditor(
                'announcement-comment-'+id,
                '/myneobooks/announcement_comment_inline_edit/'+id,
                {
                    cancelText:'Abbrechen',
                    cols:4,
                    externalControl:'announcement-comment-'+id+'-link',
                    highlightColor:'#fbefe2',
                    highlightEndColor:'#fbefe2',
                    loadTextURL:'',
                    okText:'Absenden',
                    rows:4,
                    savingText:'Speichere Daten',
                    onComplete: function(transport, element) {
                        new Ajax.Updater('recent-announcements', view_url+'id/'+id, {
                            asynchronous:true, 
                            evalScripts:false, 
                            onComplete:function(request, json){
                                renewAjaxInplaceEditorForAnnouncementComments()
                            }
                        });
                    }
                }
                );
        });
    }
}

var Accordeon = Class.create({

    setOptions: function(options) {
        this.options = {
            type: 'box',
            open: 1,
            stayOpen: true,
            animate: true,
            duration: 1
        };
        //MW
        // If a panel is requested by anchor in uri like #panel4, overide the initial open panel
        var uri = window.location.href;
        var panel_anchor = uri.match(/(.+)([#][\w]+[\d])(.*)/img);
        var panel;
        if(panel_anchor) {
            panel = uri.replace(/(.+)([#][\w]+)([\d])(.*)/img, '$3');
            if (panel) {
                this.options.open = panel;
            }
        }
        Object.extend(this.options, options || {});
    },

    initialize: function(parentEl, triggerClass, targetClass, options) {
        this.setOptions(options);
        this.triggerClass = triggerClass;
        this.targetClass  = targetClass;
        this.triggers     = parentEl.select('.'+this.triggerClass);
        this.targets      = parentEl.select('.'+this.targetClass);
        if (this.triggers.length == 0) return;

        this.targets.invoke('hide').invoke('addClassName', 'closed');
        this.triggers.invoke('addClassName', 'closed');

        if (this.options.open) {
            this.targets[this.options.open-1].show().removeClassName('closed');
            this.triggers[this.options.open-1].removeClassName('closed');
        }
        // Observe for "click" if it's a Box Header
        if (this.options.type == 'box') {
            this.triggers.each(function(el) {
                el.observe('click', this.changeState.bindAsEventListener(this, el));
            }.bind(this));
        }
        // Observe for "change" if it's a radio button
        if (this.options.type == 'radio') {
            this.triggers.each(function(el) {
                if (!Prototype.Browser.IE) {
                    el.observe('change', this.changeState.bindAsEventListener(this, el));
                } else {
                    el.observe('click', this.changeState.bindAsEventListener(this, el));
                }
            }.bind(this));
        }
    },

    openTarget: function(trigger, actual_target) {
        // Always close all containers before opening a new one
        this.closeAll(trigger);

        //Animate?
        if (this.options.animate === true) {
            new Effect.BlindDown(actual_target, {
                duration: this.options.duration,
                queue: {
                    position: 'end', 
                    scope: 'accMoves', 
                    limit: 3
                },
                afterFinish: function() {
                    trigger.removeClassName('closed');
                }
            });
        //Don't animate
        } else {
            actual_target.show();
            trigger.removeClassName('closed');
        }
        actual_target.removeClassName('closed');
    },

    closeAll: function(trigger) {
        //Animate?
        if (this.options.animate === true) {
            this.targets.each(function(tgt) {
                if (tgt.hasClassName('closed')) return;
                new Effect.BlindUp(tgt, {
                    duration: this.options.duration / 2,
                    queue: {
                        position: 'end', 
                        scope: 'accMoves', 
                        limit: 3
                    }
                });
            }.bind(this));
        //Don't animate
        } else {
            this.targets.invoke('hide');
        }
        this.triggers.invoke('addClassName', 'closed');
        this.targets.invoke('addClassName', 'closed');
    },

    changeState: function(event) {
        var trigger = event.element();
        if (trigger.match('a')) {
            event.stop();
        } else if (!trigger.hasClassName('closed')) {
            return false;
        }

        // Anything inside the header was clicked?
        if (!trigger.hasClassName(this.triggerClass)) {
            trigger = trigger.up('.'+this.triggerClass);
        }
        // stayOpen is false and an opened container is clicked: close all, open nothing
        if (!trigger.hasClassName('closed') && this.options.stayOpen === false) {
            this.closeAll(trigger);
        // Always open any closed containers
        } else if (trigger.hasClassName('closed')) {
            var actual_target = trigger.next('.'+this.targetClass);
            this.openTarget(trigger, actual_target);
        }
        if (this.options.type == 'box') {
            trigger.down('a').blur();
        }
    }
});

function showAjaxLoading() {
    new Effect.Opacity('wrapper', {
        from: 1.0, 
        to: 0.3, 
        duration: 0.7
    });
    new Effect.toggle('loading', 'appear');
}

function hideAjaxLoading() {
    new Effect.Opacity('wrapper', {
        from: 0.3, 
        to: 1, 
        duration: 0.7
    });
    new Effect.toggle('loading', 'appear');
}

function setContractDate(){
    jQuery('#frame_contract_file_download').attr('href','#');
    jQuery('#frame_contract_file_download').hide();  
    if(jQuery('.manuscript_frame_contract_date').length > 0 && jQuery('.step2_manuscript_upload_opt_in').is(":visible") ){
        contract_id=jQuery('#manuscript_contract_id').val();
        if(contract_id>0){
            jQuery.getJSON('/manuscript/frameContractDate?q='+contract_id, function(data) {
                jQuery.each(data, function(key, val) {
                    jQuery('.manuscript_frame_contract_date').html(val);
                });
            });
            jQuery.getJSON('/manuscript/frameContractHasFile?q='+contract_id, function(data) {
                if(data['frameContractHasFile']==true){
                    jQuery('#frame_contract_file_download').attr('href','/manuscript/frameContractDownload?id='+contract_id);
                    jQuery('#frame_contract_file_download').show();                    
                }else{
                    jQuery('#frame_contract_file_download').attr('href','#');
                    jQuery('#frame_contract_file_download').hide();                    
                }
            });
        }
    }
}
/**
 * Wenn die Seite /buch-schreiben neu geladen wird,
 * dann wird hierdurch sichergestellt das evtl. schon gewählte Genre auch wieder ausgewählt werden
 */
function reload_genre_select(){
    if(jQuery('#manuscript_category_id').length && jQuery('#lastSelectedGenreValue').length){
        cat=jQuery('#lastSelectedCategoryValue').html();
        jQuery('#genre_select').load('/manuscript/ajax_genre_select?category_id='+cat,function() {
             genre_id=jQuery('#lastSelectedGenreValue').html();
            jQuery("#manuscript_genre_id option[value='"+genre_id+"']").attr("selected", "selected");
        });
    }
}
 
function setAdditionalContractInfo(){
    if(jQuery('#manuscript_title').length > 0 && jQuery('.step2_manuscript_upload_opt_in').is(":visible") ){
        title=jQuery('#manuscript_title').val();
        jQuery('.manuscript_working_title').html('"'+title+'"');
        setContractDate();
    }
}

function toggle_genre_autoselect_rown_and_contract(){
    
    if(jQuery("#manuscript_category_id").length > 0 && jQuery("#nb_singles_category_id").length > 0){
        tds_autoselect_genre();
        var single_id=jQuery('#nb_singles_category_id').html();
        if(jQuery("#manuscript_category_id").val()==single_id){
            jQuery('.step2_manuscript_upload_opt_in').show();
        }else{
            jQuery('.step2_manuscript_upload_opt_in').hide();
            unsetAdditionalContractInfo();
        }
    }
    setAdditionalContractInfo();
}

function unsetAdditionalContractInfo(){
    if(jQuery('.step2_manuscript_upload_opt_in').is(":visible")){
        $('#manuscript_row_id select>option:eq(0)').attr('selected', true);
        $('#manuscript_contract_id select>option:eq(0)').attr('selected', true);
        $('input[name=manuscript[opt_in_agreement]]').attr('checked', false);
        $('input[name=manuscript[opt_in_agreement]2]').attr('checked', false);
    }
}

function tds_autoselect_genre()
{
    var cat_id = $("manuscript_category_id").getValue();
    var running_event_cats = jQuery('#active_events_categories').html().split(",");
    var is_active_event = false;

    for( i=0; i<running_event_cats.length; i++)
    {
        if( cat_id==running_event_cats[i])
        {
            is_active_event = true;
            break;
        }    
    }    

    if( is_active_event)
        $('genre_select').hide();
    else
        $('genre_select').show();
}

function tds_toggle_terms_of_use()
{
    if($("manuscript_category_id")!=undefined && $("single_category_id")!=undefined){
        var cat_id = $("manuscript_category_id").getValue();
        var single_id=$("single_category_id").getValue();
        
        var running_event_cats = jQuery('#active_events_categories').html().split(",");
        var is_active_event = false;

        for( i=0; i<running_event_cats.length; i++)
        {
            if( cat_id==running_event_cats[i])
            {
                is_active_event = true;
                break;
            }    
        }    
        
        if( is_active_event){
            $('tdsAgbDivContainer').show();
            $('isBillableOrContestableLiContainer').hide();
            $('isBillableCheckbox').checked=false;
            $('isContestableCheckbox').checked=false;
        }else if(cat_id==single_id){
            if( $('tdsAgbDivContainer') != null)
                $('tdsAgbDivContainer').hide();

            toggle_meta_data();
        }else{
            if( $('tdsAgbDivContainer') != null)
                $('tdsAgbDivContainer').hide();

            $('isBillableOrContestableLiContainer').show();
            toggle_meta_data();
        }
    }
}

/*
 * Zeigt/Verbirgt das Meta Data Panel
 * id: Die id bei der das Panel angezeigt werden soll.
 */
function toggle_meta_data()
{
    //category Id of singles
    var single_id=$("single_category_id").getValue();
    if(jQuery("#manuscript_category_id")!=undefined){
        var cat_id = jQuery("#manuscript_category_id").val();
        if( cat_id==single_id ){
            jQuery('#panel8-main').show();
            jQuery('#panel9-main').show();
            jQuery('#panel5-main').hide();
            jQuery('#isBillableOrContestableLiContainer').hide();
            jQuery('#price_container').show();
            jQuery('#form_step3_panel2_label_expose_li_container').hide();
            jQuery('#form_step3_panel2_label_figures_li_container').hide();
            jQuery('#form_step3_panel4_label_upload_li_container').hide();
            jQuery('#payment_cost_li_container').hide();
        }else{
            jQuery('#panel8-main').hide();
            jQuery('#panel9-main').hide();
            jQuery('#panel5-main').show();
            jQuery('#isBillableOrContestableLiContainer').show();
            jQuery('#form_step3_panel2_label_expose_li_container').show();
            jQuery('#form_step3_panel2_label_figures_li_container').show();
            jQuery('#form_step3_panel4_label_upload_li_container').show();
            jQuery('#payment_cost_li_container').hide();
            
            var value = jQuery("#isBillableCheckbox").is(":checked");
            if( value==true ){
                jQuery('#price_container').show();
            }else{
                jQuery('#price_container').hide();
            }
        }
        toggle_price_list_change();
    }
}



/*
 * Fügt den Preis '79 cent' mit in die Liste der möglichen Preise ein
 * wenn die Single Kategorie ausgewählt ist.
 * id: Die Category id bei der der Preis eingefügt wird
 */
function toggle_price_list_change()
{
    var single_id=$("single_category_id").getValue();
    if($("manuscript_category_id")!=undefined){
        var cat_id = $("manuscript_category_id").getValue();
        if( cat_id==single_id){
            var listBox = $('manuscript_price_cent')
            var options = listBox.getElementsByTagName('option');
            options = $A(options);
            var opt = options.find( function(employee){
                return (employee.value == "79");
            });
            if(opt==null){
                var opt = document.createElement('option');
                opt.text = "79";
                opt.value = "79";
                $('manuscript_price_cent').options.add(opt,2);
            }
        }else{
            var listBox = $('manuscript_price_cent')
            var options = listBox.getElementsByTagName('option');
            options = $A(options);
            var opt = options.find( function(employee){
                return (employee.value == "79");
            });
            if(typeof(opt) !== 'undefined'){
                opt.remove();
            }
            
        }   
    }
}
//toggle_price_list_change

/*
 * Diese Funktion ist invers zur Funktion 
 * replace_input_field_by_plaintext_and_edit_button(...). Sie wird automatisch
 * bei Kick auf das erzeugte Div gerufen.
 */
function replace_plaintext_by_input_field( input_field_id, plain_field_id)
{
    $( plain_field_id).hide();
    $( input_field_id).show();
}

/*
 * Diese Methode ersetzt das Eingabefeld fuer die Kontonummer im Bereich 
 * "Persoenliche Daten" eines Nutzers gegen ein DIV. In diesem DIV steht
 * die selbe Kontonummer, jedoch werden die ersten n Zeichen durch *
 * ersetzt. Auf diese Weise wird dem User etwas Sicherheit vorgegaukelt.
 * Die Funktion replace_plaintext_by_input_field(...) kehrt diesen Vorgang um.
 */
function replace_input_field_by_plaintext_and_edit_button( input_field_id, plain_field_id, how_many_characters_to_anonymize)
{
    if($(input_field_id)!=undefined){
        $( input_field_id).hide();
        //return true;
        var content = $( input_field_id).getValue();
        var replacement = "*";
    
        if( how_many_characters_to_anonymize)
        {
            var target = '';
            for( i=0; i<how_many_characters_to_anonymize; i++)
                target = target + replacement;
        
            content = target + content.substr(i);
        }
        if( $(plain_field_id)==undefined)
        {
            var contentIntroductionElement = new Element('div', {
                'id' : 'bank_account_invisible',
                'class' : 'editable_input_field_replacement',
                'onclick' : 'replace_plaintext_by_input_field( "'+input_field_id+'", "'+plain_field_id+'")'
            }).update( content);

            var contentElement = $('sfApplySettings_bank_account_number');
            Element.insert(contentElement, {
                'after': contentIntroductionElement
            });
        }else
            $( plain_field_id).show();
    }
    
}

function warn_country(){
    if($F('sfApplySettings_country')!="DE"){
        $('country_notification').show();
    }else{
        $('country_notification').hide();
    }
        
}
function warn_country_apply(){
    if($F('sfApplyApply_country')!="DE"){
        $('country_notification').show();
    }else{
        $('country_notification').hide();
    }
        
}

// function to save a text to nb_text (module textHelper)
function ajax_save_nb_text( event)
{
    // Formular-Absenden verhindern
    event.preventDefault();

    // Inhalt vom tinyMCE in das Textarea synchronisieren
    if( tinyMCE.get('nb_text_editfield')!=undefined)
        jQuery('#nb_text_editfield').val( tinyMCE.get('nb_text_editfield').getContent());

    // Formdaten auslesen
    var neuertext = jQuery('#nb_text_editfield').attr("value");
    var text_id = jQuery('#nb_text_id').attr("value");
    
    var clear_cache = '';
    if( jQuery('#nb_text_clear_caches').length >0)
        clear_cache = jQuery('#nb_text_clear_caches').attr("value");
        
    var data = {'nb_edittext':neuertext,'nb_text_id':text_id, 'nb_text_clear_caches':clear_cache};
    var url = 'http://'+window.location['host']+'/textHelper/ajaxSaveText';

    // Form per Ajax senden
    jQuery.ajax({
        type: 'POST',
        url: url,
        data: data,
        success: function( response){
            if( response!=0)
            {
                jQuery('#nb_text_editfield_container').toggle( 300);
                jQuery('#nb_text').html( response);
                jQuery('#nb_text').before("<div class='nb_texteditor_successmessage'>Der Text wurde gespeichert.</div>");
            }else{
                alert("FEHLER: Der Text konnte NICHT gespeichert werden.");
            }
        }
    });
}
                            
function init() {
    
    
    
    if ($('loading')) {
        $('loading').hide();
    }
    if($('sfApplySettings_country')){
        $('sfApplySettings_country').observe('change',warn_country);
        warn_country();
    }
    if($('sfApplyApply_country')){
        $('sfApplyApply_country').observe('change',warn_country_apply);
    }
    
    
    
    
    // Form to edit my Bank Account => replace Account-Number-Input-Field by non-editable-Text-Div
    replace_input_field_by_plaintext_and_edit_button( 'sfApplySettings_bank_account_number', 'bank_account_invisible', 5);

    // Target _blank
    externalLinks();
    //Social-bookmarks
    if ($('socialbookmarks')) {
        socialize($('socialbookmarks').down('ul'));
    }
    //Twitter feed generation
    if ($('twitter_update_list')) {
        var b = new Element('script', {
            type: 'text/javascript',
            src: 'http://twitter.com/statuses/user_timeline/neobooks_com.json?callback=twitterCallback'
        });
        document.body.appendChild(b);
    }
    // Rating Stars
    if ($$('.rating-option')) {
        $$('.rating-option').each(function(ratingBox) {
            new Rating(ratingBox);
        });
    }
    // Countdown
    if ($('clock')) {
        var container  = $('clock');
        var expireDate = container.down('.end_date').innerHTML;
        new PeriodicalExecuter(function(pEx) {
            new Countdown(container, expireDate, pEx, {
                leadingZero: true
            });
        }, 1);
    }
    // Tabify
    if ($('reviewTabs')) {
        new TabView($('reviewTabs'), 'tabHeader', 'tabBody');
    }
    //Toggle Felder
    init_input_toggle();
    // Login Form
    if ($('login')) {
        $('login').hide();
        $('login-btn').observe('click', changeLoginForm);
    }
    // Status Box
    if ($('status-edit')) {
        var link = $('status-edit');
        var originalText = link.innerHTML;
        link.observe('click', function(e) {
            toggleStatusBox(e, originalText, 'Schließen');
        });
        $('status-form').hide();
    }
    // Rezension schreiben
    if ($('rezension-edit')) {
        var trigger = $('rezension-edit');
        var tgtEl   = $('rezension-form');
        trigger.observe('click', toggleCommentForms.bindAsEventListener(trigger, tgtEl));
        tgtEl.hide();
    }
    // Kommentare schreiben
    if ($$('.review-comment').length) {
        $$('.review-comment').each(function(cForm) {
            new CommentForm(cForm, 'kommentar-edit', 'kommentar-form', 'kommentar-close');
        });
    }
    // Scroll To
    if ($('agbScrollTo')) {
        myScrollTo($('agbContainer'), $('agbScrollTo'));
    }

    // TODO: Check if it is easyly replaceable by jquery
    if ($$('.acc-radio').length >= 1) {
        $$('.acc-radio').each(function(acc) {
            new Accordeon(acc, 'acc-header', 'acc-body', {
                type: 'radio',
                open: false,
                stayOpen: false
            });
        });
    }
    // Shadowboxen
    if ($$('.report').length > 0) {
        $$('.report').each(function(link) {
            link.observe('click', function(e) {
                var repURL = this.href;
                Event.stop(e);
                Shadowbox.open({
                    //content:    "<div class='warning'><p>Möchten Sie uns diese Rezension als unangemessen, anstößig oder rechtswidrig melden?</p><input type='button' value='Ja' onclick='window.location.href=\""+repURL+"\";'><input type='button' value='Abbrechen' onclick='Shadowbox.close();'></div>",
                    content:    "<div class='warning'><input type='text' name='foo' /><p>Möchten Sie uns diese Rezension als unangemessen, anstößig oder rechtswidrig melden?</p><button value='Ja' onclick='window.location.href=\""+repURL+"\";'><div><p>Ja</p></div></button><button value='Abbrechen' onclick='Shadowbox.close();'><div><p>Abbrechen</p></div></button></div>",
                    player:     "html",
                    title:      "Löschen?",
                    height:     125,
                    width:      300
                });
            });
        });
    }

    // MW
    if ($$('a[class*=shadow-open]').size() > 0) {
        $$('a[class*=shadow-open]').each(function(link) {
            var width = link.readAttribute('class').replace(/shadow-open-(\d+)-(\d+)(.*)/img,'$1');
            var height = link.readAttribute('class').replace(/shadow-open-(\d+)-(\d+)(.*)/img,'$2');

            link.observe('click', function(e) {
                var URL = this.href;
                Event.stop(e);
                Shadowbox.open({
                    content:    URL,
                    player:     "iframe",
                    width:      (width != 'shadow-open') ? width : 759,
                    height:     (height != 'shadow-open') ? height : 572,
                    handleOversize: 'none'
                });
            });
        });
    }

    //MW
    // Toggles the cover-editor-upload form
    if($$('.show_cover_upload').size() > 0) {
        $$('.show_cover_upload').each(function(button) {
            button.observe('click', function(e) {
                Event.stop(e);
                $('upload_cover').toggle();
            });
        });
    }
    
    // Toggle 
    if( jQuery('.switchCoverUploadMethod').size() > 0) {
        jQuery('.switchCoverUploadMethod').live('click', function(event) {
            event.preventDefault();
            jQuery('#upload_cover_01').toggle(600);
            jQuery('#upload_cover_02').toggle(600);
        });
    }

    // MW
    // Dynamic height override of the slider height by largest element height
    if($$('.slide-content').size() > 0) {
        $$('.slide-content').each(function(slider) {
            var overall_height = 193;
            slider.adjacent('li').each(function(item) {
                var dimensions = item.getDimensions();
                if (dimensions.height > overall_height) {
                    overall_height = dimensions.height;
                }
            });
            slider.up().setStyle({
                height: overall_height+'px'
            });
            slider.up(1).setStyle({
                height: overall_height+'px'
            });
        });
    }

    // MW
    // Dynamic height override of the slider height by largest element height
    if($$('.slide-content').size() > 0) {
        $$('.slide-content').each(function(slider) {
            var overall_height = 193;
            slider.adjacent('li').each(function(item) {
                var dimensions = item.getDimensions();
                if (dimensions.height > overall_height) {
                    overall_height = dimensions.height;
                }
            });
            slider.up().setStyle({
                height: overall_height+'px'
            });
            slider.up(1).setStyle({
                height: overall_height+'px'
            });
        });
    }

    if ($$('.announcement-twitter a').length > 0) {
        $$('.announcement-twitter a').each(function(link) {
            link.observe('click', function(e) {
                Event.stop(e);
                var url    = link.href;
                var api_id = link.readAttribute('api_id');

                new Ajax.Request(url,
                {
                    method:'get',
                    parameters: {
                        client_id: '153489644673782',
                        redirect_uri: window.location.href,
                        scope: 'publish_stream'
                    },
                    onSuccess: function(transport){
                        var response = transport.responseText || "no response text";
                    },
                    onFailure: function(){  }
                });

            });
        });
    }

    // MW
    // Chapter Movement with AJAX
    if ($$('.chapter-item').length > 0) {
        initChapterMovement();
    }

    // MW
    // Because member-list is an unordered list and its list elements could have variable height,
    // it isn't possible to fix layout iritations by css only.
    // So, we calculate the height of the highest item in a row and fix the height of its siblings.
    // Result: everything looks just fine :)
    if($$('.member-list-shadowbox').size() > 0) {
        $$('.member-list-shadowbox').each(function(list) {
            // Defailt height
            var list_dimensions = list.getDimensions();
            var list_item_dimensions = list.down('li').getDimensions();
            var items_per_row = Math.round(list_dimensions.width / list_item_dimensions.width)

            // Calculate height of the highest item as new default height per row
            var all_items = list.childElements();
            while (all_items.length = 0) {
                var highest = 0;

                // Get items for current row
                var current_row = all_items.splice(0, items_per_row);
                // Calculate height for current row
                current_row.each(function(item) {
                    var item_dimensions = item.getDimensions();
                    if (item_dimensions.height > highest) {
                        highest = item_dimensions.height;
                    }
                });
                // Set the new calculated height for this row
                current_row.each(function(item) {
                    item.setStyle({
                        height: highest-30+'px'
                    });
                });
            }

        });
    }


    if ($$('.not_logged_in').length > 0) {
        $$('.not_logged_in').each(function(link) {
            link.observe('click', function(e) {
                Event.stop(e);
                Shadowbox.open({
                    content:    "<div class='warning'><p>Bitte zuerst einloggen <a href=\"/user/login\">zum Login</a></p></div>",
                    player:     "html",
                    title:      "Login !",
                    height:     58,
                    width:      300
                });
            });
        });
    }

    if ($('sfApplyProfile_thumb_delete')) {
        $('sfApplyProfile_thumb_delete').observe('click', function() {
            Shadowbox.open({
                content:    "<div class='warning'><p>Wollen Sie Ihr Profilbild wirklich löschen?</p><input type='button' value='Ja' onclick='document.forms[\"sf_apply_profile_form\"].submit();' /><input type='button' value='Abbrechen' onclick='document.forms[\"sf_apply_profile_form\"].sfApplyProfile_thumb_delete.checked=false;Shadowbox.close();'></div>",
                player:     "html",
                title:      "Löschen?",
                height:     100,
                width:      300
            });
        });
    }
    if ($$('.delete_manuscript').length > 0) {
        $$('.delete_manuscript').each(function(link) {
            link.observe('click', function(e) {
                var delURL = this.href;
                Event.stop(e);
                Shadowbox.open({
                    content:    "<div class='warning'><p>Wollen Sie das Manuskript wirklich löschen?</p><input type='button' value='Ja' onclick='window.location.href=\""+delURL+"\";'><input type='button' value='Abbrechen' onclick='Shadowbox.close();'></div>",
                    player:     "html",
                    title:      "Löschen?",
                    height:     100,
                    width:      300
                });
            });
        });
    }
    if ($('showCoverEditor')) {
        var sb_link  = $('showCoverEditor');
        var sb_uri   = $('showCoverEditor').href;
        var ajax_ctn = $('cover');
        var manuscriptID = $F('manuscript_id');
        var ajax_uri = '/manuscript/ajaxShowCover?id='+manuscriptID;
        Shadowbox.setup(sb_link, {
            content: sb_uri,
            player: 'iframe',
            title: 'Cover-Editor',
            height: 620,
            width: 1020,
            onClose: function() {
                new Ajax.Updater(ajax_ctn, ajax_uri);
            }
        });
    }

    initManuscriptPreview();

    // Ajax Calls
    initChapterEditor();

    initCategoryLoader();

    // Category Loader Profile
    if ($('sfApplyProfile_favourite_category')) {
        var url_base     = '/sfApply/ajax_select?category_id=';
        var tgtContainer = $('genre_select');
        if (!Prototype.Browser.IE) {
            $('sfApplyProfile_favourite_category').observe('change', changeCategory.bindAsEventListener(this, url_base, tgtContainer));
        } else {
            $('sfApplyProfile_favourite_category').observe('click', changeCategory.bindAsEventListener(this, url_base, tgtContainer));
        }
    }

    // Slider
    if ( $$('.basic-slider').length > 0) {
        $$('.basic-slider').each(function(el) {
            new SlidingBox(el, {
                increments:2,
                duration:.8
            });
        });
    }
    if ($$('.basic-slider-small').length >= 1) {
        $$('.basic-slider-small').each(function(el) {
            new SlidingBox(el, {
                increments:2,
                duration:.8
            });
        });
    }

    // chararcter counter
    initCharacterCounter();

    // pseudonym autocompletion
    initPseudonymAutocompleter();

    // pseudonym watcher
    initPseudonymWatcher();
    initManuscriptTitleWatcher();

    tds_toggle_terms_of_use();
    
    toggle_genre_autoselect_rown_and_contract();
    
    
    reload_genre_select();

    // Funktion zum Ein-/Ausblenden der Textbearbeitung von DB-Texten
    jQuery('#nb_text_editfield_toggle').live('click', function( event){
        jQuery('#nb_text_editfield_container').toggle( 300);
        if( jQuery('.nb_texteditor_successmessage').length)
            jQuery('.nb_texteditor_successmessage').remove();
    });

    // Funktion zum Speichern eines geaenderten Textes
    jQuery('#nb_text_editfield_submit').live('click', function(event){
        ajax_save_nb_text( event);
    });
}

// Initialisierung nach Event DOMContentLoaded
document.observe("dom:loaded", init);

