(function($) {

    // configuration
    window.Blikvoer = {
        //rootPath: '../dotnet/src/source/Vara_Jongerenportal_230100883.Website/',
        rootPath: '/',
        topicVideoWidth: 480,
        topicVideoHeight: 270,
        topicVideoID: 'topic_mediaplayer',
        commentVideoWidth: 320,
        commentVideoHeight: 240,
        flashVersion: '9.0.28',
        installerPath: 'static/swf/expressInstall.swf',
        flashVars: {
            stream: '',
            autoplay: 'true',
            replyID: '',
            urlName: '1'
        },
        params: {
            menu: 'true',
            base: 'static/swf',
            wmode: 'transparent',
            bgcolor: '#000000',
            allowFullScreen: 'true',
            allowScriptAccess: 'sameDomain'
        },
        attributes: {
            id: ''
        },
        commentPingCounterURL: '/ReactieBekeken.aspx'
    }

    // on load...
    $(function() {
        window.isIE6 = /msie 6/i.test(navigator.userAgent) ? true : false;
        $('body').addClass('js_active');
        Blikvoer.CountBlocks.init();
        Blikvoer.Hoverable.init();
        Blikvoer.EnhanceTopic.init();
        Blikvoer.EnhanceComments.init();
        //Blikvoer.TransformTitles.init();
        //Blikvoer.SIFR.init();
        Blikvoer.LabeledValues.init();
        Blikvoer.ExternalLinks.init();
        Blikvoer.MovingCommentCall.init();
        window.setTimeout(function() { Blikvoer.equalizeBoxes.init(); }, 200);
        if (window.isIE6) Blikvoer.FixModals.init();
    });

    Blikvoer.updateNode = function(node) {
        //Blikvoer.CountBlocks.init(node);
        Blikvoer.Hoverable.init(node);
        Blikvoer.EnhanceComments.init(node);
        Blikvoer.CountBlocks.init();
        Cufon.refresh();
    }

    // text transformation in .count blocks
    Blikvoer.CountBlocks = {
        init: function(root) {
            if (!root) root = $(document);
            var numberClassNames = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
            $('.count .value', root).each(function() {
                var number = $(this).text();
                number = number.replace(/(^\s+|\s+$)/g, ''); // remove whitespace
                var container = jQuery('<span class="replaced"></span>');
                var fraction = false;
                for (var i = 0; i < number.length; i++) {
                    var digit = number.charAt(i);
                    if (digit == '.' || digit == ',') {
                        fraction = true;
                        container.append('<span class="dot"></span>');
                        continue;
                    } else if (digit == '%') {
                        container.append('<span class="percent"></span>');
                        continue;
                    } else if (digit == '+') {
                        container.append('<span class="plus"></span>');
                        continue;
                    }
                    else container.append('<span class="' + numberClassNames[digit] + '"></span>');
                }
                $(this).parent().append(container);
            });
        }
    }

    // sequences of items, hoverable and clickable
    Blikvoer.Hoverable = {
        init: function(root) {
            if (!root) root = $(document);
            $('.hoverable', root).hover(
				function() { $(this).addClass('hover'); },
				function() { $(this).removeClass('hover'); }
			);
            $('.clickable', root).each(function() {
                $(this).click(
					function(e) {
					    var target = e.target;
					    if (target.tagName != "A") {
					        document.location = $('a', $(this)).eq(0).attr('href');
					        e.preventDefault();
					    }
					}
				);
                $(this).attr('title', $('a:first-child', $(this)).attr('title'));
            });
        }
    }

    // transformed titles (splitting into lines, init sifr)
    Blikvoer.TransformTitles = {
        init: function() {
            $('.transform').each(function() {
                var heading = $(this).clone();
                var originalText = $(this).text();
                var textBuffer = originalText;
                var parent = $(this).parent();
                parent.css({ overflow: 'hidden' });
                heading.html('');
                parent.append(heading);
                // repeat until text buffer is empty
                while (textBuffer.length > 0) {
                    // create a new line
                    var line = jQuery('<span class="line"></span>');
                    heading.append(line.text(textBuffer)).append(' ');
                    // in case width of a line is longer than parent, keep subtracting words
                    var p = parseInt(parent.css("paddingLeft")) + parseInt(parent.css("paddingRight"));
                    var parentWidth = parent.get(0).offsetWidth - p;
                    while (line.get(0).offsetWidth > parentWidth) {
                        line.text(line.text().substring(0, line.text().lastIndexOf(' ')));
                    }
                    // subtracted string is also subtracted from text buffer
                    textBuffer = textBuffer.substring(line.text().length + 1, textBuffer.length);
                }
                // add SIFR and remove original heading
                $('span.line', heading).wrapInner('<span class="sifr"></span>');
                $(this).remove();
                $('body').addClass('has_transformed');
            });
        }
    }

    // enhance topic blocks
    Blikvoer.EnhanceTopic = {
        init: function(root) {
            if (!root) root = $(document);
            $('#topic', root).each(function() {
                // toggle collapse on button
                $('.button', $(this)).click(function(e) {
                    var topic = $(this).parents('#topic');
                    if (topic.hasClass('collapsed')) {
                        topic.removeClass('collapsed');
                        $('.button span', topic).html('Vertel me meer');
                    } else {
                        topic.addClass('collapsed');
                        $('.button span', topic).html('Ik weet genoeg');
                    }
                    // tickle DOM, for some browser
                    $("body").toggleClass("tickled");
                    e.preventDefault();
                });
            });
            /* insert video */
            $('#' + Blikvoer.topicVideoID, root).each(function() {
                var url = $('a', $(this)).attr('href');
                var params = getURLParams(url);
                var pathToPlayer = url.split('?')[0];
                Blikvoer.flashVars.stream = params.stream;
                Blikvoer.flashVars.replyID = params.replyID;
                Blikvoer.flashVars.urlName = params.urlName;
                Blikvoer.attributes.id = 'topicvideo';
                swfobject.embedSWF(pathToPlayer, Blikvoer.topicVideoID, Blikvoer.topicVideoWidth, Blikvoer.topicVideoHeight, Blikvoer.flashVersion, Blikvoer.installerPath, Blikvoer.flashVars, Blikvoer.params, Blikvoer.attributes);
            });
        }
    }

    // enhance comments
    Blikvoer.EnhanceComments = {
        init: function(root) {
            if (!root) root = $(document);
            this.mediaContainer = jQuery('<div id="commentvideo"></div>');
            $('#comments .comment', root).each(function() {
                if ($(this).hasClass('isvideo')) Blikvoer.EnhanceComments.enhanceVideo($(this));
                if ($(this).hasClass('isaudio')) Blikvoer.EnhanceComments.enhanceAudio($(this));
                if ($(this).hasClass('istext')) Blikvoer.EnhanceComments.enhanceTextOnly($(this));
            });
        },
        enhanceVideo: function(comment) {
            // toggle collapse on video comments
            var toggleLink = jQuery('<a href="#" class="more">Bekijk video</a>');
            var showVideo = function(e) {
                Blikvoer.EnhanceComments.toggleCollapse($(this).parents('.comment'));
                e.preventDefault();
            }
            toggleLink.bind('click', showVideo);
            $('.comment_video a', comment).bind('click', showVideo);
            $('.comment_text', comment).append(toggleLink);
        },
        enhanceAudio: function(comment) {
            // toggle collapse on video comments
            var toggleLink = jQuery('<a href="#" class="more">Beluister audio</a>');
            var showVideo = function(e) {
                Blikvoer.EnhanceComments.toggleCollapse($(this).parents('.comment'));
                e.preventDefault();
            }
            toggleLink.bind('click', showVideo);
            $('.comment_video a', comment).bind('click', showVideo);
            $('.comment_text', comment).append(toggleLink);
        },
        enhanceTextOnly: function(comment) {
            // toggle collapse on text-only comments with more than one paragraph of text
            if ($('.comment_text p', comment).length > 1) {
                var toggleLink = jQuery('<a href="#" class="more">Lees meer</a>');
                var showText = function(e) {
                    Blikvoer.EnhanceComments.toggleCollapse($(this).parents('.comment'));
                    e.preventDefault();
                }
                toggleLink.bind('click', showText);
                $('.comment_text', comment).append(toggleLink);
            }
        },
        toggleCollapse: function(comment) {
            Blikvoer.EnhanceComments.resetAllComments();
            comment.toggleClass('collapsed');
            // collapse video
            if (comment.hasClass('isvideo')) {
                var url = $('.comment_video a', comment).attr('href');
                var params = getURLParams(url);
                var pathToPlayer = url.split('?')[0];
                Blikvoer.flashVars.stream = params.stream;
                Blikvoer.flashVars.replyID = params.replyID;
                Blikvoer.flashVars.urlName = params.urlName;
                Blikvoer.attributes.id = 'commentvideo';
                $('.comment_video a, .comment_text', comment).hide();
                $('.comment_video', comment).append(Blikvoer.EnhanceComments.mediaContainer);
                window.Blikvoer.movieControl.stopAll();
                swfobject.embedSWF(pathToPlayer, 'commentvideo', Blikvoer.commentVideoWidth, Blikvoer.commentVideoHeight, Blikvoer.flashVersion, Blikvoer.installerPath, Blikvoer.flashVars, Blikvoer.params, Blikvoer.attributes);
            }
            else if (comment.hasClass('isaudio')) {
                var url = $('.comment_video a', comment).attr('href');
                var params = getURLParams(url);
                var pathToPlayer = url.split('?')[0];
                Blikvoer.flashVars.stream = params.stream;
                Blikvoer.flashVars.replyID = params.replyID;
                Blikvoer.flashVars.urlName = params.urlName;
                Blikvoer.attributes.id = 'commentvideo';
                $('.comment_video a, .comment_text', comment).hide();
                $('.comment_video', comment).append(Blikvoer.EnhanceComments.mediaContainer);
                window.Blikvoer.movieControl.stopAll();
                swfobject.embedSWF(pathToPlayer, 'commentvideo', Blikvoer.commentVideoWidth, Blikvoer.commentVideoHeight, Blikvoer.flashVersion, Blikvoer.installerPath, Blikvoer.flashVars, Blikvoer.params, Blikvoer.attributes);
            }
            else if (comment.hasClass('istext')) {
                var commentID = $('>a', comment).attr('name') || comment.attr('id');
                Blikvoer.EnhanceComments.pingCounter(commentID);
                comment.toggleClass('collapsed_istext');
            }
            // tickle DOM, for some browser
            $("body").toggleClass("tickled");
        },
        resetAllComments: function(root) {
            if (!root) root = $(document);
            $('#commentvideo').remove();
            $('#comments .comment', root).each(function() {
                $(this).removeClass('collapsed').removeClass('collapsed_istext');
                $('.comment_video a, .comment_text', $(this)).show();
            });
            // tickle DOM, for some browser
            $("body").toggleClass("tickled");
        },
        pingCounter: function(commentID) {
            var args = {
                replyID: commentID
            };
            var url = Blikvoer.commentPingCounterURL;
            return $.post(url, args, false, 'xml');
        }
    }

    // equalize boxes in a collection of elements
    Blikvoer.equalizeBoxes = {
        init: function(root) {
            var self = this;
            if (!root) root = $(document);
            $(".equalize", root).each(function() {
                Blikvoer.equalizeBoxes.setHeight($(".equal", $(this)));
            });
        },
        setHeight: function(obj) {
            var h = 0;
            obj.each(function() { h = Math.max(h, $(this).get(0).offsetHeight); });
            obj.each(function() {
                var p = parseInt($(this).css("paddingTop")) + parseInt($(this).css("paddingBottom"));
                $(this).css({ minHeight: (h - p) + "px" });
                // compensate for stubborn IE6
                if (window.isIE6) $(this).css({ height: (h - p) + "px" });
            });
            // tickle DOM, for some browser
            $("body").toggleClass("tickled");
        }
    };

    // sifr
    Blikvoer.SIFR = {
        type: {
            regular: Blikvoer.rootPath + 'static/swf/headlineone.swf',
            small: Blikvoer.rootPath + 'static/swf/futuraltcondensedbold.swf'
        },
        write: function() {
            if (typeof sIFR == 'function') {
                for (var i = 0, l = arguments.length; i < l; i++) {
                    Blikvoer.SIFR.rule(arguments[i]);
                }
            }
        },
        rule: function(conf) {
            sIFR.replaceElement(named({
                sSelector: conf.selector,
                sFlashSrc: conf.font || Blikvoer.SIFR.type.regular,
                sColor: conf.color || '#d8220a',
                sLinkColor: conf.link || null,
                sHoverColor: conf.hover || null,
                sWmode: "transparent",
                nPaddingBottom: conf.nPaddingBottom || -1
            }));
        },
        init: function(rootSelector) {
            rootSelector = rootSelector || '';
            Blikvoer.SIFR.write(
				{
				    selector: rootSelector + ' ol.agenda_list h2 .sifr',
				    color: '#d8220a'
				},
				{
				    selector: rootSelector + ' #comment_call .pity .sifr',
				    color: '#d0ddd6'
				},
				{
				    selector: rootSelector + ' #comment_call .sifr',
				    color: '#84a594'
				},
				{
				    selector: rootSelector + ' span.line .sifr',
				    color: '#ffffff',
				    nPaddingBottom: -8
				},
				{
				    selector: rootSelector + ' .layout_b h1 .sifr',
				    color: '#ffffff'
				},
				{
				    selector: rootSelector + ' .page_block_section_alt h2 .sifr',
				    color: '#ffffff'
				},
				{
				    selector: rootSelector + ' .page_block_section h2 .sifr',
				    color: '#84a594'
				},
				{
				    selector: rootSelector + ' #highlights h2 .sifr',
				    color: '#ffffff'
				},
				{
				    selector: rootSelector + ' .section h2 .sifr',
				    color: '#ffffff'
				},
				{
				    selector: rootSelector + ' h4 .sifr',
				    color: '#84a594'
				},
				{
				    selector: rootSelector + ' #other_responses .sifr',
				    color: '#84a594'
				},
				{
				    selector: rootSelector + ' .sifr'
				}
			);
        }
    };

    // preset labels in form text fields
    Blikvoer.LabeledValues = {
        init: function(root) {
            if (!root) root = $(document);
            var self = this;
            var fields = $('input.labeled_value, textarea.labeled_value', root);
            fields.each(function() {
                Blikvoer.LabeledValues.setLabel($(this))
            });
            fields.bind('focus', function() { self.resetLabel($(this)) });
            fields.bind('blur', function() { self.setLabel($(this)) });
        },
        setLabel: function(element) {
            var title = element.attr('title');
            if (element.val() == '' || !element.attr('className').match('labeled')) {
                element.addClass('labeled');
                element.val(title);
            }
        },
        resetLabel: function(element) {
            var title = element.attr('title');
            if (element.val() == title || element.attr('className').match('labeled')) {
                element.removeClass('labeled');
                element.val('');
            }
        }
    }

    // external links
    Blikvoer.ExternalLinks = {
        init: function(root) {
            if (!root) root = $(document);
            $('a[rel="external"]', root).each(function() {
                $(this).click(function(e) {
                    if (!(e.shiftKey || e.altKey || e.ctrlKey || e.metaKey)) {
                        var win = window.open($(this).attr('href'), 'Nieuw%20venster');
                        e.preventDefault();
                    }
                });
            });
        }
    }

    // fix layer for IE6
    Blikvoer.FixModals = {
        init: function() {
            if (!window.isIE6) return;
            this.modals = $('.modal');
            $(window).scroll(function() { window.Blikvoer.FixModals.update(); });
            $(window).resize(function() { window.Blikvoer.FixModals.update(); });
            window.Blikvoer.FixModals.update();
        },
        update: function() {
            window.Blikvoer.FixModals.modals.each(function() {
                var scrollY = document.documentElement.scrollTop;
                var vpHeight = document.documentElement.clientHeight;
                $(this).css({ top: scrollY + 'px', height: vpHeight + 'px' });
            });
        },
        lock: function() {
            $('html, body').css('overflow', 'hidden');
        },
        unlock: function() {
            $('html, body').css('overflow', 'auto');
        }
    }

    // external video control
    Blikvoer.movieControl = {
        getVideo: function(id) {
            if (navigator.appName.indexOf("Microsoft") != -1) {
                return window[id];
            } else {
                return document[id];
            }
        },
        stop: function(id) {
            var video = Blikvoer.movieControl.getVideo(id);
            if (video && video.stopVideo) video.stopVideo();
        },
        stopAll: function() {
            Blikvoer.movieControl.stop('application');
            Blikvoer.movieControl.stop('commentvideo');
        }
    }

    // scrolling comment button (topic page)
    Blikvoer.MovingCommentCall = {
        init: function() {
            this.timer;
            this.state = 'passive';
            this.movingButton = $('#comments #comment_call');
            if (this.movingButton.get(0)) {
                $(window).scroll(function() {
                    Blikvoer.MovingCommentCall.scrolling();
                });
                Blikvoer.MovingCommentCall.scrolling();
            }
        },
        scrolling: function() {
            // stop animating while scrolling
            if (this.state == 'animating') {
                this.movingButton.stop();
                this.state = 'passive';
            }
            // start animating when scrolling stopped
            window.clearTimeout(this.timer);
            this.timer = window.setTimeout(function() { Blikvoer.MovingCommentCall.animate() }, 200);
        },
        animate: function() {
            var viewportHeight = window.innerHeight || document.documentElement.clientHeight;
            var scrolledTop = document.documentElement.scrollTop;
            var scrolledBottom = scrolledTop + viewportHeight;
            var comments = document.getElementById('comments');
            var commentsTop = comments.offsetTop;
            var buttonHeight = this.movingButton.get(0).offsetHeight;
            var buttonVerticalMargin = 60;
            var buttonTop = this.movingButton.get(0).offsetTop + commentsTop;
            var buttonBottom = buttonTop + buttonHeight;
            var minimum = 0;
            var maximum = comments.offsetHeight - buttonHeight - buttonVerticalMargin;
            // set the target location 
            var targetTop;
            if (scrolledTop > buttonTop)
                targetTop = scrolledTop - commentsTop;
            else if (scrolledBottom < buttonBottom)
                targetTop = (scrolledBottom - buttonHeight - 2 * buttonVerticalMargin) - commentsTop;
            else return;
            // constrain within available space
            if (targetTop < minimum) targetTop = minimum;
            if (targetTop > maximum) targetTop = maximum;
            // start animating, change state afterwards
            this.movingButton.animate({ top: targetTop }, 500, 'swing', function() {
                Blikvoer.MovingCommentCall.state = 'passive';
            });
            this.state = 'animating';
        }
    }


})(jQuery);

getURLParams = function(url) {
	var params = {};
	url.replace(/([^&?=]+=[^&\$]+)+/mig, function($){
	   var pair = $.split('=');
	   params[pair[0]] = pair[1];
	});
	return params;
}



