/**
 * ALL JAVASCRIPT NEEDS TO BE IN SEPARATE NAMESPACES
 * didz namespace
 */

var hvvg = {
    COMMENT_READ: "#viewlet-below-content .discussion",
    COMMENT_WRITE: "#viewlet-below-content #commenting",
    HELP_TXT: "#hvvg-help-viewlet dd",

    init: function(){
        if (jq('#portal-personaltools-wrapper #personaltools-logout').length == 1) {
            var link = jq('#portaltab-verhalen-aanmelden').find('a');
            link.text('Verhaal aanmelden')
            link.attr('href', '/hvvg/verhalen/verhaal-aanmelden');
        }

        if (jq("body.portaltype-verhaal").length == 1) {
            // if a comment is added don't hide the comments
            var splitted = document.location.href.split('#');
            if (splitted.length != 2 && jq("#" + splitted[1]).length != 1 ) {
                jq(hvvg.COMMENT_READ).hide();
            }

            jq(hvvg.COMMENT_WRITE).hide();

            hvvg.addCommentControls();
        }
        else if (jq("#verhaal-search-view").length == 1) {
            hvvg.searchImagePreview();
            hvvg.searchAjaxify();
        }

        hvvg.toggleHelp();
        hvvg.fancybox();
        hvvg.carousel();
        hvvg.highlights();
        hvvg.linkableBlock();
        hvvg.disableRightMouseButton();

        hvvg_maps.init();
        if (window.hvvg_member != undefined) {
            hvvg_member.init();
        }
        hvvg_pagination.init();
    },
    /**
     * Small html snippet with which a portal status message is generated given a
     *  brief message.
     */
    portalMessage: function(message) {

        // get rid of existing messages
        jq(".portalMessage").remove();

        // ... and create a new one
        jq("#content").prepend(' \
            <dl class="jq-rating-message portalMessage info"> \
                <dt>Info</dt> \
                <dd>' + message + '</dd> \
            </dl>'
        );
        jq("dl.portalMessage").show();
    },
    
    /**
     * Toggle help part that is shown in topbar.
     */
    toggleHelp: function() {

        jq("#hvvg-help-viewlet dt a,#hvvg-help-viewlet dd").click(function(e) {
            e.preventDefault();

            jq(this).removeClass("display-" + jq(hvvg.HELP_TXT).css('display'));
            var help = jq(hvvg.HELP_TXT);
            help.slideToggle();
            jq(this).addClass("display-" + jq(hvvg.HELP_TXT).css('display'));
        });
    },

    /**
     * Hide comments + form, elements can be toggled thru a hyperlink
     */
    addCommentControls: function() {
        var controls = "<a id='verhaal-write-comment' class='comment-controls hvvg-arrow display-none' href='#'>Schrijf een reactie</a>"

        if (jq(hvvg.COMMENT_READ).length == 1) {
             var controlsRead = "<a id='verhaal-read-comments' class='comment-controls hvvg-arrow display-none' href='#'>Lees alle reacties</a>"
             controls = controlsRead + controls
            jq(controls).insertBefore(jq(hvvg.COMMENT_READ));
        } else {
            jq(controls).insertBefore(jq(hvvg.COMMENT_WRITE));
        }

        jq("#verhaal-read-comments").click(function(e) {
            e.preventDefault();
            jq(this).removeClass("display-" + jq(hvvg.COMMENT_READ).css('display'));
            jq(hvvg.COMMENT_READ).toggle();
            jq(this).addClass("display-" + jq(hvvg.COMMENT_READ).css('display'));
        });
        jq("#verhaal-write-comment").click(function(e) {
            e.preventDefault();
            jq(this).removeClass("display-" + jq(hvvg.COMMENT_WRITE).css('display'));
            jq(hvvg.COMMENT_WRITE).toggle();
            jq(this).addClass("display-" + jq(hvvg.COMMENT_WRITE).css('display'));
        });
    },

    /**
     * Modal window is shown when a anchor (with thumbnail) has a specific rel attr.
     */
    fancybox: function() {

        //preview images
        jq("a[rel=hvvg-slideshow]").fancybox({
                'type': 'image',
                'transitionIn'		: 'none',
                'transitionOut'		: 'none',
                'titlePosition' 	: 'over',
                'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
                    var description = false;
                    var splitted = title.split('|');

                    title = splitted[0];

                    if (splitted.length > 1) { description = splitted[1] }

                    var html = '<span id="fancybox-title-over">';
                    html += title;
                    if (description) {
                        html+='<br/><br/>Credits: ' + description;
                    }
                    html += '</span>'

                    return html;
                }
        });

        // preview verhalen
        jq(".hvvg-highlight-widget a, .content-type-Verhaal a").not('.playlist-item').each(function() {
            var link = jq(this).attr("href");
            link = link + "/preview"
            jq(this).attr("href", link);
        }).fancybox({
            autoDimensions: false,
            width: 700,
            height: 400,
            onStart: function() {
                jq("body").addClass("fancybox-verhaalpreview");
	        },
            onClosed: function() {
                jq("body").removeClass("fancybox-verhaalpreview");
	        }
        });

        //preview video
        jq(".content-type-Video a").each(function() {
            var link = jq(this).attr("href");
            link = link + "/preview"
            jq(this).attr("href", link);
        }).fancybox({

	    swf: {
                wmode		: 'transparent',
                allowfullscreen	: 'true'
            }
        });
    },

    /**
     * Image carousel, shown below verhaal and in a portlet
     */
    carousel: function(start) {

        if (!start) {
            start = 1;
        }

        jq("ul.jcarousel-skin-hvvg").jcarousel({
            'start': start,
            'scroll': 3,
            'itemLoadCallback': hvvg.carousel_trigger
        });

        /* Filter options: filter Verhalen/Foto's/Video's */
        var prefix='content-type-'; // see also hvvg.css and verwanteportlets.pt
        jq('.verwant-type-filter li[class^="' + prefix + '"]').each(function() {
            jq(this).css({cursor:'pointer'});
            var selected_type_name = jq(this).attr('class').split(" ")[0].replace(prefix,"");
            jq(this).click(function() {
                if ( jq(this).is('.selected') ) {
                    jq(this).removeClass('selected');
                    jq('.hvvg-carousel .jcarousel-skin-hvvg li[class^="' + prefix + '"]').show();
                } else {
                    jq('.hvvg-carousel .jcarousel-skin-hvvg li[class^="' + prefix + '"]').each(function() {
                        var element_type_name = jq(this).attr('class').split(" ")[0].replace(prefix,"");
                        if ( selected_type_name != element_type_name) {
                            jq(this).hide();
                        } else { jq(this).show() };
                    });
                    jq(this).addClass('selected');
                };
                jq(this).siblings().removeClass('selected');
            });
        });

        if (jq.cookie('playlist-toggle') == 'on') {
            hvvg_playlist._showPlaylist();
        }
    },

    /**
     * Store playlist carousel position
     *
     * @param carousel - jq carousel object
     * @param state
     */
    carousel_trigger: function(carousel, state) {
        if (jq(carousel.container).parents('#playlist-control')) {
            jq.cookie('playlist-position', carousel.first);
        }
    },

    /**
     * Image pop-up when there's a mouseover on a thumbnail. Used in search results.
     */
    searchImagePreview: function() {
        /* KC: imgPreview library is customized! */
        if ( jq('.hvvg-search-item a.image-link.preview').length > 0 ) {
            jq('.hvvg-search-item a.image-link.preview').imgPreview({
                containerID: 'imgPreviewWithStyles',
                srcAttr: 'rel',
                onShow: function(link){
                    jq(jq(link).find(".tooltip").html()).appendTo(this);
                },
                // When container hides:
                onHide: function(link){
                    jq('div', this).remove();
                }
            });
        }
    },

    /**
     * Automagically do a underwater submit of the form when a input element is
     * changed. Update only the search results in the page.
     */
    searchAjaxify: function() {
        // submit form with ajax
        jq('#verhaal-search-view form').submit(function(e) {
            e.preventDefault();
            hvvg.ajaxSubmit(jq(this));  
        });
        // submit form when a checkbox is changed
        jq("#verhaal-search-view input[type='checkbox']").change(function(){
            var form = jq(this).parents('form').first();
            form.submit()
        });
    },
    ajaxSubmit: function(form) {
        jq('#hvvg-search-results').fadeTo('normal', 0.3);
        jq('body').css('cursor', 'progress');
        jq('#imgPreviewWithStyles').remove();

        jq.ajax({
            url: form.attr('action') + '/results_view',
            type: 'POST',
            asynchronous: true,
            data: form.serialize(),
            complete: function(request) {

                jq('#hvvg-search-results').fadeTo('normal', 1);
                jq('body').css('cursor', 'default');
                jq('input.searchButton').removeClass('submitting');

                if (request.status == 200) {
                    jq('#hvvg-search-results').replaceWith(request.responseText);
                    jq('#hvvg-search-results .listingBar a').each(function() {
                       var link = jq(this).attr('href');
                       link = link.replace('results_view', '');
                       jq(this).attr('href', link);
                    });
                    hvvg.searchImagePreview();

                } else {
                    hvvg.portalMessage('Fout bij het ophalen van de zoekresultaten. Herlaad deze pagina en probeer het opnieuw.');
                    jq('.portalMessage').addClass('error');
                }
            },
            onFailure: function(request){

                jq('#kss-spinner').hide();
                jq('#hvvg-search-results').fadeTo('normal', 1);
                jq('body').css('cursor', 'default');
                jq('input.searchButton').removeClass('submitting');

                hvvg.portalMessage('Fout bij het ophalen van de zoekresultaten. Herlaad deze pagina en probeer het opnieuw.');
                jq('.portalMessage').addClass('error');
            }
        });
    },

    /**
     * Verhalen highlights, slideshow on top, tabs with verhalen below.
     * The slideshow removes image that are too small.
     */
    highlights: function() {
        // make sure window load is done, so all images are loaded
        jq(window).load(function(){
            // center images in parent tile and start slideshow
            jq("#hvvg-highlights .verhaal-album img").each(function(){
                var parent_height = jq(this).parent().height();
                var parent_width = jq(this).parent().width();

                // hack to get dimension of hidden elements
                var css = {'position':'absolute','visibility':'hidden', 'display':'block'};
                jq(this).parent().css(css);
                jq(this).parent().parent().css(css);
                var image_height = jq(this).height();
                var image_width = jq(this).width();
                jq(this).parent().removeAttr('style');
                jq(this).parent().parent().removeAttr('style');

                if (image_height >= parent_height && image_width >= parent_width) {
                    //calculate how far from top the image should be
                    var top_margin = (parent_height - image_height)/2;
                    //and change the margin-top css attribute of the image
                    $(this).css('margin-top' , top_margin+"px");
                } else {
                    jq(this).parent().remove();
                }
            });

            if (jq(".verhaal-album.selected").length > 0) {
                jq(".verhaal-album.selected").cycle({shuffle:1});
            }

            // cycle only works on two or more images
            // manually show single image
            jq(".verhaal-album").each(function(){
                if (jq(this).find(".verhaal-tile").length == 1) 
                    jq(this).find(".verhaal-tile").css("display", "block");
            });
        });
        jq("#hvvg-highlights ul.tabs").tabs("div.panes > div");


        // show corresponding slideshow
        jq("#hvvg-highlights ul.tabs li a").click(function(){
            var current = jq(this).attr("href").replace("#tabs", "#album");

            jq(".verhaal-album.selected").cycle("destroy")
            jq(".verhaal-album").removeClass("selected")
            jq(current).addClass("selected").cycle({shuffle:1});
        });
    },

    linkableBlock: function() {
        jq("#hvvg-highlights .hvvg-verhaal").css("cursor", "pointer")
        jq("#hvvg-highlights .hvvg-verhaal").click(function(){
            var url = jq(this).find("a").attr("href");

            if (jq(this).parent('#tabs-afspeellijsten').length > 0) {
                hvvg_playlist.clicked(url);
            } else {
                window.location = url;
            }
        });
    },

    disableRightMouseButton: function() {
        //this one line will disable the right mouse click menu
        jq("img").bind("contextmenu",function(e){
            alert("Deze afbeelding is auteursrechtelijk beschermd en mag niet zonder toestemming van de auteur worden gebruikt.");
            return false;
        });

    }
}

jq(document).ready(function() {

    hvvg.init();

});

