/*
 * (c) 2011 David Krause, Interaktive Gestaltung
 * http://www.interaktive-gestaltung.de
 */

function ContentView(model, controller)
{
    var model = model;
    var controller = controller;

    var photoSeries; // controls the photoseries
    var slideshow; // controls the slideshow
    var thumbIndex; // controls the thumbnails on the index pages
    var photoUrls; // stores the urls while preloading the images
    var infoButton; // controls the info button

    var scrollPaneApi;

    this.loadingContentId = 0;
    this.loadedContentId = 0;

    this.init = function()
    {
        hideAllContent();
    }

    /**
     * Handles the content change event of the model.
     * Only prepares the change of the content, the actual
     * change is handled by the onContentLoaded function.
     *
     */
    this.onChangeContent = function()
    {
        emptyAllContent();
        hideAllContent();
        this.loadingContentId ++;
    }

    /**
     * Handles the contentLoaded event.
     * A render function is called, dependent on the state.
     *
     * @param {Object} obj The object of the event
     */
    this.onContentLoaded = function(obj)
    {
        this.loadedContentId ++;
        trace("ContentView onContentLoaded loadingContentId=" + this.loadingContentId + " loadedContentId=" + this.loadedContentId);

        /*
         Only display content if the ids of loading and loaded match,
         to prevent overlapping of content.
         */
        if (this.loadedContentId == this.loadingContentId)
        {
            trace("display new content");
            if (obj.state == model.SLIDESHOW)
                renderSlideshow(obj.content);

            else if (obj.state == model.PHOTOINDEX || obj.state == model.FILMINDEX)
                renderPhotoFilmIndex(obj.content);

            else if (obj.state == model.PHOTOSERIES)
                renderPhotoseries(obj.content);

            else if (obj.state == model.FILMDETAIL)
                renderFilmdetail(obj.content);

            else if (obj.state == model.NEWS)
                renderNews(obj.content);

            else if (obj.state == model.VITA || obj.state == model.CONTACT || obj.state == model.IMPRINT)
                renderText(obj.content);

            this.loadedContentId = 0;
            this.loadingContentId = 0;
        }

    }

    /**
    * Handles the infoTextChanged event.
    *
    * @param {Object} obj The object of the event
    */
    this.onInfoTextChanged = function(obj)
    {
        trace("onInfoTextChanged " + obj.id);
        if (obj.id != null)
            thumbIndex.showTarget(obj.id);
        else
            thumbIndex.hideTarget();
    }

    /**
     * Renders the index pages of sections from photo and film,
     * (i.e. one thumbnail of each series from the current section).
     *
     * @param {Object} content Contains the content to be rendered.
     */
    var renderPhotoFilmIndex = function(content)
    {
        /*
            Create the thumbnails
         */
        var index = $('#containerIndex');
        index.show();

        index.append(content.thumbnails);
        index.css({ opacity: 0 });
        index.fadeTo(250, 1, 'swing');

        /*
            Create the info texts
         */
        $('#containerInfo').show();
        var textsNum = content.texts.length;
        var texts = '';
        for (var i = 0; i < textsNum; i++)
        {
            texts += content.texts[i];
        }
        $('#containerInfo .infoText .content').append(texts);


        thumbIndex = new ThumbIndex(controller, '#containerIndex ul li a', '#containerInfo .infoText', '#containerInfo .infoText .content div.text');
        thumbIndex.init();
    }

    /**
     * Renders the detail of a film (i.e. the videoplayer)
     *
     * @param {Object} content Contains the content to be rendered.
     */
    var renderFilmdetail = function(content)
    {

        $('#containerFilm').show();
        $('#containerInfo').show();
        $('#containerInfo .infoButton').show();

        /*
         Create the video, depending on browser/platform
         */
        var video;
        var platform = navigator.platform;
        var isIOS = ( navigator.platform.indexOf("iPhone") != -1 || navigator.platform.indexOf("iPad") != -1);


        /*
        For iOs, embed the Quicktime-Movie with QT-Plugin
         */
        var video_width = 705;
        var video_height = 396;
        if($.browser.webkit && isIOS)
        {
            video = '<object width="' + video_width + '" height="' + video_height + '" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab"> <param name="src" value="'  + content.video_image + '" /> <param name="href" value="' + content.video_file + '" /> <param name="target" value="myself" /> <param name="controller" value="true" /> <param name="autoplay" value="true" /> </object>';
            $('#containerFilm').append(video);
        }
        /*
         For all other browsers/system, embed the Movie using flv player and swfobject
         */
        else
        {
            /*
                flowplayer embedding
             */

            $('#containerFilm').append("<div id='videoPlayer'></div>");

            flowplayer('videoPlayer', '/fileadmin/flowplayer/flowplayer.commercial-3.2.7.swf', {
                key: '#$00d29f6711892db53ea',
                clip: {
                    url: content.video_file,
                    autoPlay: true,
                    scaling: 'orig',
                    bufferLength: 5
                },

                plugins: {
                    controls: {
                        // location of the controlbar plugin
                        url: '/fileadmin/flowplayer/flowplayer.controls-3.2.5.swf',
                        // styling properties (will be applied to all plugins)
                        background: '#666666',
                        opacity: 0.6,
                        backgroundGradient: 'none'
                    }
                }
            });
        }

        /*
        Create the info text with info button
        */
        var text = content.text;
        $('#containerInfo .infoText .content').append(text);

        var infoButton = new InfoButton('#containerInfo .infoButton a', '#containerInfo .infoText', '#containerInfo .infoText .content div.text');
        infoButton.init(0);


    }


    /**
     * Renders text pages
     * e.g. vita
     *
     * @param {Object} content Contains the content to be rendered.
     */
    var renderText = function(content)
    {
        var allContainer = $('#containerText');
        allContainer.show();


        /*
         Append the content
         */
        var contentContainer = $('#containerText .content');

        var contentDe = cleanContent(content['textDe']);
        var contentEn = cleanContent(content['textEn']);
        var contentImage = cleanContent(content['image']);

        contentContainer.append("<div class='de'>" + contentDe + contentImage + '</div>');

        if (contentEn)
        {
            contentContainer.append("<div class='en'>" + contentEn + contentImage + '</div>');
            contentContainer.append("<div class='languageButton'><a href=''>info</a></div>");
            var languageButton = new LanguageButton('#containerText .content .languageButton a', new Array('#containerText .content .de','#containerText .content .en'), new Array('deutsch', 'english'));
            languageButton.init();
        }

        contentContainer.css({ opacity: 0 });
        contentContainer.css({ 'background-color': '#FFF' }); // for ie fade bug
        allContainer.css({ 'margin-top': '-1px' }); // for ie 1px bug
        contentContainer.fadeTo(250, 1, 'swing');
    }


    /**
     * Renders the news page
     * A scrollbar is displayed, if content is larger than the stage.
     *
     * @param {Object} content Contains the content to be rendered.
     */
    var renderNews = function(content)
    {
        var container = $('#containerText');
        container.show();

        /*
            Init the scrollbar
         */
        var scrollSettings = { showArrows: true, autoReinitialise: true, arrowRepeatFreq: 50, arrowScrollOnHover: false };
        var scrollPane = $('#containerText .content');
        scrollPane.jScrollPane(scrollSettings);
        scrollPaneApi = scrollPane.data('jsp');

        /*
            Append the content
         */
        scrollPaneApi.getContentPane().append(cleanContent(content.text));
        scrollPaneApi.reinitialise();

        scrollPaneApi.getContentPane().css({ opacity: 0 });
        scrollPaneApi.getContentPane().css({ 'background-color': '#FFF' }); // for ie fade bug
        container.css({ 'margin-top': '-1px' }); // for ie 1px bug
        scrollPaneApi.getContentPane().fadeTo(250, 1, 'swing');
        scrollPaneApi.getContentPane().css({ 'width': '693px' });

    }


    /**
     * Basic function for cleaning the content
     * before being rendered on the document.
     *
     * @param content
     */
    var cleanContent = function(content)
    {
        if (content)
        {
            var content = content.replace(/javascript/gi, '');
            var content = content.replace(/script/gi, '');
            return content;
        } else
        {
            return '';
        }
    }


    /**
     * Renders the slideshow
     *
     * @param {Object} content Contains the content to be rendered.
     */
    var renderSlideshow = function(content)
    {
        //$('#containerPhotos').show();

        /*
            Create the empty divs for the photos and the div for the photoNavi
         */
        content.photos.pop();  // remove the empty last element
        var photosNum = content.photos.length;
        var photoDivs = '';
        for (var i = 0; i < photosNum; i++)
        {
            photoDivs += "<div class='photo'></div>"
        }
        // photoNavi here only used for "protecting" the bg images
        photoDivs += "<div class='photoNavi'><img src='/fileadmin/images/n.gif' alt='' width='705' height='567' /></div>";
        $('#containerPhotos').append(photoDivs);

        /*
            init the slideshow and start the preloading of the photos
         */
        slideshow = new Slideshow('div.photo');
        slideshow.init(photosNum);

        photoUrls = content.photos;
        photoUrls.shuffle();

        preloadPhotoOfSlideshow();
    }

    /**
     * Preloads all photos of the slideshow.
     * After an image has been loaded, the function is called again,
     * until all images have been loaded.
     */
    var preloadPhotoOfSlideshow = function ()
    {
        var url = photoUrls.shift();
        var img = new Image();
        $(img).attr('src', url);

        $(img).load(function ()
        {
            if( $('#containerPhotos').is(':hidden') )
                $('#containerPhotos').show();

            if (slideshow)
            {
                slideshow.addImage(img);
                if (photoUrls.length > 0) preloadPhotoOfSlideshow();
            }

        });

        $(img).error(function ()
        {
            trace("ERROR preloadPhotoOfSlideshow " + img.src)
        });
    }

    /**
     * Renders a photoseries
     *
     * @param {Object} content Contains the content to be rendered.
     */
    var renderPhotoseries = function(content)
    {
        $('#containerPhotos').show();
        $('#containerInfo').show();
        $('#containerInfo .infoButton').show();
        $('#containerInfo .thumbnails').show();

        /*
             Display the thumbnails
         */
        $('#containerInfo .thumbnails').append(content.thumbnails);

        /*
            Create the empty divs for the photos and the div for the photoNavi
         */
        if (content.photos)
        {
            content.photos.pop(); // remove the empty last element
            var photosNum = content.photos.length;
            var photoDivs = '';
            for (var i = 0; i < photosNum; i++)
            {
                var mb = content.marginBottom[i];
                var style = (mb != 0) ? "style='top: -" + mb + "px;'" : ""; // push photo up, if marginBottom is defined
                photoDivs += "<div class='photo' " + style +  "></div>"
            }
            photoDivs += "<div class='photoNavi'><img src='/fileadmin/images/n.gif' alt='' width='705' height='567' /></div>";
            $('#containerPhotos').append(photoDivs);
        }

        /*
            Create the info texts
         */
        if (content.texts)
        {
            var textsNum = content.texts.length;
            var texts = '';
            for (var i = 0; i < textsNum; i++)
            {
                texts += content.texts[i];
            }
            $('#containerInfo .infoText .content').append(texts);
        }

        /*
            init the photoSeries and start the preloading of the photos
         */
        photoSeries = new PhotoSeries('div.photo', '.photoNavi', '#containerInfo .thumbnails li.thumb img');
        photoSeries.init(photosNum);

        photoUrls = content.photos;
        preloadPhotoOfSeries();
    }

    /**
     * Preloads all photos of the current series.
     * After an image has been loaded, the function is called again,
     * until all images have been loaded.
     */
    var preloadPhotoOfSeries = function ()
    {
        if (!photoUrls) return;
        var url = photoUrls.shift();
        var img = new Image();

        $(img).load(function ()
        {
            //trace("image.load=" + img.src);
            photoSeries.addImage(img);
            if (photoUrls.length > 0) preloadPhotoOfSeries();
        });

        $(img).error(function ()
        {
            trace("ERROR preloadPhoto " + img.src)
        });

        $(img).attr('src', url);
    }

    /**
     * Empties all content of the page.
     *
     */
    var emptyAllContent = function ()
    {
        $('#containerIndex').empty();
        $('#containerPhotos').empty();
        $('#containerFilm').empty();
        $('#containerInfo .thumbnails').empty();
        $('#containerInfo .infoText .content').empty();

        if (scrollPaneApi)
        {
            scrollPaneApi.getContentPane().empty();
            scrollPaneApi.destroy();
            scrollPaneApi = undefined;
        }

        $('#containerText .content').empty();

        if (photoSeries)
        {
            photoSeries.exit();
            photoSeries = undefined;
        }

        if (slideshow)
        {
            slideshow.exit();
            slideshow = undefined;
        }

        if (thumbIndex)
        {
            thumbIndex.exit();
            thumbIndex = undefined;
        }


    }

    /**
     * Hides all content of the page.
     */
    var hideAllContent = function ()
    {
        $('#containerIndex').hide();
        $('#containerPhotos').hide();
        $('#containerFilm').hide();
        $('#containerText').hide();
        $('#containerInfo').hide();
        $('#containerInfo .infoButton').hide();
        $('#containerInfo .thumbnails').hide();
        $('#containerInfo .infoText').hide();

    }

}

