window.addEvent('domready', function(){
    if( document.location.href.indexOf('admin') != -1 ) {
        return;
    }
    var galleries = $$('div.gallery');
    galleries.each(function(g) {
        try {
            new gallery(g, { preloader: true });
        } catch(e) {
        }
    });
    if( document.location.href.indexOf('/site/') != -1 || document.location.href.indexOf('admin') != -1  || document.location.href.indexOf('newsletter') != -1){
        return;
    }
    var documentScroller = new Fx.Scroll(document);
    var postWrappers = $$('.post_wrapper');
    var commentsSliders = [];
    var addClosedClass = false;
    if( document.location.href.indexOf('archive') != -1 ) {
        addClosedClass = true;
    }
    var buildSlider = function(postWrapper){
        var blogPost = postWrapper.getElement('.blogPost');
        if( addClosedClass ) {
            postWrapper.addClass('closed');
        }
        var slider = new Fx.Slide(blogPost, { duration: 'short' });
        slider.hide();
        postWrapper.store('slider', slider);
        //postWrapper.addClass('closed');
        var innerWrapper = postWrapper.getElement('.post_inner_wrapper');
        innerWrapper.setStyle( 'background-color', document.body.getStyle('background-color') );
        var lightBgColor = new Color(
            document.body.getStyle('background-color')
        ).mix(new Color('#fff'), 50);
        var highlightDuration = 400;
        innerWrapper.set('tween', { duration: highlightDuration });
        postWrapper.addEvent('mouseenter', function(e){
            innerWrapper.highlight(lightBgColor.hex);
        });
        var defaultPostHeight = postWrapper.getStyle('height');
        var commentsSlider = new Fx.Slide(postWrapper.getElement('div.comments'));
        var gallery = postWrapper.getElement('div.jdGallery');
        if( gallery ) {
            gallery.setStyle('display', 'none');
        }
        postWrapper.addEvent('click', function(e){
            if(e) {
                e = new Event(e);
                if( slider.open && e.target.tagName != 'H1' ) {
                    return;
                }
            }
            if( gallery ) {
                if( gallery.getStyle('display') == 'none' ) {
                    gallery.setStyle('display', '');
                }
                else {
                    gallery.setStyle('display', 'none');
                }
            }
            if( commentsSlider.open && slider.open ) { commentsSlider.slideOut(); }
            if( !slider.open ) {
                commentsSliders.each(function(cSlider){
                    if( cSlider !== commentsSlider ) {
                        cSlider.slideOut();
                    }
                });
                slider.slideIn().chain(function(){
                    toggleCommentsSlider(e);
                    documentScroller.toElement(postWrapper)
                });
            }
            else {
                slider.slideOut();
            }
            if( addClosedClass ) {
                postWrapper.toggleClass('closed');
            }
            //postWrapper.toggleClass('closed');
            postWrappers.each(function(otherPostWrapper){
                if( otherPostWrapper === postWrapper ) {
                    return;
                }
                if( addClosedClass ) {
                    otherPostWrapper.addClass('closed');
                }
                var otherGallery = otherPostWrapper.getElement('div.jdGallery');
                if( otherGallery ) {
                    otherGallery.setStyle('display', 'none');
                }
                otherPostWrapper.retrieve('slider').slideOut();
                //otherPostWrapper.addClass('closed');
            });
        });
        commentsSliders.push(commentsSlider);
        commentsSlider.hide();
        var openCommentsButton = postWrapper.getElement('p.comments');
        var createCommentButton = postWrapper.getElement('p.doComment');
        var commentEditorIsBuilt = false;
        var toggleCommentsSlider = function(e){
            //new Event(e).stop();
            if(!slider.open) {
                if( gallery ) {
                    if( gallery.getStyle('display') == 'none' ) {
                        gallery.setStyle('display', '');
                    }
                    else {
                        gallery.setStyle('display', 'none');
                    }
                }
            }
            commentsSliders.each(function(cSlider){
                if( cSlider !== commentsSlider ) {
                    cSlider.slideOut();
                }
            });
            if( !commentsSlider.open && !slider.open ) {
                slider.slideIn();
            }
            postWrappers.each(function(otherPostWrapper){
                if( otherPostWrapper === postWrapper ) {
                    return;
                }
                otherPostWrapper.retrieve('slider').slideOut();
                var otherGallery = otherPostWrapper.getElement('div.jdGallery');
                if(otherGallery) {
                    otherGallery.setStyle('display', 'none');
                }
                //otherPostWrapper.addClass('closed');
            });
            return commentsSlider.toggle();
        };
        if( createCommentButton ) {
            createCommentButton.addEvent('click', function(e){
                if( commentEditorIsBuilt ) {
                    var fx = commentsSlider.toggle();
                    if( !commentsSlider.open ) {
                        fx.chain(function(){ documentScroller.toElement(postWrapper.getElement('div.comments').getLast('.commentWrapper')) });
                    }
                    return;
                }
                commentEditorIsBuilt = true;
                var commentEditor = new Element('div', { 'class':'commentWrapper' });
                var commentInner = new Element('div', { 'class':'comment' }).inject(commentEditor);
                var authorClass = innerWrapper.get('class').replace(/^.*(author\d+).*$/, "$1");
                commentInner.addClass(authorClass);
                var submitButton = new Element('button', { text: 'Veröffentlichen' }).inject(commentInner);
                var authorLabel = new Element('p', {
                    text: 'Kommentar von: ',
                    'class': 'caption author'
                });
                var authorInput = new Element('input');
                if( window.bloghausUsername ) {
                    authorLabel.grab(new Element('strong', { text: window.bloghausUsername }));
                }
                else {
                    authorLabel.grab(authorInput);
                }
                authorLabel.inject(commentInner);
                var textarea = new Element('textarea').inject(commentInner);
                textarea.focus();
                submitButton.addEvent('click', function(){
                    var postId = postWrapper.id.replace(/[^\d]/g, '');
                    var commentRequest = new Request.JSON({
                        url: window.bloghausBaseUrl + 'comment/' + postId,
                        onSuccess: function(comment) {
                            textarea.dispose();
                            if(!window.bloghausUsername) {
                                authorLabel.dispose();
                                Element('p', {
                                    text: 'Kommentar von: ',
                                    'class': 'caption author'
                                }).grab(new Element('strong', { text: comment.author })).inject(commentInner);
                            }
                            new Element('p', { text: comment.text }).inject(commentInner);
                            submitButton.dispose();
                            commentsSlider.hide().show();
                            commentEditorIsBuilt = false;
                            commentInner.set('tween', { duration: highlightDuration });
                            commentInner.highlight(lightBgColor.hex);
                            var commentsCountNode = postWrapper.getElement('p.comments').getFirst('strong');
                            commentsCountNode.set({
                                text: parseInt(commentsCountNode.get('text'), 10)+1
                            });
                            documentScroller.toElement(commentInner);
                        }
                    });
                    var dataToSend = {
                        text: textarea.value
                    };
                    if(!window.bloghausUsername) {
                        dataToSend.poster_name = authorInput.getProperty('value');
                    }
                    commentRequest.post(dataToSend);
                });
                commentEditor.inject(commentsSlider.element);
                if( commentsSlider.open ) {
                    commentsSlider.hide().show();
                }
                else {
                    commentsSlider.show().hide();
                    toggleCommentsSlider(e).chain(function(){ documentScroller.toElement(textarea) });
                }
                textarea.focus();
            });
        }
        /*if( openCommentsButton ) {
            openCommentsButton.addEvent('click', function(e){
                toggleCommentsSlider(e).chain(function(){ documentScroller.toElement(postWrapper.getElement('div.comments').getLast('.commentWrapper')) });
            });
        }*/
        var editPostButton = postWrapper.getElement('p.doEdit');
        if( editPostButton ) {
            editPostButton.addEvent('click', function(){
                var p = postWrapper.getElement('p.postText');
                var text = new Element('textarea', { value: p.get('text') }).replaces(p);
                var submit = new Element('button', {text: 'Veröffentlichen'}).injectAfter(text);
                if( slider.open ) { slider.hide().show(); }
                submit.addEvent('click', function(){
                    submit.dispose();
                    p.set('html', text.get('value').replace(/(\r?\n)/g, '<br />')).replaces(text);
                    slider.hide().show();
                });
            });
        }
    };
    postWrappers.each(buildSlider);
    if( postWrappers.length === 1 ) {
        postWrappers[0].fireEvent('click');
    }
    var defaultPostHeight = postWrappers[0].getStyle('height');
    var editPanelIsBuilt = false;
    var ViewTypeIcon = function(typeName){
        return new Element('div', { 'class': 'post_category' }).grab( new Element('div', { 'class': typeName }) );
    };
    var buildEditPanel = function(){
        var editPanel = new Element('div');
        var publicInterface = {};
        var editPanelOuter = new Element('div', {'class': 'editPanelWrapper'}).inject(editPanel);
        var editPanelInner = new Element('div', {'class': 'editPanel author' + window.bloghausUserId}).inject(editPanelOuter);
        var submitButton = new Element('button', { text: 'Veröffentlichen' }).inject(editPanelInner);
        new Element('strong', {text: window.bloghausUsername}).inject(new Element('p', {
            'class': 'caption',
            text: 'Beitrag von: '
        }).inject(editPanelInner));
        var titleInput = new Element('input').inject(editPanelInner);
        var separator = new Element('div', {'class':'hr'}).inject(editPanelInner);
        var textarea = new Element('textarea').inject(editPanelInner);
        var viewTypeIcons = [];
        ['text', 'image', 'video', 'sound'].each(function(viewType){
            var icon = ViewTypeIcon(viewType).inject(editPanelInner);
            viewTypeIcons.push(icon);
            icon.addEvent('click', function(){
                viewTypeIcons.each(function(viewTypeIcon){
                    viewTypeIcon.getFirst().removeClass('selected');
                });
                icon.getFirst().addClass('selected');
                publicInterface.viewType = viewType;
            });
        });
        viewTypeIcons[0].getFirst().addClass('selected');
        publicInterface.viewType = 'text';
        new Element('div', { styles: { clear: 'left' } }).inject( editPanelInner );
        return $extend(publicInterface, {
            panel: editPanel,
            title: titleInput,
            innerWrapper: editPanelInner,
            outerWrapper: editPanelOuter,
            textarea: textarea,
            separator: separator,
            submit: submitButton
        });
    };
    var buildBlogPost = function(postTitle, postText, postViewType) {
        var postWrapper = new Element('div', { 'class': 'post_wrapper' });
        var postOuterWrapper = new Element('div', { 'class': 'post_outer_wrapper' }).inject(postWrapper);
        var postCategory = ViewTypeIcon(postViewType).inject(postWrapper);
        new Element('div', { styles: { clear: 'right' } }).inject(postWrapper);
        new Element('div', { 'class': 'comments' }).inject(postWrapper);
        var postInnerWrapper = new Element('div', { 'class': 'post_inner_wrapper author' + window.bloghausUserId }).inject(postOuterWrapper);
        var postHead = new Element('div', { 'class': 'post_head'}).inject(postInnerWrapper);
        var PostHeadEntry = function(label, value, className) {
            var p = new Element('p', { text: label + ': ' });
            if( className ) {
                p.addClass(className);
            }
            return p.grab( new Element('strong', { text: value }) );
        };
        PostHeadEntry('Beitrag von', window.bloghausUsername).inject(postHead);
        PostHeadEntry('Kategorie', '').inject(postHead);
        PostHeadEntry('Kommentare', '0', 'comments').inject(postHead);
        new Element('h1', { text: postTitle }).inject(postHead);
        new Element('p', {'class': 'postText', text: postText}).inject(new Element('div', { 'class': 'blogPost' }).inject(postInnerWrapper));
        return postWrapper;
    };
    var createPostButton = $('create_post');
    var editPanelFx;
    if( createPostButton ) {
        createPostButton.addEvent('click', function(e){
            e = new Event(e).stop().preventDefault();
            if( editPanelIsBuilt ) {
                var editPanel = editPanelFx.element.getParent('.editPanelWrapper');
                if(!editPanelFx.open) {
                    editPanel.setStyle('display', '');
                }
                editPanelFx.toggle().chain(function(){
                    if(!editPanelFx.open) {
                        editPanel.setStyle('display', 'none');
                    }
                });
                return;
            }
            editPanelIsBuilt = true;
            var editor = buildEditPanel();
            editor.submit.addEvent('click', function(e){
                new Event(e).preventDefault().stop();
                editor.panel.setStyle('overflow', 'hidden');
                editor.panel.tween('height', defaultPostHeight);
                editor.submit.tween('opacity', '0');
                editor.textarea.tween('opacity', '0');
                editor.separator.tween('opacity', '0');
                var fx = editor.title.get('tween');
                fx.start(
                    'background-color', editor.innerWrapper.getStyle('background-color')
                ).chain( function(){
                    editPanelIsBuilt = false;
                    var newPost = buildBlogPost( editor.title.get('value'), editor.textarea.get('value'), editor.viewType );
                    //newPost.injectTop($('content').getFirst('.postList'));
                    newPost.injectAfter(editor.panel);
                    editor.panel.dispose();
                    editor = null;
                    postWrappers = $$('.post_wrapper');
                    buildSlider(newPost);
                    newPost.fireEvent('mouseenter');
                });
            });
            editor.panel.injectTop($('contentInner').getFirst('.postList'));
            editPanelFx = new Fx.Slide(editor.panel.getElement('.editPanel')).hide();
            editPanelFx.slideIn();
        });
    }
    var forwardBackward = $$('.forward_backward')[0];
    if(forwardBackward) {
        var myHeight = forwardBackward.getSize().y;
        var height = $('content').getSize().y + 200 - myHeight;
        if(Browser.Engine.trident){
            height -= myHeight * 1.5;
        }
        var naviHeight = $('navi').getSize().y + 200 + myHeight;
        forwardBackward.setStyle('top', height <= naviHeight ? naviHeight : height );
    }
});
/*window.addEvent('domready', function(){
    $$('.blogPost p a').each(function(link){
        if( !link.get('target') && link.get('href').indexOf('http://') == 0 ) {
            link.set('target', '_blank');
        }
    });
    var categoryListItems = $$('#categories ul.category li');
    var fxDuration = 0;
    categoryListItems.each(function(el){
        el.set('tween', { property: 'background-color', duration: fxDuration });
        var link = el.getFirst('a');
        link.set('tween', { property: 'color', duration: fxDuration });
        var originalLinkColor = link.getStyle('color');
        var hr = el.getParent();
        hr.set('tween', { property: 'background-color', duration: fxDuration });
        el.addEvents({
            mouseover: function(e) {
                setTimeout(function(){ el.get('tween').start('#000000'); }, 0);
                setTimeout(function(){ hr.get('tween').start('#000000'); }, 0);
                setTimeout(function(){ link.get('tween').start('#FFFFFF'); }, 0);
            },
            mouseout: function(e) {
                setTimeout(function(){ el.get('tween').start('#FFFFFF'); }, 0);
                setTimeout(function(){ hr.get('tween').start('#CCCCCC'); }, 0);
                setTimeout(function(){ link.get('tween').start(originalLinkColor); }, 0);
            },
            click: function(e) {
                document.location.href = link.href;
            }
        });
        //$('logo_top').addEvent('mouseover', function(){ borderFx.start('#CCCCCC'); });
        //$('content').addEvent('mouseover', function(){ borderFx.start('#CCCCCC'); });
    });
});*/

