/*
*       gallery by Matteo Bicocchi
*       © 2002-2007 Open Lab srl, Matteo Bicocchi
*			  www.open-lab.com - info@open-lab.com
*       	version 1.0
*       	free to use - please don't cut this lines
*       	tested on: 	Explorer, Mozilla, Netscape and Opera for PC
*                  			Mozilla, Netscape and Safari for Mac Os X
*                  			Mozilla for Linux
*/


jQuery.fn.mbGallery = 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 : "white",
      thumbStripPos : "right",
      thumbSelectColor : "black",
      thumbOverColor : "#cccccc",
      imageSelector : ".imgFull",
      thumbnailSelector : ".imgThumb",
      descSelector : ".imgDesc",
      descriptionWidth:300,

      labelColor : "yellow",
      labelColorDisactive:"white",
      labelTextColor : "black",
      labelTextSize : "9px",
      labelHeight : 25,
      iconFolder: contextPath +"/applications/webwork/site_" + installationId + "/local/portlet/photoGallery/elements/black",
      fadeTime : 300,
      autoSlide : true,
      slideTimer : 100,
      autoSize : true,
      startTimer:0
    }

    $.extend (this.options, NewOptions);
    var options = this.options;
    var prop = "";
    for (property in options) {
      var p = options [property];
      p = (p == true || p == false || typeof p == "number") ? p : "'" + p + "'";
      eval ("var " + property + " = " + p);
    }
    thumbsBorder = thumbsBorder + "px solid";
    if ( ! thumbStripWidth) var thumbStripWidth = galleryWidth;
    if ( ! thumbUnselectColor) var thumbUnselectColor = thumbStripColor;
    var thumbSel = {
      thumbSel :
      {
        border : thumbsBorder, borderColor : thumbSelectColor
      },
      thumbUnsel :
      {
        border : thumbsBorder, borderColor : thumbUnselectColor
      },
      thumbOver :
      {
        border : thumbsBorder, borderColor : thumbOverColor
      }
    }
    $.extend (this.options, thumbSel);
    if (slideTimer < 2000)
      slideTimer = 2500;
    var actualImg;
    var actualThumb;
    var thumbSel = this.options.thumbSel;
    var thumbUnsel = this.options.thumbUnsel;
    var thumbOver = this.options.thumbOver;
    $ (this).css (
    {
      width : galleryWidth,
      height : galleryHeight,
      background:galleryColor,
      overflow : "hidden"
    });
    // GETTING THE ELEMENTS FOR THE GALLERY FROM THE PAGE
    var thumbs = $ (this).find (thumbnailSelector);
    var full = $ (this).find (imageSelector);
    var imgDesc = $ (this).find (descSelector);

    $ (this).empty ();
    if (startFrom == "random")
      startFrom = Math.floor (Math.random () * full.length);

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

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

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

    // CREATE THE GALLERY STRUCTURE FOR FULLSIZE IMAGES
    $ (this).append ("<div class='FullImg'></div>");
    var fullImageArea = $ (this).find (" .FullImg");
    var theImg = $ (fullImageArea, "img");

    // CREATE THE GALLERY STRUCTURE FOR THUMBS IMAGES
    var headerH = labelHeight > 0?labelHeight : galleryFrameBorder;

    var galleryTitle = $ (this).attr ("title");
    $ (this).removeAttr ("title");

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

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

    var thumbWinBtn = $ (header).find (".thumbWinBtn");
    $ (thumbWinBtn).append ("<img src='"+iconFolder+"/thumb.gif' class='thumbIco'>");

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

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

    var spacer = $ (header).find (".spacer");
    $ (spacer).append ("<img src='"+iconFolder+"/separator.gif'>");

    var next = $ (header).find (".next");
    $ (next).append ("<img src='"+iconFolder+"/next.gif'>");

    var prev = $ (header).find (".prev");
    $ (prev).append ("<img src='"+iconFolder+"/prev.gif'>");

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

    //Thumbnails
    $ (thumbBox).append ("<div class='ThumbImg'></div>");
    var thumbImages = $ (thumbBox).find (" .ThumbImg");
    $(thumbBox).css("opacity",0);
    $ (thumbImages).prepend ($ (thumbs));

    $ (thumbBox).append("<div class='descriptionBox'></div>");
    var descriptionBox= $ (galleryContainer).find(".descriptionBox");
    $ (descriptionBox).css(
    {
      position:"absolute",
      padding: 10,
      zIndex:0,
      opacity: .8,
      width : $.browser.msie? thumbStripWidth : thumbStripWidth-20
    })

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

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

    $ (thumbImages).css (
    {
      opacity :.8,
      backgroundColor : thumbStripColor,
      border: "2px solid "+ labelColor
    });

    $ (header).css (
    {
      opacity : headerOpacity,
      textAlign : "left",
      color : labelTextColor,
      padding : "0px",
      border : "0px",
      height : headerH
    });

    $ ("td", header).css (
    {
      background : labelColorDisactive,
      padding : "2px",
      paddingRight : "10px",
      height:headerH,
      color : labelTextColor,
      fontFamily : "Verdana, Arial",
      fontSize : labelTextSize
    });
    setTimeout(function(){$(thumbBox).fadeTo(1000,1)},1000);
    $ (".pointer").css (
    {
      cursor : "pointer"
    });

    jQuery.fn.extend (
    {
      getW : function () {
        var ow = $ (this).width ();
        if (galleryMaxWidth > 0 && ow > galleryMaxWidth) {
          $ (this).attr ("width", galleryMaxWidth);
          ow = galleryMaxWidth;
        }
        return ow;
      }
    });
    function changePhoto (i) {
      $ (descriptionBox).fadeTo (fadeTime, 0);
      $ (fullImageArea).fadeTo (fadeTime, 0, function () {
        //replacing the image
        $(this).show()
        $ (this).html ("<img src='"+$(full [i]).attr("src")+"' style='visibility:visible'>");
        if (imgDesc[i] && $(imgDesc[i]).html()!="") $(descriptionBox).html(imgDesc[i]);
        //showing the new image
        setTimeout (function () {
          $ (fullImageArea).fadeTo (fadeTime, 1)
          if (imgDesc[i] && $(imgDesc[i]).html()!=""){$ (descriptionBox).fadeTo (fadeTime, .8)};
        }, fadeTime);
        // if autosize option resize the image frame
        if (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
          }, fadeTime);
          //if the thumbstrip has no width set the width according ti the frame width
          if (thumbStripWidth == galleryWidth) {
            $ (thumbBox).animate (
            {
              width : full [i].offsetWidth
            },
                fadeTime)
          } else {
            // if the thumbstrip has a width reposition it according to the image width
            var l = setThumbPos ($ (full [i]).width ());
            $ (thumbBox).animate (
            {
              marginLeft : l
            }, fadeTime);
          }
        }
      });
      //redefine the indexLabeles
      $ (actualThumb).css (thumbUnsel);
      actualImg = full [i];
      actualThumb = thumbs [i];
      $ (actualThumb).css (thumbSel);
      $ (indexLabel).html (i +1 + ".<b>" + full.length + "</b>");
    }
    thumbs.each (function (i) {
      $ (this).click (function () {
        x = i;
        stopShow ();
        preloadImg (i);
        setTimeout(function(){$ (thumbImages).hide (500);},500)
      })
    })
    $ (this).show ();

    // EVENTS
    var hideTumb, thumbOpen, headerMO;
    $ (thumbWinBtn).click (function () {
      if ( !thumbOpen) {
        $ (thumbImages).show (500);
        thumbOpen = true;
      } else {
        $ (thumbImages).hide (500);
        thumbOpen = false;
      }
      stopShow ();
    })
    $ (fullImageArea).click (function () {
      stopShow ();
    });
    $ (fullImageArea).dblclick (function () {
      startShow ();
    });
    $ (thumbBox).mouseover (function () {
      clearTimeout (hideTumb);
      clearTimeout (headerMO);
      //$ (header).css ({opacity :1, background: labelColor});
      $ ("td", header).css ({opacity :1, background: labelColor})
      clearTimeout (closeThumbStrip);
    })

    $ (thumbBox).mouseout (function () {
      headerMO=setTimeout(function(){
        //$ (header).css ({opacity : headerOpacity, background: labelColorDisactive})
        $ ("td", header).css ({opacity :1, background: labelColor})
      },100)
      hideTumb = setTimeout (function () {
        $ (thumbImages).hide (500);
        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 [startFrom];
    $ (thumbs).css (thumbUnsel);
    actualThumb = thumbs [startFrom];
    $ (actualThumb).css (thumbSel);
    var closeThumbStrip = setTimeout (function () {
      $ (thumbImages).hide (500)
    }, 2000);
    var slideShowTimer, x = startFrom, startSlide = autoSlide, startShow = function () {
      $ (slideShow).find ("img").attr ("src", iconFolder+"/stop.gif")
      if (x == full.length)
        x = 0;
      preloadImg (x);
      slideShowTimer = setTimeout (startShow, slideTimer)
      x ++
    };
    var stopShow = function () {
      clearTimeout (slideShowTimer);
      $ (slideShow).find ("img").attr ("src", iconFolder+"/play.gif");
      startSlide = false;
    }
    if (startSlide) {
      setTimeout (startShow, startTimer);
    } else {
      setTimeout (function () {
        preloadImg (startFrom)
      }, startTimer);
    }
  })
}

