/**
 * Class to generate a dialog window from an <ul><li>...</li>...</ul> List with slider
 * @returns {ScDialogSlider}
 */
var ScDialogSlider = {
    /**
     * Varaibles to hold the current gallery
     */
    _gallery: [],
    _root: [],
    _thumbnails: [],
    _options: null,
    // set default options
    _defaultOptions: {
        galleryImageHeight:         332,
        galleryImageWidth:          624,
        width:                      695,
        height:                     565,
        modal:                      true,
        prev:                       '&nbsp;',
        next:                       '&nbsp;',
        maxThumbnails:              5,
        thumbnailClass:             'thumbnailImage',
        galleryImageClass:          'galleryImage',
        title:                      '%object% %num% von %count%',
        translationImage:           'Bild',
        translationVideo:           'Video',
        dialogTitle:                '',
        resizable:                  false,
        videoDummyImage:            '/fileadmin/meinl_sites2011/images/abb-dummy_artist-video.jpg',
        faderTime:                  750
    },
    _names: [],
    _types: [],
    _currentName: 'default',
    _enableAnimation: true,
    _intermissionConf: {
        target: null,
        css:{
            'background-color': 'black',
            'opacity':0.5,
            'position':'absolute',
            'top':150,
            'left':285,
            'width':30,
            'height':30,
            'padding':30
        },
        loadingImage: '/fileadmin/meinl_sites2011/js/jquery-lightbox/images/loading.gif'
    },


    /**
     * Intermition Function
     * @param string target
     * @return void
     */
    _intermission: function(target) {
        if(target == 'start') {
            var loadingImage = $('<img src="'+ScDialogSlider._intermissionConf.loadingImage+'"/>');

            ScDialogSlider._intermissionConf.target = $('<div id="ScDialogSliderIntermissionTarget"></div>');
            ScDialogSlider._intermissionConf.target.css(ScDialogSlider._intermissionConf.css);
            ScDialogSlider._intermissionConf.target.append(loadingImage);

            ScDialogSlider._get(null, 'gallery').find('.scDialogSliderGalleryWrapper').append(ScDialogSlider._intermissionConf.target);

            purge(loadingImage);
        } else if(target == 'stop') {

            if(ScDialogSlider._intermissionConf.target != null) {
                ScDialogSlider._intermissionConf.target.remove();
                ScDialogSlider._intermissionConf.target = null;
            }
        }

        purge(target);

        return;
    },

    /**
     * Function used when the user clicks on the thumbnail
     * @return void
     */
    _thumbnailClick: function() {
        ScDialogSlider._intermission('stop');
        var gallery = ScDialogSlider._get(null, 'gallery'),
            currentLiThumbnail = $(this);

        // remove all .active classes
        $(this).parent().find('li').each(function() {
            if($(this).hasClass('thumbnailActive')) {
                $(this).removeClass('thumbnailActive');
            }
        });

        $(this).addClass('thumbnailActive');

        if(gallery != null) {
            var currentLiElement = gallery.find('li.'+ScDialogSlider._options.galleryImageClass+'.active');
            var img = gallery.find('li.'+ScDialogSlider._options.galleryImageClass+':visible').find('img');

            // animate image
            if(ScDialogSlider._type() == 'image') {
                ScDialogSlider._intermission('start');
                currentLiElement
                    .removeClass('active')
                    .hide()
                    .animate({
                            //opacity:0.4
                        },
                        ScDialogSlider._options.faderTime,
                        'linear',
                        // execute function after animation is complete
                        function() {
                            var listElements = gallery.find('li.'+ScDialogSlider._options.galleryImageClass);

                            currentLiElement.hide();
                            // manipulate Image
                            if(ScDialogSlider._type() == 'image') {
                                listElements
                                    .eq( parseInt(currentLiThumbnail.attr('rel'))-1 )
                                    .each(ScDialogSlider._manipulateSelectedImage);
                            }
                            purge(listElements);
                        }
                    );
            }

            // show and hide video
            if(ScDialogSlider._type() == 'video') {
                ScDialogSlider._intermission('start');
                if ($("a", currentLiElement).length == 0) {
                    var clone = $('<li class="galleryImage">' + currentLiElement.html() + '</li>').insertAfter(currentLiElement);
                    clone.hide();
                    gallery.find('li.'+ScDialogSlider._options.galleryImageClass+'.active').remove();
                }
                else {
                    flowplayer("*").each(function () {
                        this.stop();
                    });
                    currentLiElement
                        .removeClass('active')
                        .hide();
                }

                // manipulate Video
                gallery.find('li.' + ScDialogSlider._options.galleryImageClass)
                    .eq( parseInt(currentLiThumbnail.attr('rel'))-1 )
                    .each(ScDialogSlider._manipulateSelectedVideo);
            }
            purge(gallery);
        }
        purge(currentLiElement);
        purge(currentLiThumbnail);

        return;
    },

    /**
     * Function to update the Meta Information of an Object (i.e. "Picture 2 of 12" )
     * @param int objectNr
     * @return void
     */
    _updateMetaInformation: function (objectNr) {
        var count = ScDialogSlider._get(null, 'gallery').find('li.'+ScDialogSlider._options.galleryImageClass).length
            msg = '',
            type = '';
        objectNr = objectNr || 1;

        type = (ScDialogSlider._type() == 'image') ? ScDialogSlider._options.translationImage : ScDialogSlider._options.translationVideo;
        msg = ScDialogSlider._options.title
            .replace(/%object%/, type)
            .replace(/%num%/, objectNr)
            .replace(/%count%/, count);

        ScDialogSlider._get(null, 'root').dialog('option', 'title', msg);
        ScDialogSlider._options.dialogTitle = msg;

        purge(count);
        purge(type);
        purge(msg);
        return;
    },

    /**
     * Function to show and manipulate the current selected Image
     */
    _manipulateSelectedImage: function() {
        var li = $(this);
        ScDialogSlider._updateMetaInformation( parseInt($(this).index())+1 );

        li
            .css('opacity', 0.2)
            .show()
            .animate({
                opacity:1
                },
                ScDialogSlider._options.faderTime,
                'linear',
                // execute function after animation is complete
                function() {
                    li
                    .addClass('active');

                    ScDialogSlider._intermission('stop');
                }
            );
       // purge(li);
    },

    /**
     * Function to show and manipulate the current selected Video
     */
    _manipulateSelectedVideo: function() {
        ScDialogSlider._updateMetaInformation( parseInt($(this).index())+1 );
        var videoLink = $('.ScPictureItem a', this);

        $(this)
            .css('opacity', 0.2)
            .show()
            .addClass('active')
            .animate({
                opacity:1
            },
            ScDialogSlider._options.faderTime,
            'linear',
            // execute function after animation is complete
            function() {
                ScDialogSlider._intermission('stop');
                videoLink.trigger('click').trigger('click');
            }
        );
        //ScDialogSlider._intermission('start');
    },

    /**
     * Preperation Method of the thumbnail
     * @param int index
     * @return void
     */
    _prepareThumbnail: function (index) {
        var type = ScDialogSlider._type();

        if(index == 0) {
            $(this).addClass('thumbnailActive');
        }

        if(type == 'image') {
            var img = $(this).find('img'),
                pic_real_width = 0,
                pic_real_height = 0;

            // only one img in the current <li>...</li>
            if(img.length > 0 && img.length < 2) {

                $("<img/>") // Make in memory copy of image to avoid css issues
                    .attr("src", img.attr("src"))
                    .each(function() {
                        pic_real_width = this.width;   // Note: $(this).width() will not
                        pic_real_height = this.height; // work for in memory images.
                    });

                $(this)
                    .css({
                        'background-image':     'url('+img.attr('src')+')',
                        'background-position':  '-'+ Math.round( (pic_real_width/ 1.8) -20 ) +'px -' + Math.round( (pic_real_height/ 1.8)-20 ) + 'px'
                    });

            // check if class:thumb exists, if not, use the first img
            } else {
                var backgound_img = $(img[0]);
                img.each(function(index) {
                    if($(this).hasClass('thumb')) {
                        backgound_img = $(this);
                    }
                });

                $(this)
                    .css({
                        'background-image':     'url('+backgound_img.attr('src')+')'
                    });
                purge(backgound_img);
            }

            img.remove();
            purge(img);
        } else if(type == 'video') {
            var thumbnail = $(this).find('img.thumb:first'); // get first thumbnail if available

            // show thumbnail image
            if(thumbnail.length > 0) {
                $(this).html('');
                $(this).append('<div class="videoYoutubeThumbnail" ><img src="fileadmin/meinl_sites2011/images/overlay-play.png" class="playbutton"></div>');
                $('.videoYoutubeThumbnail', this).prepend(thumbnail.clone().height(66));
                thumbnail.remove();
                $(this).addClass('scVideoThumbnail');
            // show dummy image
            } else {
                // display dummy image if available
                if(ScDialogSlider._options.videoDummyImage.length > 0) {
                    $(this).html('');
                    $(this).css({
                        'background-image':     'url('+ScDialogSlider._options.videoDummyImage+')'
                    });
                    $(this).addClass('scVideoThumbnail');
                }
            }
            purge(thumbnail);
        }

        $(this)
            .attr('rel', ($(this).index()+1) )
            .addClass(ScDialogSlider._options.thumbnailClass)
            .click(ScDialogSlider._thumbnailClick);

        // display only n thumbnails
        if ((index+1) <= ScDialogSlider._options.maxThumbnails) {
            $(this).show();
        } else {
            $(this).hide();
        }

        purge(index);
        purge(type);

        return;
    },

    /**
     * Preperation Method of each gallery image
     * @param int index
     * @return void
     */
    _prepareGallery: function (index) {
        var img = $(this).find('img'),
            type = ScDialogSlider._type();

        if(type == 'image') {
            var scWidth = parseInt(img.attr('width'));
            var scHeight = parseInt(img.attr('height'));

            if (scWidth > scHeight) {
                if (scWidth > ScDialogSlider._options.galleryImageWidth) {
                    img.attr('width', ScDialogSlider._options.galleryImageWidth);
                }
                img.removeAttr('height');
            } else {
                if (scHeight > ScDialogSlider._options.galleryImageHeight) {
                    img.attr('height', ScDialogSlider._options.galleryImageHeight);
                }
                img.removeAttr('width');
            }
            // encapsulate the object from the <li>{object}</li> tag
            // and align it in the middle vertically
            var child = $(this).children(':first'),
                encapsulateDiv = $('<div class="ScPictureItem"></div>'),
                table = $('<table class="ScVerticalFix"><tr><td></td></tr></table>');

            encapsulateDiv.append(child);
            table.find('td').html(encapsulateDiv);
            $(this).html(table);
            if(img.length > 1) {
                img.each(function(index) {
                    if($(this).hasClass('thumb')) {
                        $(this).remove();
                    }
                });
            }
        } else if(type == 'video') {
            // encapsulate the object from the <li>{object}</li> tag
            // and align it in the middle vertically
            var child = $(this).children(':first'),
                encapsulateDiv = $('<div class="ScPictureItem"></div>'),
                table = $('<table class="ScVerticalFix"><tr><td></td></tr></table>');

            encapsulateDiv.append(child);
            table.find('td').html(encapsulateDiv);

            if (child.get(0)) {
                encapsulateDiv.css('height', child.get(0).height );
            }
            $(this).html(table);

            $(this).css('width', ScDialogSlider._options.galleryImageWidth);
            // remove all thumb images
            img.each(function(index) {
                if($(this).hasClass('thumb')) {
                    $(this).remove();
                }
            });
        }

        $(this)
            .addClass(ScDialogSlider._options.galleryImageClass)
            .hide();

        purge(img);
        purge(child);
        purge(encapsulateDiv);
        purge(table);
    },

    /**
     * Returns the current type (image/video) as string
     * @return string
     */
    _type: function() {
        var type = 'image'; // default

        if(ScDialogSlider._types[ScDialogSlider._currentName] != undefined) {
            type = ScDialogSlider._types[ScDialogSlider._currentName];
        }

        return type;
    },

    /**
     * Returns a reccource according to its name and type
     * @param string name
     * @param string type
     * @return object
     */
    _get: function(name, type) {
        name = name || ScDialogSlider._currentName;
        var selectedRessource = null;

        switch(type) {
            case 'root':
                if(ScDialogSlider._root[name] != undefined) {
                    selectedRessource = ScDialogSlider._root[name];
                }
                break;
            case 'thumbnails':
                if(ScDialogSlider._thumbnails[name] != undefined) {
                    selectedRessource = ScDialogSlider._thumbnails[name];
                }
                break;
            case 'gallery':
                if(ScDialogSlider._gallery[name] != undefined) {
                    selectedRessource = ScDialogSlider._gallery[name];
                }
                break;
            default: break;
        }
        purge(name);
        purge(type);

        return selectedRessource;
    },

    /**
     * Sets data for a specific type
     * @param string name
     * @param string type
     * @param object data
     * @return void
     */
    _set: function(name, type, data) {
        name = name || 'default';

        switch(type) {
            case 'root':
                ScDialogSlider._root[name] = data;
                break;
            case 'thumbnails':
                ScDialogSlider._thumbnails[name] = data;
                break;
            case 'gallery':
                ScDialogSlider._gallery[name] = data;
                break;
            default: break;
        }

        purge(name);
        purge(type);
        purge(data);

        return;
    },

    /**
     * Creates the initial dialog Window and necessary objects
     * @param string galleryId
     * @param string name The Name of the current gallery. It's need to switch between two or more galleries
     * @param object settings
     * @return object
     */
    init: function (galleryId, name, type, settings) {
        name = name || 'default';
        type = type || 'image';

        var options = {};
        $.extend(
            options,
            ScDialogSlider._defaultOptions,
            settings
        );

        ScDialogSlider._options = options;

        if(galleryId != null) {
            var gallery = null,
                root = null,
                thumbnails = null;

            ScDialogSlider._currentName = name;
            ScDialogSlider._types[ScDialogSlider._currentName] = type;

            if(!$('#'+galleryId).is(':visible')) {
                $('#'+galleryId).show();
            }

            // Set Gallery
            gallery = $('<div class="scDialogSliderGallery" id="' + name + '"></div>');
            gallery .append('<div class="scDialogSliderGalleryWrapper" id="' + name + '"></div>')
                    .find('.scDialogSliderGalleryWrapper:first')
                    .append($('#' + galleryId).html());

            // Set Thumbnails
            thumbnails = $('<div class="scDialogSliderThumbnails" id="' + name + '"></div>');
            thumbnails  .append('<div class="scDialogSliderThumbnailsWrapper" id="' + name + '"></div>')
                        .find('.scDialogSliderThumbnailsWrapper:first')
                        .append($('#' + galleryId).html());

            // Set Root
            root = $('<div class="scDialogSliderRoot" id="' + name + '"></div>');

            // Store
            ScDialogSlider._set(name, 'gallery', gallery);
            ScDialogSlider._set(name, 'thumbnails', thumbnails);

            // Finish concating
            root.append(gallery)
                .append(thumbnails);

            ScDialogSlider._set(name, 'root', root);

            $('#'+galleryId).hide();

            // prepare Thumbnail list
            var thumbnailLi = thumbnails.find('li');
            thumbnailLi.each(ScDialogSlider._prepareThumbnail);

            // display controls if needed
            var hideClass = "";
            if(thumbnailLi.length <= options.maxThumbnails) {
                hideClass = 'hideBackgroundImage';
            }
            thumbnails
                .prepend('<div class="scThumbnailPrev scControl hideBackgroundImage"><a href="javascript:void(0)" onclick="ScDialogSlider.prevThumbnail(\''+name+'\'); return false;">'+options.prev+'</a></div>')
                .append('<div class="scThumbnailNext scControl ' + hideClass + ' "><a href="javascript:void(0)" onclick="ScDialogSlider.nextThumbnail(\''+name+'\'); return false;">'+options.next+'</a></div>');

            // prepare Gallery
            gallery.find('li').each(ScDialogSlider._prepareGallery);
            gallery
                .prepend('<div class="scPrev"><a href="javascript:void(0)" onclick="ScDialogSlider.prev(\''+name+'\'); return false;" class="scControl">'+options.prev+'</a></div>')
                .append('<div class="scNext"><a href="javascript:void(0)" onclick="ScDialogSlider.next(\''+name+'\'); return false;" class="scControl">'+options.next+'</a></div>');

            purge(galleryId);
            purge(gallery);
            purge(thumbnails);
            purge(root);
        }


        purge(name);
        purge(type);
        return;
    },

    /**
     * Opens the dialog window (if available)
     * @return void
     */
    open: function(name) {
        name = name || ScDialogSlider._currentName;
        ScDialogSlider._currentName = name;

        // find active element (if available)
        var activeElement = ScDialogSlider._get(name, 'gallery').find('li.'+ScDialogSlider._options.galleryImageClass+':first');
        var activeLink = $('.ScPictureItem a', activeElement);
        if (typeof(activeLink) != "undefined" && activeLink.attr("data-type") == "video") {
            // first click initializes the flowplayer, second click loads the flowplayer
            activeLink.trigger('click').trigger('click');
        }

        ScDialogSlider._get(name, 'gallery').find('li.'+ScDialogSlider._options.galleryImageClass).each(function (index) {
            if($(this).hasClass('active')) {
                activeElement = $(this);
            }
        });

        // fix image css
        activeElement.each(ScDialogSlider._manipulateSelectedImage);

        if(ScDialogSlider._get(name, 'root') != null) {
            // open dialog
            ScDialogSlider._get(name, 'root').dialog({
                width:  ScDialogSlider._options.width,
                height: ScDialogSlider._options.height,
                modal:  ScDialogSlider._options.modal,
                title: ScDialogSlider._options.dialogTitle,
                resizable: ScDialogSlider._options.resizable,
                close: function(ev, ui) {
                    // resume the news slider
                    window.hasOpenedDialog = false;
                    //$(this).remove();
                }
            });
        }
        // pause the news slider
        window.hasOpenedDialog = true;

        purge(name);
        purge(activeElement);
    },

    /**
     * Clears and removes all traces of current dialogSlider
     * @return void
     */
    clear: function() {
        ScDialogSlider._gallery = null;
        ScDialogSlider._root = null;
        ScDialogSlider._thumbnails = null;
        ScDialogSlider._options = null;

        return;
    },

    reset: function() {
        ScDialogSlider._gallery = new Array();
        ScDialogSlider._root = new Array();
        ScDialogSlider._thumbnails = new Array();
        ScDialogSlider._types = new Array();

        return;
    },

    _visibilityOfArrows: function(direction) {
        name = name || ScDialogSlider._currentName;

        if(ScDialogSlider._get(name, 'thumbnails').find('li').length <= ScDialogSlider._options.maxThumbnails) {
            return;
        }

        var firstVisibleImage = ScDialogSlider._get(name, 'thumbnails').find('li.'+ScDialogSlider._options.thumbnailClass+':visible').first(),
            lastVisibleImage = ScDialogSlider._get(name, 'thumbnails').find('li.'+ScDialogSlider._options.thumbnailClass+':visible').last();

        if(direction == 'prev') {
            if(parseInt(firstVisibleImage.attr('rel')) < 2) {
                $('.scThumbnailPrev').addClass('hideBackgroundImage');
                $('.scThumbnailNext').removeClass('hideBackgroundImage');
            } else {
                $('.scThumbnailPrev').removeClass('hideBackgroundImage');
                $('.scThumbnailNext').removeClass('hideBackgroundImage');
            }
        } else {
            if(ScDialogSlider._get(name, 'thumbnails').find('.'+ScDialogSlider._options.thumbnailClass).length <= parseInt(lastVisibleImage.attr('rel')) ) {
                $('.scThumbnailNext').addClass('hideBackgroundImage');
                $('.scThumbnailPrev').removeClass('hideBackgroundImage');
            } else {
                $('.scThumbnailPrev').removeClass('hideBackgroundImage');
                $('.scThumbnailNext').removeClass('hideBackgroundImage');
            }
        }
        purge(name);
        purge(direction);
        purge(firstVisibleImage);
        purge(lastVisibleImage);
    },

    /**
     * Iterate the Thumbnail List backwards
     * @return void
     */
    prevThumbnail: function(name) {
        name = name || ScDialogSlider._currentName;
        ScDialogSlider._currentName = name;

        var firstVisibleImage = ScDialogSlider._get(name, 'thumbnails').find('li.'+ScDialogSlider._options.thumbnailClass+':visible').first(),
            lastVisibleImage = ScDialogSlider._get(name, 'thumbnails').find('li.'+ScDialogSlider._options.thumbnailClass+':visible').last();

        if(parseInt(firstVisibleImage.attr('rel')) > 1) {
            firstVisibleImage.prev().show();
            lastVisibleImage.hide();
        }

        ScDialogSlider._visibilityOfArrows('prev');
        purge(name);
        purge(firstVisibleImage);
        purge(lastVisibleImage);
    },

    /**
     * Iterate the Thumbnail List forward
     * @return void
     */
    nextThumbnail: function(name) {
        name = name || ScDialogSlider._currentName;
        ScDialogSlider._currentName = name;

        var firstVisibleImage = ScDialogSlider._get(name, 'thumbnails').find('li.'+ScDialogSlider._options.thumbnailClass+':visible').first(),
            lastVisibleImage = ScDialogSlider._get(name, 'thumbnails').find('li.'+ScDialogSlider._options.thumbnailClass+':visible').last();

        if(ScDialogSlider._get(name, 'thumbnails').find('.'+ScDialogSlider._options.thumbnailClass).length > parseInt(lastVisibleImage.attr('rel')) ) {
            firstVisibleImage.hide();
            lastVisibleImage.next().show();
        }

        ScDialogSlider._visibilityOfArrows('next');
        purge(name);
        purge(firstVisibleImage);
        purge(lastVisibleImage);
    },

    /**
     * Iterate one picture backwards
     * @return void
     */
    prev: function(name) {
        name = name || ScDialogSlider._currentName;
        ScDialogSlider._currentName = name;

        var img = ScDialogSlider._get(name, 'gallery').find('li.'+ScDialogSlider._options.galleryImageClass + ':visible'),
            maxImages = ScDialogSlider._get(name, 'gallery').find('li.'+ScDialogSlider._options.galleryImageClass).length;
        var thumbnail = ScDialogSlider._get(name, 'thumbnails').find('li.'+ScDialogSlider._options.thumbnailClass + '[rel='+(img.index()+1)+']');

        if(ScDialogSlider._get(name, 'thumbnails').find('li.'+ScDialogSlider._options.thumbnailClass).length > ScDialogSlider._options.maxThumbnails) {
            var count = 0;
            while(!thumbnail.prev().is(':visible')) {
                if(count > maxImages) {
                    break;
                }
                ScDialogSlider.prevThumbnail();
                count += 1;
            }
        }
        thumbnail.prev().trigger('click');

        purge(name);
        purge(thumbnail);
        purge(img);
        purge(maxImages);
        purge(count);
    },

    /**
     * Iterate one picture forward
     * @return void
     */
    next: function(name) {
        name = name || ScDialogSlider._currentName;
        ScDialogSlider._currentName = name;

        var img = ScDialogSlider._get(name, 'gallery').find('li.'+ScDialogSlider._options.galleryImageClass + ':visible'),
            maxImages = ScDialogSlider._get(name, 'gallery').find('li.'+ScDialogSlider._options.galleryImageClass).length;
        var thumbnail = ScDialogSlider._get(name, 'thumbnails').find('li.'+ScDialogSlider._options.thumbnailClass + '[rel='+(img.index()+1)+']');

        if(ScDialogSlider._get(name, 'thumbnails').find('li.'+ScDialogSlider._options.thumbnailClass).length > ScDialogSlider._options.maxThumbnails) {
            var count = 0;
            while(!thumbnail.next().is(':visible')) {
                if(count > maxImages) {
                    break;
                }
                ScDialogSlider.nextThumbnail();
                count += 1;
            }
        }
        thumbnail.next().trigger('click');

        purge(name);
        purge(thumbnail);
        purge(img);
        purge(maxImages);
        purge(count);
    }
}

function toggle(id){
    var element = document.getElementById("id");

    if(element.style.display != 'block'){
        element.style.display = 'none';
        var ytobject = document.getElementById("youtubeplayerid");
        if(ytobject.stopVideo) {
            ytobject.stopVideo();
        }
    } else {
        element.style.display = 'block';
        var element = document.getElementById("youtubeplayerid");
        if(ytobject.playVidep) {
            ytobject.playVideo();
        }
    }
}

function purge(d) {
    if (typeof(d) != "undefined") {
        var a = d.attributes, i, l, n;
        if (a) {
            for (i=0, l=a.length; i<l; i++) {
                n = a[i].name;
                if (typeof d[n] === 'function') {
                    d[n] = null;
                }
            }
        }
        a = d.childNodes;
        if (a) {
            for (i=0, l=a.length; i<l; i++) {
                purge(d.childNodes[i]);
            }
         }
        delete d;
    }
}