/*function addEventsToCommentDeleteLinks(urlPrefix) {
    $$('a.delete').each(function(deleteLink){
        var comment_id = deleteLink.id.replace(/delete_/, '');
        deleteLink.addEvent('click', function(deleteLinkClickEvent){
            var event = new Event(deleteLinkClickEvent);
            var commenterName = $E('h1', event.target.parentNode).getText();
            //event.stop();
            event.preventDefault();
            var modalContainer = new Element('div');
            new Element('h1').setText("Löschen eines Kommentares").inject(modalContainer);
            new Element('p').setText('Wollen Sie den Kommentar von «' + commenterName + '» wirklich löschen?').inject(modalContainer);
            new Element('a', {href: urlPrefix + '/' + comment_id}).setText('Ja ').inject(modalContainer);
            var cancelLink = new Element('a', {href: '#'}).setText('| Nein');
            cancelLink.addEvent('click', function(cancelEvent){
                new Event(cancelEvent).preventDefault(); Lightbox.close()
            });
            cancelLink.inject(modalContainer);
            Lightbox.show(modalContainer, 'Löschen eines Kommentares', '500 400');
        });
    });
}*/

function initPlayer( playerContainer ) {
	var swfFile = this.swfFile;
	var videoPreview = playerContainer.getElement('img');
	
        var playerContainerSize, playerContainerCoordinates;
        if(null === videoPreview) {
            playerContainerSize = {size: { x: '100', y: '100' } };
            playerContainerCoordinates = { 'top': 0, 'left': 0 };
        }
        else {
            playerContainerSize = { size: videoPreview.getSize() };
            playerContainerCoordinates = videoPreview.getCoordinates();
        }
	
	playerContainer.setStyle('cursor', 'pointer');
		playerContainer.removeEvents('click');
		var playerHeight;
		var playerWidth;
		var playerDisplayHeight;
		if (null !== videoPreview) {
			//playerHeight 		= videoPreview.height + 20;
			//playerDisplayHeight = videoPreview.height;
			//playerWidth 		= videoPreview.width;
                        playerDisplayHeight = 378;
                        playerHeight = 398;
                        playerWidth = 680;
                        videoPreview.dispose();
		}
		else {
			/*playerHeight        = 220;
			playerDisplayHeight = 200;
			playerWidth         = 400;*/
                        /*playerDisplayHeight = 388;
                        playerHeight = 418;*/
                        playerDisplayHeight = 0;
                        playerHeight = 30;
                        playerWidth = 680;
		}
                var flashVars = {
                    width: playerWidth,
                    height: playerHeight,
                    displayheight: playerDisplayHeight,
                    file: playerContainer.attributes.rel.value,
                    bufferlength: 2,
                    stretching: 'fill',
                    autostart: document.location.href.indexOf('about/dercast') > -1
                };
                if( videoPreview ) {
                    flashVars.image = videoPreview.getProperty('src');
                }
                var player = new Swiff(swfFile, {
                    id: 'mediaplayer',
                    width: playerWidth,
                    height: playerHeight,
                    params: {
                        wmode: 'transparent',
                        allowfullscreen: true
                    },
                    vars: flashVars
                }).inject(playerContainer);
}

