/*
 *            Based on mbGallery-Script
 *            developed by Matteo Bicocchi on JQuery
 *          © 2002-2009 Open Lab srl, Matteo Bicocchi
 *            www.open-lab.com - info@open-lab.com
 *           version 1.0
 *           tested on:     Explorer and FireFox for PC
 *                          FireFox and Safari for Mac Os X
 *                          FireFox for Linux
 *         GPL (GPL-LICENSE.txt) licenses.
 */


jQuery.fn.cduGallery = function (NewOptions)
{
    return this.each (function () {
        var galleryId = !this.id ? Math.floor (Math.random () * 100): this.id;
        var gallery = this;

        this.options = {
            galleryWidth : 300,
            galleryHeight : 300,
            galleryMaxWidth : 0,
            galleryColor : "white",
            galleryFrameBorder : 30,
            galleryFrameColor : "white",

            startFrom : 0,
            headerOpacity : 0.5,
            thumbsBorder : 5,
            thumbHeight : 30,
            thumbStripColor : "black",
            thumbStripPos : "right",
                        thumbStripWidth:250,
            thumbSelectColor : "black",
            thumbOverColor : "#cccccc",
            imageSelector : ".imgFull",
            thumbnailSelector : ".imgThumb",
            descSelector : ".imgDesc",
                        descriptionWidth:300,

            labelColor : "yellow",
            labelColorDisactive:"white",
            labelTextColor : "black",
            labelTextSize : "9px",
            labelHeight : 25,
            iconFolder: "elements/black",
            fadeTime : 300,
            autoSlide : true,
            slideTimer : 100,
            autoSize : true,
            startTimer:0

        }

        $.extend (this.options, NewOptions);
                var opt= this.options;

                opt.thumbsBorder = opt.thumbsBorder + "px solid";
        var thumbSel = {
            thumbSel :
            {
                border : opt.thumbsBorder, borderColor : opt.thumbSelectColor
            },
            thumbUnsel :
            {
                border : opt.thumbsBorder, borderColor : opt.thumbStripColor
            },
            thumbOver :
            {
                border : opt.thumbsBorder, borderColor : opt.thumbOverColor
            }
        }
        $.extend (opt, thumbSel);
        if (opt.slideTimer < 2000)
            opt.slideTimer = 2000;
        var actualImg;
        var actualThumb;
        var thumbUnsel = opt.thumbUnsel;
        var thumbOver = opt.thumbOver;
        $ (this).hide ();

                // GETTING THE ELEMENTS FOR THE GALLERY FROM THE PAGE
        var thumbs = $ (this).find (opt.thumbnailSelector).show();
        var full = $ (this).find (opt.imageSelector);
        var imgDesc = $ (this).find (opt.descSelector);
        var video = $ (this).find (".video");
        var playvideo = $(this).find(".playvideo");
        
        $ (this).empty ();
        if (opt.startFrom == "random")
            opt.startFrom = Math.floor (Math.random () * full.length);

        function preloadImg(i) {
            $ (thumbloading).find ("img").attr ("src", "/images/bas/loader.gif");
            var IMG_URL = $ (full [i]).attr ("src");
            var IMGOBJ = new Image ();
            IMGOBJ.onload = function ()
            {
                $ (thumbloading).find ("img").attr ("src", "/images/bas/loaded.gif");
                changePhoto (i);
            };
            IMGOBJ.onerror = function ()
            {
                //alert ("can't load " + IMG_URL)
            };
            IMGOBJ.src = IMG_URL;
        }

        var thumbPos = "";
                var pos;
                function setThumbPos(w) {
            switch (opt.thumbStripPos)
                {
                case "left" :
                    return pos = 0;
                    break;
                case "center" :
                    return pos = ((w / 2) - (opt.thumbStripWidth / 2));
                    break;
                case "right" :
                    return pos = (w - opt.thumbStripWidth);
                    break;
                        default:
                            return pos = 0;
                            break;
                        }
                };
        thumbPos = setThumbPos (opt.galleryWidth);

        $ (this).parent().append ("<table cellpadding='0' cellspacing='0' height='"+opt.galleryHeight+"'><tr><td id ='gallery_"+galleryId+"'></td></tr></table>");
        var galleryContainer= $ (this).parent().find('#gallery_'+galleryId);
        $ (galleryContainer).css(
        {
            border : opt.galleryFrameBorder + "px solid " + opt.galleryFrameColor,
                        background: opt.galleryColor
                })
        $ (galleryContainer).append(this);

        // CREATE THE GALLERY STRUCTURE FOR FULLSIZE IMAGES
        $ (this).append ("<div class='FullImg'></div>");
        var fullImageArea = $ (this).find (" .FullImg");
            
        // CREATE THE GALLERY STRUCTURE FOR THUMBS IMAGES
        var headerH = opt.labelHeight > 0?opt.labelHeight : opt.galleryFrameBorder;

        $ (this).removeAttr ("title");

        // thumbnail container
        $ (galleryContainer).prepend ("<div class='thumbBox'></div>");
        var thumbBox = $ (galleryContainer).find (" .thumbBox");

        //thumbnail navigator
        $ (thumbBox).prepend ("<div class='header'><table cellpadding='0' cellspacing='0'><td class='prev pointer' ></td><td class='indexLabel' nowrap></td><td class='next pointer' ></td><td class='spacer' ></td><td class='loader'></td><td class='spacer' ></td></td><td class='thumbWinBtn pointer' ></div>");
        var header = $ (thumbBox).find (" .header");

        var thumbWinBtn = $ (header).find (".thumbWinBtn");
        $ (thumbWinBtn).append ("Alle Themen <img src='/images/bas/index.png' class='thumbIco'>");

        var slideShow = $ (header).find (".slideShow");
        $ (slideShow).append ("<img src='/images/bas/play.gif' class='slideIco'>");

        var thumbloading = $ (header).find (".loader");
        $ (thumbloading).append ("<img src='/images/bas/loaded.gif'>");

        var spacer = $ (header).find (".spacer");
        
        var next = $ (header).find (".next");
        $ (next).append ("<img src='/images/bas/more.png'>");

        var prev = $ (header).find (".prev");
        $ (prev).append ("<img src='/images/bas/back.png'>");

        var indexLabel = $ (thumbBox).find (" .indexLabel").html ((opt.startFrom + 1) + " / <b>" + full.length + "</b>");

        

        //Thumbnails
        $ (thumbBox).prepend ("<div class='ThumbImg'><div class='ThumbImgInner'></div></div>");
        var thumbImages = $ (thumbBox).find (" .ThumbImg");
        var thumbImagesInner = $ (thumbImages).find (" .ThumbImgInner");
        $ (thumbImagesInner).prepend ($ (thumbs));

        //close Thumbnails-Area link
        $ (thumbBox).prepend ("<div class='closeThumbArea' style='display: none;'><div>zurück</div></div>");
        var closeThumbArea = $ (thumbBox).find (".closeThumbArea");

        $ (thumbBox).prepend("<div class='descriptionBox'></div>");
        var descriptionBox= $ (galleryContainer).find(".descriptionBox");
        $ (descriptionBox).css(
        {
            position:"absolute",
            padding: 10,
            zIndex:0,
            opacity: opt.headerOpacity,
            width : opt.thumbStripWidth-20,
            height: opt.galleryHeight-50
        })

        $ (thumbBox).prepend("<div class='videoBox'></div>");
        var videoBox= $ (galleryContainer).find(".videoBox");
        $ (thumbBox).prepend("<div class='closeVideoArea' style='display: none;'><div>zurück</div></div>");
        var closeVideoArea = $ (thumbBox).find (".closeVideoArea");
        
        $ (this).css (
        {
            width : opt.galleryWidth,
            height : opt.galleryHeight,
            overflow : "hidden"
        });

        $ (thumbs).css (
        {
            width : opt.thumbHeight,
            padding : "0px",
            border: "1px solid "+opt.labelColor,
            cursor : "pointer"
        });

        $ (thumbBox).css (
        {
            textAlign : "left",
            zIndex : 1000,
            /*marginTop : "-" + headerH + "px",*/
            marginTop: 0,            
            position : "absolute",
            width : opt.thumbStripWidth + "px",
            marginLeft : thumbPos + "px"
        });

        $ (thumbImages).css (
        {
            /*opacity : opt.headerOpacity,*/
            display: 'none',
            backgroundColor : opt.thumbStripColor,
               height: opt.galleryHeight - headerH
        });

        $ (closeThumbArea).css ({
            /*opacity : opt.headerOpacity,*/
            backgroundColor : opt.thumbStripColor,
            height: headerH,
            position: "absolute",
            marginTop: opt.galleryHeight - headerH
        });

        $ (closeVideoArea).css ({
            /*opacity : opt.headerOpacity,*/
            backgroundColor : opt.thumbStripColor,
            height: headerH,
            position: "absolute",
            marginTop: opt.galleryHeight - headerH
        });

        $ (videoBox).css(
        {
            display: 'none'
        })

        $ (header).css (
        {
            opacity : opt.headerOpacity,
            textAlign : "left",
            color : opt.labelTextColor,
            padding : "0px",
            border : "0px",
            height : headerH,
            position : "absolute",
            width: opt.thumbStripWidth + "px",
            marginTop : opt.galleryHeight - headerH
        });

        $ ("td", header).css (
        {
            background : opt.labelColorDisactive,
            padding : "2px",
            paddingRight : "10px",
            height:headerH,
            color : opt.labelTextColor,
            fontFamily : "Verdana, Arial",
            fontSize : opt.labelTextSize
        });

        $ (".pointer").css (
        {
            cursor : "pointer"
        });

        jQuery.fn.extend (
        {
            getW : function () {
                var ow = $ (this).width ();
                if (opt.galleryMaxWidth > 0 && ow > opt.galleryMaxWidth) {
                    $ (this).attr ("width", opt.galleryMaxWidth);
                    ow = opt.galleryMaxWidth;
                }
                return ow;
            }
        });

        var actualVideoID;
        function changePhoto (i) {
            $ (descriptionBox).fadeTo (opt.fadeTime, 0);
            
            $ (video).hide();
            $ (fullImageArea).fadeTo (opt.fadeTime, 0, function () {
                //replacing the image
                $ (this).html (full [i]);
                $(descriptionBox).html(imgDesc[i]);
                //$ (videoBox).html($(video[i]).html()); 
                
                if($(video[i]).html() != '') {
                    //$(playvideo[i]).html("Video abspielen"); 
                    $(playvideo[i]).html("<img src='/images/bas/play.png'>");
                    $(playvideo[i]).css ({
                        border : "0px",
                        position : "absolute",
                        top: (opt.galleryHeight - 62)/2,
                        left: (opt.galleryWidth - 62)/2
                    });
                    actualVideoID = $(video[i]).html();
                }
                //alert($(playvideo[i]).html());
                $(playvideo[i]).bind("click", function(e){
                    playActualVideo(i);
                });
                
                                
                //showing the new image
                setTimeout (function () {
                    $ (fullImageArea).fadeTo (opt.fadeTime, 1)
                    $ (descriptionBox).fadeTo (opt.fadeTime, 1);
                }, opt.fadeTime);
                // if autosize option resize the image frame
                if (opt.autoSize) {
                    //if a maxWith is set resize the image width
                    var w = $ (full [i]).getW ();
                    //resize frame
                    $ (gallery).animate (
                    {
                        height : full [i].offsetHeight,
                        width : w
                    }, opt.fadeTime);
                }
            });
            //redefine the indexLabeles
            $ (actualThumb).css (thumbUnsel);
            actualImg = full [i];
            actualThumb = thumbs [i];
            $ (actualThumb).css (opt.thumbSel);
            $ (indexLabel).html (i +1 + " / <b>" + full.length + "</b>");
        }

        thumbs.each (function (i) {
            $ (this).click (function () {
                x = i;
                stopShow ();
                preloadImg (i);
                setTimeout(function(){
                    $ (full).css ({opacity : 1 });
                    /*$ (full).fadeTo (0, 1);*/
                    $ (closeThumbArea).hide();
                    $ (thumbImages).hide (0); 
                    
                    //vk and show description and header
                    //and set thumbOpen to false actualy
                    $ (descriptionBox).show();
                    thumbOpen = false;
                    $ (header).show();
                },300)
                
                
            })
        })
        $ (this).show ();

        // EVENTS
        var hideTumb, thumbOpen, headerMO;
        $ (thumbWinBtn).click (function () {
            if ( !thumbOpen) {
                //vk hide description and header before showing thimb images
                $ (descriptionBox).hide(0);
                $ (header).hide(0);
                $ (actualImg).css ({opacity : 0.5 });
                $ (thumbImages).show ();
                //$ (thumbImages).show (300);
                $ (closeThumbArea).css ({ display: 'block' });
                thumbOpen = true;
            } else {
                $ (full).css ({opacity : 1 });
                $ (closeThumbArea).hide();
                $ (thumbImages).hide (0); 
                //vk show description and header immediately after closing thumb area 
                $ (descriptionBox).show();
                $ (header).show();
                thumbOpen = false;
            }
            stopShow ();
        })

        //vk clicking on closeThumbArea
        $ (closeThumbArea).click (function () {
            if ( !thumbOpen) {
                //do nothing
                
            } else {
                $ (actualImg).css ({opacity : 1 });
                $ (closeThumbArea).hide();
                $ (thumbImages).hide (0); 
                $ (descriptionBox).show();
                $ (header).show();
                thumbOpen = false;
            }
            stopShow ();
        })

        $ (closeVideoArea).click (function () {
            $ (videoBox).css ({ display: 'none' }); 
            $ (closeVideoArea).hide();
            $ (video).hide();
            writePlayerCode();

            $ (actualImg).css ({opacity : 1, display: 'block' });
            $ (closeThumbArea).hide();
            $ (thumbImages).hide (0); 
            $ (descriptionBox).show();
            $ (header).show();
            thumbOpen = false;
            stopShow ();            
        })

        
        function playActualVideo(i) {
            writePlayerCode();

            $ (descriptionBox).hide();
            //$ (header).css ({ marginTop: 0 });
            $ (header).hide(0);
            $ (actualImg).hide();
            $ (closeVideoArea).show();
            $ (video).show();
            $ (videoBox).css ({ display: 'block' }); 
        }

        var playerOpen,oldVideoURL;
        function writePlayerCode() {
            //var actualEmbed = $ (videoBox).find ("embed");
            //var actualURL = $(actualEmbed).attr("src");
            
            //var actualVideoID = $ (videoBox);
            var actualURL = "http://www.youtube.com/v/" +  actualVideoID + "&hl=de&fs=1&rel=0";
            
            if(playerOpen) {
                $(videoBox).html('<div class="video" >'+actualVideoID+'</div>');
                oldVideoURL = '';
                playerOpen = false;
            } else {
                $(videoBox).html('<div class="video" ><object width="572" height="287" ><param name="movie" value="'+actualURL+'&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="'+actualURL+'&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="572" height="287" ></embed></object></div>');
                oldVideoURL = actualURL;
                playerOpen = true;
            }
        }
        
        //vk disabled start/stop slideshow on mouseClick event 
        /*$ (fullImageArea).click (function () {
            stopShow ();
        });
        $ (fullImageArea).dblclick (function () {
            startShow ();
        });*/

        //vk disabled thumbBox closing  after on mousout event
        /*$ (thumbBox).mouseover (function () {
            clearTimeout (hideTumb);
            clearTimeout (headerMO);
            $ ("td", header).css ({opacity :opt.headerOpacity, background: opt.labelColor})
            clearTimeout (closeThumbStrip);
        })

        $ (thumbBox).mouseout (function () {
            headerMO=setTimeout(function(){
                $ ("td", header).css ({opacity :opt.headerOpacity, background: opt.labelColor})
            },100)
            hideTumb = setTimeout (function () {
                $ (thumbImages).hide (300);
                $ (descriptionBox).show();
                thumbOpen = false;
            }, 1000);
        })*/

        $ (thumbs).mouseover (function () {
            if (this != actualThumb) {
                $ (this).css (thumbOver)
            }
        })
        $ (thumbs).mouseout (function () {
            if (this != actualThumb) {
                $ (this).css (thumbUnsel)
            }
        });

        $ (slideShow).click (function () {
            startSlide = ! startSlide;
            if (startSlide) {
                startShow ();
            } else
                stopShow ();
        })

        var goOn;

        $ (next).click ( function () {
            stopShow ();
            clearTimeout (goOn);
            x += 1;
            goOn = setTimeout (function () {
                if (x >= full.length) x = 0;
                preloadImg (x);
            }, 200);
        })

        $ (prev).click ( function () {
            stopShow ();
            clearTimeout (goOn);
            x -= 1;
            goOn = setTimeout (function () {
                if (x < 0) x = full.length - 1;
                preloadImg (x);
            }, 200);
        })

        actualImg = full [opt.startFrom];
        $ (thumbs).css (thumbUnsel);
        actualThumb = thumbs [opt.startFrom];
        $ (actualThumb).css (thumbSel);

        var closeThumbStrip = setTimeout (function () {
            $ (thumbImages).hide (500)
        }, 2000);
            
        var slideShowTimer, x = opt.startFrom, startSlide = opt.autoSlide, startShow = function () {
            $ (slideShow).find ("img").attr ("src", "/images/bas/stop.gif")
            if (x == full.length)
                x = 0;
            preloadImg (x);
            slideShowTimer = setTimeout (startShow, opt.slideTimer)
            x ++
        };
        function stopShow() {
            clearTimeout (slideShowTimer);
            $ (slideShow).find ("img").attr ("src", "/images/bas/play.gif");
            startSlide = false;
        }
        if (startSlide) {
            setTimeout (startShow, opt.startTimer);
        } else {
            setTimeout (function () {
                preloadImg (opt.startFrom)
            }, opt.startTimer);
        }
    })
}
