/*
 *         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.
 */

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

      this.options = {
        galleryID: "galleryID",
		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

      };

      var closeThumbStrip,actualImg,actualThumb,thumbUnsel,thumbOver,thumbs,full,imgDesc;

      $.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;

      thumbUnsel = opt.thumbUnsel;
      thumbOver = opt.thumbOver;
      $(this).hide();

      // GETTING THE ELEMENTS FOR THE GALLERY FROM THE PAGE
      thumbs = $(this).find(opt.thumbnailSelector);
      full = $(this).find(opt.imageSelector);
      imgDesc = $(this).find(opt.descSelector);
      $(this).empty();

      if(opt.startFrom == "random")
        opt.startFrom = Math.floor(Math.random() * full.length);

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

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

      thumbPos = setThumbPos(opt.galleryWidth);

      $(this).parent().append("<table id='"+galleryId+"' class='mbGallery' cellpadding='0' cellspacing='0' height='"+opt.galleryHeight+"'><tr><td id ='gallery_"+galleryId+"'></td></tr></table>");
      var myGallery= $(this).parent().find('.mbGallery');
      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;

      // 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' width='600'><tr>" +
                          //"<td width='180' id='submenu'><!--a href='#' class='act'>Client</a>&nbsp;&nbsp;<a href='#'>Category</a--></td>" +
						  "<td width='120' class='thumbWinBtn pointer'> </td>" +
                          "<td width='110' class='slideShow pointer'> </td>" +
                          "<td width='30' class='prev pointer'  align='right' > </td>" +
						  "<td width='150' align='center' class='indexLabel' nowrap> </td>" +
                          "<td width='50' class='next pointer' > </td>" +
                          //"<td class='loader'> </td>" +
                       	  "<td class='navigator pointer' align='right' > </td>" +
                          "</tr></table>" +
                          "</div>");
      var header = $(thumbBox).find(".header");

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

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

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

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

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

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

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

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

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


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


      $(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",
        position:"absolute",
        width:opt.thumbStripWidth + "px",
        marginLeft:thumbPos + "px",
        zIndex:10000
      });

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

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

      $(header).find("td").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;
        }
      });
      function changePhoto(i) {
        $(fullImageArea).click(function(){clickFullImageArea()});
        //$(descriptionBox).fadeTo(opt.fadeTime, 0);
		$(descriptionBox).fadeTo(1, 0);
        $(fullImageArea).fadeTo(opt.fadeTime, 0, function() {
          //replacing the image
          $(this).html(full [i]);
		  loadYoutubeVideo();
		  
		  
          $(descriptionBox).html(imgDesc[i]);
          //showing the new image
          setTimeout(function() {
            $(fullImageArea).fadeTo(opt.fadeTime, 1);
            //$(descriptionBox).fadeTo(opt.fadeTime, .8);
			$(descriptionBox).fadeTo(0, 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);
            //if the thumbstrip has no width set the width according ti the frame width
            if(opt.thumbStripWidth == opt.galleryWidth) {
              $(thumbBox).animate(
              {
                width: full[i].offsetWidth
              },opt.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
              }, 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>");
		$(indexLabel).html((i +1)+ "." + full.length + "");
      }
      thumbs.each(function(i) {
        $(this).click(function() {
          x = i;
          stopShow();
          preloadImg(i);
          setTimeout(function(){$(thumbImages).hide(opt.fadeTime);},opt.fadeTime);
        });
      });
      $(this).show();

      // EVENTS
      var hideTumb, thumbOpen, headerMO;
	  
	  // INTEGRAZIONE
	 $(navigatorShow).click(function() {
		$(thumbImages).hide(opt.fadeTime);
	 	thumbOpen = false;
        stopShow();
		var navImg = $(fullImageArea).children('.imgFull').attr("zoom");
        var IMGOBJ = new Image();
        IMGOBJ.src = navImg;
		IMGOBJ.onload = function() {
			// alert(navImg);
			if (navImg.indexOf("/")!=-1) {
				var indexArea = Math.floor(Math.random() * 100);
				var navArea = '<div id="navArea' + indexArea + '">';
				navArea += '<div style="display:none;" class="imagesContainer {imageUrl:\'' + navImg + '\', navPosition:\'BR\', navWidth: 100}">';
				navArea += '</div>';
				navArea += '</div>';
				$(fullImageArea).html(navArea);
				
				$("#navArea" + indexArea).imageNavigator({
					areaWidth: 600,
					areaHeight: 400,
					draggerStyle:"1px dotted red",
					navOpacity:.8
				})
			} else {
				// create 
			}
        };
        IMGOBJ.onerror = function() {
          alert("can't load " + IMG_URL);
        };

		
		
      });
	 
      $(thumbWinBtn).click(function() {
        if( !thumbOpen) {
          $(thumbImages).show(opt.fadeTime);
          thumbOpen = true;
        } else {
          $(thumbImages).hide(opt.fadeTime);
          thumbOpen = false;
        }
        stopShow();
      });
      
	  //$(fullImageArea).click(function(){loadYoutubeVideo()});
	  $(fullImageArea).click(function(){
			clickFullImageArea();
		});
	  
	  function clickFullImageArea(){
			 stopShow();
			$(fullImageArea).unbind('click');
		}
	 function loadYoutubeVideo() {
        if ($(fullImageArea).html().indexOf("href")==-1 && $(fullImageArea).html().indexOf("vidbox")!=-1) {
			var vid = $(fullImageArea).children('.imgFull').attr('vidbox');
			var hfia = $(fullImageArea).html();
			$(fullImageArea).html(hfia + "<div style='position:relative'><div style='position:absolute;z-index:9999;top:-316px;left:97px;'><a style='background:#000;color:#FFF' class=\"media {width:410, height:257, type:'swf', autoplay: true}\" href=\"" + vid + "\"></a></div></div>");
			$('a.media').media();
			//$(fullImageArea).html(hfia + "<div style='position:relative'><div style='position:absolute;z-index:9999;top:-316px;left:97px;'><a style='background:#000;color:#FFF' target='_blank' href=\"" + vid + "\"><img border='0' src='/shim.gif' width='410' height='257'></a></div></div>");
		}
	  }
	
	 function loadYoutubeVideo2() {
        if ($(fullImageArea).html().indexOf("href")==-1 && $(fullImageArea).html().indexOf("vidbox")!=-1) {
			var vid = $(fullImageArea).children('.imgFull').attr('vidbox');
			//alert(vid);
			//$(fullImageArea).html('<a href="' + vid + '" class="vidbox">' + $(fullImageArea).html() + '</a>');
			//$(".vidbox").jqvideobox();
			stopShow();
			var hfia = $(fullImageArea).html();
			$(fullImageArea).html(hfia + "<div style='position:relative'><div style='position:absolute;z-index:9999;top:-316px;left:97px;'><a style='background:#000;color:#FFF' class=\"media {width:410, height:257, type:'swf', autoplay: true}\" href=\"" + vid + "\"></a></div></div>");
			//$(fullImageArea).html(hfia + '<div style="position:relative"><div style="position:absolute;z-index:9999;top:-316px;left:97px;"><object width="410" height="257"><param name="movie" value="http://www.youtube.com/v/Zbs5QOlNgxY&hl=it_IT&fs=1&"></param><param name="autoplay" value="true"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/Zbs5QOlNgxY&hl=it_IT&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="410" height="257"></embed></object>');
			$('a.media').media();
			$(fullImageArea).unbind('click');
			// <a class="media {width:450, height:380, type:'swf'}" href="http://youtube.com/v/TyvN59L4hJU">Youtube Video (SWF)</a> 
			//$('a.media').media();
		}
		
      }
	  
	  
      $(fullImageArea).bind("dblclick",function() {
        //startShow();
      });
      $(thumbBox).mouseover(function() {
        clearTimeout(hideTumb);
        clearTimeout(headerMO);
        $(header).find("td").css({opacity:opt.headerOpacity, background: opt.labelColor});
        clearTimeout(closeThumbStrip);
      });

      $(thumbBox).mouseout(function() {
        headerMO=setTimeout(function(){
          $(header).find("td").css({opacity:opt.headerOpacity, background: opt.labelColor});
        },100);
        hideTumb = setTimeout(function() {
          $(thumbImages).hide(opt.fadeTime);
          thumbOpen = false;
        }, opt.fadeTime*2);
      });
      $(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);
      });
      $(close).click( function() {
        myGallery.fadeOut("slow");
      });

      actualImg = full [opt.startFrom];
      $(thumbs).css(thumbUnsel);
      actualThumb = thumbs [opt.startFrom];
      $(actualThumb).css(thumbSel);
      closeThumbStrip = setTimeout(function() {
        $(thumbImages).hide(opt.fadeTime);
      }, opt.fadeTime*2);
	  
      var slideShowTimer, x = opt.startFrom, startSlide = opt.autoSlide, startShow = function() {
        //$(slideShow).find("img").attr("src", opt.iconFolder+"/stop.gif");
		$(slideShow).html("Pause");
        if(x == full.length)
          x = 0;
        preloadImg(x);
        slideShowTimer = setTimeout(startShow, opt.slideTimer);
        x ++;
      };
      function stopShow() {
        clearTimeout(slideShowTimer);
        //$(slideShow).find("img").attr("src", opt.iconFolder+"/play.gif");
		$(slideShow).html("Play");
        startSlide = false;
      }
	  
	  function fixThumbClose(){
		  
	  	 thumbOpen = false;
		 $(thumbImages).show(opt.fadeTime);
		/*thumbOpen = true;*/
	  }
	  
      /*if(startSlide) {
		$(thumbImages).hide();
	    setTimeout(fixThumbClose, opt.startTimer);
        //setTimeout(startShow, opt.startTimer);
      } else {
        setTimeout(function() {
          preloadImg(opt.startFrom);
        }, opt.startTimer);
      }*/
	  
	  if(startSlide) {
		fixThumbClose();
		//$(thumbImages).hide();
		//thumbOpen = false;
	    //setTimeout(fixThumbClose, opt.startTimer);
        startShow();
      } else {
        setTimeout(function() {
          preloadImg(opt.startFrom);
        }, opt.startTimer);
      }
	  
	  /*$(thumbImages).hide();
	  thumbOpen = false;
      setTimeout(function() {
         preloadImg(opt.startFrom);
      }, opt.startTimer);
		*/
      //setTimeout(fixThumbClose, opt.startTimer);
	  
    });
  };
})(jQuery);
