// **************************************************************
// mediabox.js
//
// Author       : Richard van den Winkel
// E-mail       : richardvandenwinkel@gmail.com
//
// Dependencies : SWFObject.js v2.1 (http://code.google.com/p/swfobject/)
//                jMyCarousel.js (http://plugins.jquery.com/project/jMyCarousel)
//                metadata plugin (http://jquery-multifile-plugin.googlecode.com/svn-history/r16/trunk/jquery.MetaData.js)
//
// **************************************************************


// -------------------------------------------------------------------------
// N.B.: Werkt op dit moment maar met slechts 1 mediabox op de pagina
// Mede doordat VideoDock de sender niet meegeeft in zijn Raise Events
// -------------------------------------------------------------------------


// globale variabele die nodig is om in de EventHandler die de events van VideoDock afvangt
// de slideshow te kunnen starten/stoppen.
var mediabox;

;(function($) {

    $.fn.mediabox = function(options) {

        //        // jMyCarousel plugin check
        //        if (!$.jMyCarousel) {
        //            alert('jMyCarousel plugin missing: http://plugins.jquery.com/project/jMyCarousel');
        //            return;
        //        }

        //        // metadata plugin check
        //        if (!$.metadata) {
        //            alert('metadata plugin missing: http://jquery-multifile-plugin.googlecode.com/svn-history/r16/trunk/jquery.MetaData.js');
        //            return;
        //        }


        // plugin main options
        var o = $.extend({}, $.fn.mediabox.defaults, options);


        // iterate each matched element
        this.each(function() {

            // this => the mediabox container element
            var $this = $(this);

            // set global variable
            mediabox = $this;

            // Preview container (outer)
            var pc = $this.find('.' + o.previewContainer + ':first');

            // Actual preview container
            var apc = $(pc).find('.' + o.previewDiv + ':first');

            // Info container
            var ic = $(pc).find('.' + o.infoDiv + ':first');

            // Thumbnails container
            var tc = $this.find('.' + o.thumbnailContainer + ':first');

            // If pc or tc not found then don't continue
            if (pc.length <= 0 || tc.length <= 0)
                return 0;

            // The mediaitems to display
            var items = $(tc).find("li").length;


            // Variable for the current open item
            $this.curThis = "";
            $this.previewWidth = $(pc).width();
            $this.previewHeight = $(pc).height();
            $this.pc = pc;
            $this.apc = apc;
            $this.ic = ic;
            $this.items = items;
            $this.o = o;
            $this.playing = o.autoStartSlideShow;

            // Initialise display & thumbnail scrolling areas (requires jMyCarousel)
            // Als er meer dan 5 items zijn, dan jMyCarousel activeren.
            //            if (items > 5) {
            //                $(tc).jMyCarousel({
            //                    visible: '100%'
            //                });
            //            }
            //                        
            // als er maar 1 item is, dan thumbnailcontainer verbergen
            //            if (items == 1) {
            //                $(tc).hide();
            //            }


            // Als er geen items zijn, dan in z'n geheel hiden
            if (items < 1) {
                $this.hide();
                return;
            }

            // Info container
            if (o.showinfo == true) {
                // add hover handler to previewContainer for showing/hiding info
                $(pc).hover
                (
                    function() {
                        $(ic).slideDown();
                    },
                    function() {
                        $(ic).slideUp();
                    }
                );
            }

            //            // slideshow controls (play/pause)
            //            if (o.autoStartSlideShow == false) {
            //                $(ic).find('.controls a:first').addClass('is_pausing');
            //            }
            //            
            //            $(ic).find('.controls a:first').click(function() {
            //                if ($this.playing == false) {
            //                    StartSlideshow($this);
            //                    $this.playing = true;
            //                    $(this).removeClass('is_pausing');
            //                }
            //                else {
            //                    PauseSlideshow($this);
            //                    $this.playing = false;
            //                    $(this).addClass('is_pausing');
            //                }
            //            });

            // Vars tbv SlideShow
            $this.medialinks = $(tc).find('.' + o.mediaLink);
            $this.curMediaLinkItem = 0;

            // initialise containers
            $(pc).find('.' + o.positionTable + ':first').height($this.previewHeight);
            $(pc).find('.' + o.positionTable + ':first').width($this.previewWidth);
            $(ic).hide();

            // add click handler to all thumbnails
            $(tc).find('.' + o.mediaLink).click(function() {
                //  alert($(this).html());
                Thumbnail_Click(this, $this);
            });

            // show first item in previewContainer
            $(tc).find('.' + o.mediaLink + ':first').click();


            // --- FUNCTIONS -------------------------------------------------------
            // Functions to start/stop the slide show
            $this.StartSlideShow = function() {
                StartSlideshow($this);
            }
            $this.StopSlideShow = function() {
                StopSlideshow($this);
            }

        }); // end of main iteration


        // return this for chaining
        return this;


    }; // end of mediabox function

    $.fn.mediabox.defaults = {
        flash_version: '9.0.0',
        flash_express_installer: '/swf/expressInstall.swf',
        loading_indicator: '/images/loading-bar.gif',

        // ClassNames for the various elements
        // Preview frame
        previewContainer: 'previewContainer',
        previewDiv: 'preview',
        infoDiv: 'info-bar',
        positionTable: 'previewPositionTable',

        // Thumbnail frame
        thumbnailContainer: 'thumbnailContainer',
        mediaLink: 'mediaLink',

        // Show info on hover?
        showinfo: true,

        // Resize images?
        resizeImages: false,

        autoStartSlideShow: true
    };


    // --- PRIVATE METHODS / EVENTHANDLERS -----------------------------------------------
    function Thumbnail_Click(sender, $this) {
        // get element metadata 
        var o = $(sender).metadata();

        if ($(sender).attr('href') && $(sender).attr('href').length > 0) {
            $($this.pc).click(function() {
                window.open($(sender).attr('href'), '_self');

            });
            $($this.pc).css('cursor', 'pointer');
        }
        else {
            $($this.pc).unbind('click');
            $($this.pc).css('cursor', 'default');

        }
        //alert(  $($this.ic).html());
        // Set info en downloadlink
        $($this.ic).find('.info:first').html('');
        if (o.hires) {
            var downloadLink = "<div class=\"rght t10\"><a href=\"" + o.hires + "\" class=\"button\">download</a></div>";
            $($this.ic).find('.info:first').append(downloadLink);
        }

        if (o.info || o.title || o.copyright) {
            var str = '<div class="lft">';
            if (o.title)
                str += o.title + ' - ';
            if (o.info)
                str += o.info + ' - ';
            if (o.copyright)
                str += "&copy; " + o.copyright + '<br />';

            str += '</div>';
            $($this.ic).find('.info:first').append(str);
        }

        // show loading indicator
        $($this.apc).html('');
        var div = document.createElement("div");
        var d = new Date();
        var tmpId = "moviePlaceHolder_" + Date.UTC(d.getFullYear(), d.getMonth(), d.getDay(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds());
        div.setAttribute("id", tmpId);
        $(div).css("background-color", "#ffffff");
        $(div).css("width", "100%");
        $(div).css("height", "100%");
        var img = document.createElement("img");
        img.setAttribute("src", $this.o.loading_indicator);
        div.appendChild(img);
        $($this.apc).append(div);

        // Type bepalen
        switch (o.type) {
            case 'video':
                var flashvars = {};
                flashvars.allowscriptaccess = "always";
                flashvars.wmode = "transparent";
                flashvars.type = "swf";

                var attributes = {};
                attributes.id = "vcplayer";

                var params = {};
                params.wmode = "transparent";
                params.allowfullscreen = "true";
                params.allowscriptaccess = "always";

                var src = o.rel;
                if (src.indexOf('youtube', 0) > 0) {
                    attributes.id = "ytplayer";
                    src = "http://www.youtube.com/apiplayer?enablejsapi=1&playerapiid=ytplayer";
                }

                swfobject.embedSWF(src, tmpId, $this.previewWidth, $this.previewHeight, $this.o.flash_version, $this.o.flash_express_installer, flashvars, params, attributes);

                break;

            case 'image':
                var img = document.createElement("img");
                img.setAttribute("src", o.rel);

                // Resize image to available width/height
                // --------------------------------------------
                var displayratio = $this.previewWidth / $this.previewHeight;
                //alert('displayratio: ' + displayratio + '; aspectratio: ' + aspectratio);
                if (o.aspectratio && $this.o.resizeImages == true) {
                    if (displayratio <= o.aspectratio) {
                        img.setAttribute("width", $this.previewWidth);
                        img.setAttribute("height", 1 / o.aspectratio * $this.previewWidth);
                    } else {
                        img.setAttribute("width", o.aspectratio * $this.previewHeight);
                        img.setAttribute("height", $this.previewHeight);
                    }
                } else {
                    img.setAttribute("width", $this.previewWidth);
                    img.setAttribute("height", $this.previewHeight);
                }


                $($this.apc).html('');
                $($this.apc).append(img);
                break;

            case 'audio':
            case 'document':
            default:
                $($this.apc).html('');
                break;
        } // end switch(type)

        // --- SlideShow starten --- 
        StartSlideshow($this);



    } // end Thumbail_Click

    /**
    * De slideshow werkt als volgt:
    * Elke n aantal seconden wordt een click op een thumbnail getriggered. 
    * Er wordt een index bijgehouden van de huidige thumbnail.
    * De volgende klik vind plaats op de volgende thumbnail in de lijst.
    **/
    function StartSlideshow($this) {
        if ($this.timeOut)
            clearTimeout($this.timeOut);

        $this.timeOut = setTimeout(function() {

            // volgende te tonen item bepalen
            if ($this.curMediaLinkItem == $this.medialinks.length - 1) {
                $this.curMediaLinkItem = 0;
            } else {
                $this.curMediaLinkItem++;
            }
            // click uitvoeren om te tonen
            $($this.medialinks[$this.curMediaLinkItem]).click();
        }
        , 8000);
    }

    function StopSlideshow($this) {
        if ($this.timeOut)
            clearTimeout($this.timeOut);
    }


})(jQuery);


// Initialize the mediabox on the page when ready
jQuery(function($) {
    $("#mediaBox").mediabox();
});


// --- Video Culture Player EventHandlers & Funtions ---
function onVCCall(msg) {
    if (mediabox) {
        switch (msg) {
            case 'StartPlayer':
                mediabox.StopSlideShow();
                break;
            case 'EndOfPlayer':
                mediabox.StartSlideShow();
                break;
        }
    }
}



// --- YouTube Player EventHandlers & Functions ---
var yt_curVideo_id = '';
var yt_curVideo_startSeconds = '';

function onYouTubePlayerReady(id) {

    //alert('onYouTubePlayerReady(' + id + ')');
    
    ytplayer = $('#' + id)[0];
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");

    if (mediabox) {
        // get current element
        var cur = $(mediabox.medialinks[mediabox.curMediaLinkItem]);
        
        // get element metadata
        var o = $(cur).metadata();

        // cue video
        if (o.rel.indexOf("youtube", 0) > 0 && o.fkid) {
            //alert('o.fkid: ' + o.fkid + '');
            cueNewVideo(o.fkid, 0);
            yt_curVideo_id = o.fkid;
            yt_curVideo_startSeconds = 0;
        }
    }

}
function loadNewVideo(id, startSeconds) {
    if (ytplayer) {
        //alert('> ' + yt_curVideo_id + ' - ' + yt_curVideo_startSeconds);
        ytplayer.loadVideoById(yt_curVideo_id, parseInt(yt_curVideo_startSeconds));
    }
}
function cueNewVideo(id, startSeconds) {
    if (ytplayer) {
        ytplayer.cueVideoById(id, startSeconds);
    }
}
function onytplayerStateChange(newState) {
    // state = 3: play
    if (newState == 3) {
        mediabox.StopSlideShow();
        loadNewVideo();
    }
    // state = 0: endOfVideo
    if (newState == 0) {
        mediabox.StartSlideShow();
    }    
}
