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





(function(H){
  jQuery.fn.mbMaskGallery = function (options){
    return this.each (function ()
    {
      //var galleryId = !this.id ? "maskGallery"+Math.floor (Math.random () * 1000): this.id;
      var thisGallery = this;

      this.options = {
        galleryMask:"mask/monitor.png",
        galleryLoader:"loader/loader.gif",
        galleryColor:"white",
        type:"normal", //or "random"
        transition:"crossfade", // or "normal"
        fadeTime: 500,
        loader:true,
        loaderOpacity:.3,
        changeOnClick:false,
        navId:"",
        nextPath:"",
        prevPath:"",
        slideTimer: 2000
      };
      H.extend (this.options, options);

      var loader="<table id='loader' cellpadding='0' cellspacing='0' width='100%' height='100%'><tr><td valign='middle' align='center'><img src='"+this.options.galleryLoader+"' alt='loading'></td></tr></table>";

      // get the images
      var images = H (this).find ("img");
      H (thisGallery).empty ();

      var idx=(this.options.type =="random")?Math.floor(Math.random()*H(images).size()):0;


      // container
      H(thisGallery).append("<div class='container'></div>");
      var galleryContainer=H (this).find(".container");

      if (thisGallery.options.loader){
        // loader
        H(galleryContainer).append(loader);
        var galleryloader=H (thisGallery).find("#loader");
        H(galleryloader).css({
          position: "absolute",
          top: 0,
          left:0
        });
        if(!H.browser.msie) {
          H(galleryloader).css({
            opacity:thisGallery.options.loaderOpacity
          });
        }
      }

      //image
      H(galleryContainer).append("<div class='galleryImage'></div>");
      var galleryImage=H (thisGallery).find(".galleryImage");

      //mask
      H(galleryContainer).append("<image class='galleryMask' src='"+this.options.galleryMask+"'>");
      var galleryMask=H (thisGallery).find(".galleryMask");
      if (H.metadata){
        H.metadata.setType("class");
      }
      H(thisGallery).mouseover(
              function(){
                if (H.metadata){
                  H.metadata.setType("class");
                  if (H(images[idx]).metadata().url) H(images[idx]).attr("url",H(images[idx]).metadata().url);
                  if (H(images[idx]).metadata().script) H(images[idx]).attr("script",H(images[idx]).metadata().script);
                }

                H(this).css({
                  cursor: H(images[idx]).attr("url") || H(images[idx]).attr("script") ?"pointer":"default"
                });
              });

      H(galleryMask).click(
              function(){
                if (H(images[idx]).attr("url")) self.location.href=H(images[idx]).attr("url");
                if (H(images[idx]).attr("script")) eval(H(images[idx]).attr("script"));
              });

      H(galleryContainer).css({
        position:"relative",
        overflow:"hidden",
        opacity:0,
        backgroundColor: thisGallery.options.galleryColor
      });

      H(galleryImage).css({
        position: "relative",
        top: 0,
        left:0
      });

      H(galleryMask).css({
        position: "absolute",
        top: 0,
        left:0
      });

      var changePhoto = function (u){
        if (thisGallery.options.transition=="crossfade"){
          var actualImg=H(galleryImage).find("img");
          H(actualImg).removeClass("newImg");
          var newImg=H("<img class='newImg' src='"+u+"'>").css({
            position: "relative",
            top: 0,
            left:0,
			right:0,
            opacity:0,
			width:170 //HACK YDEO ligne rajoutée
          });
          H(galleryImage).append(newImg);
          H(newImg).fadeTo(thisGallery.options.fadeTime, 1, function(){
            H(actualImg).remove();
          });
        }else{
          H (galleryImage).fadeTo (thisGallery.options.fadeTime, 0, function (){
            //replacing the image
            H (galleryImage).find("img").remove();
            H (galleryImage).append("<img src='"+u+"'>");
            //showing the new image
            setTimeout (function ()
            {
              H (galleryImage).fadeTo (thisGallery.options.fadeTime, 1);
            }, (thisGallery.options.fadeTime/2));
          });
        }
      };



      function preloadImg(u){
        var o = new Image ();
        o.onload = function (){changePhoto (u);};
        o.onerror = function (){alert ("can't load " + u);};
//LIGNE D'origine remplacée par la suivante        o.src = u+"?rnd="+Math.floor (Math.random () * 1000);
		o.src = u;
      }

      function startGallery(){

        setTimeout(function(){
          preloadImg(H(images[idx]).attr("src"));
          H(galleryContainer).fadeTo (thisGallery.options.fadeTime, 1);
          if (!thisGallery.options.changeOnClick){
            if (H(images).size()>1){
              setInterval(function(){
                var rnd = Math.floor(Math.random()*H(images).size());
                idx= (thisGallery.options.type =="random")? rnd: ((idx>=H(images).size()-1)?0:idx+1);
                preloadImg(H(images[idx]).attr("src"));
              },thisGallery.options.slideTimer);
            }else{
              preloadImg(H(images[0]).attr("src"));
            }
          }else if (H(images).size()>1){

            var cont=thisGallery.options.navId!=""?H("#"+thisGallery.options.navId):"";
            if (thisGallery.options.changeOnClick && thisGallery.options.navId=="" ){
              H(thisGallery).append("<div class='cont'></div>");
              cont=H(thisGallery).find(".cont");
              cont.css({
                position:"relative",
                zIndex:10000,
                bottom:0,
                textAlign:"center",
                cursor:"pointer"
              }).html("<img class='prev' src='"+thisGallery.options.prevPath+"' alt='prev'>&nbsp;<img class='next' src='"+thisGallery.options.nextPath+"' alt='next'>");
            }
            if (thisGallery.options.navId!="" ){
              cont.css({
                width: H(galleryMask).width(),
                cursor:"pointer"
              });
            }

            var next= cont.find(".next");
            next.click(function(){
              var rnd = Math.floor(Math.random()*H(images).size());
              idx= (thisGallery.options.type =="random")? rnd: ((idx>=H(images).size()-1)?0:idx+1);
              preloadImg(H(images[idx]).attr("src"));
            });
            var prev= cont.find(".prev");
            prev.click(function(){
              var rnd = Math.floor(Math.random()*H(images).size());
              idx= (thisGallery.options.type =="random")? rnd:(idx<1?H(images).size()-1:idx-1);
              preloadImg(H(images[idx]).attr("src"));
            });
          }
          if(H.browser.msie && (H.browser.version.indexOf("6")>-1)) correctPNG();

        },200);
      }
      function loadMask(u){
        var o = new Image ();
        o.onload = function (){
          var w = thisGallery.options.galleryWidth ? thisGallery.options.galleryWidth : H(galleryMask).width();
          var h = thisGallery.options.galleryHeight ? thisGallery.options.galleryHeight : H(galleryMask).height();
          H(thisGallery).css({
            width: w,
            height: h
          });
          H(galleryContainer).css({
            width: w,
            height:h
          });
          startGallery();
        };
        o.onerror = function (){alert ("can't load mask: " + u);};
        o.src = u+"?rnd="+Math.floor (Math.random () * 1000);
      }

      function correctPNG() // correctly handle PNG transparency in Win IE 5.5 or higher.
      {
        for(var i=0; i<document.images.length; i++)
        {
          var img = document.images[i];
          var imgName = img.src.toUpperCase();
          if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
          {
            var imgID = (img.id) ? "id='" + img.id + "' " : "";
            var imgClass = (img.className) ? "class='" + img.className + "' " : "";
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
            var imgStyle = "display:inline-block;" + img.style.cssText;
            if (img.align == "left") imgStyle = "float:left;" + imgStyle;
            if (img.align == "right") imgStyle = "float:right;" + imgStyle;
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
            img.outerHTML = "<span " + imgID + imgClass + imgTitle
                    + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
                    + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                    + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
            i = i-1;
          }
        }
      }
      loadMask(this.options.galleryMask);
    });

  };
})(jQuery);