/*
 * FlexBox 0.1
 * By Andreas Tetzl (http://www.tetzl.de)
 * Copyright (c) 2008 Andreas Tetzl
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Based on:
 * http://www.learningjquery.com/2007/10/a-plugin-development-pattern
*/

/*
TODO:

Loading-Animation besser positionieren
Andere Galerie-Bilder vorladen
Wenn Caption oben ist, wird der Close-Button vom Next-Link verdeckt.
Div besser positionieren, wenn Fenster zu klein ist.


*/


//
// create closure
//
(function($) {

  // plugin definition
  $.fn.flexBox = function(options) {
    options = jQuery.extend({
          caption:           "top", // [top|right] position of caption
          captionWidth:      240, // width of right text box, 0 to disable
          overlayColor:      "#000",
          overlayOpacity:    0.7,

          // texts
          textImage:      'Image', // Image x of n
          textOf:       'of',    // Image x of n
          textClose:         'close', // close button
          textPrev:          'Prev',  // prev button
          textNext:          'Next',  // next button

          // internal
          currentImage:      0,
          imageLinks:        []
    }, options);
  // Cache jQuery object with all elements matched
    var jQueryMatches = this;

    // assign click event to image link
    return this.unbind('click').click(init);

    /**
     * called when image link is clicked
     */
    function init() {
      // this -> clicked image link
      for (var i=0; i<jQueryMatches.length; i++) {
        options.imageLinks.push(jQueryMatches[i]);
        if (jQueryMatches[i]==this) {
          options.currentImage=i;
        }
      }

      build();
      show();

      return false;
    }


    // private function for debugging
    function debug($obj) {
      if (window.console && window.console.log)
        window.console.log('hilight selection count: ' + $obj.size());
    };

    function build() {
      var html='\
  <div id="flexbox-container" class="'+options.caption+'">\
    <div id="flexbox-caption">\
      <div id="flexbox-count"></div>\
      <div id="flexbox-caption-text"></div>\
    </div>\
    <img id="flexbox-image" src="about:blank" />\
    <a id="flexbox-prev" href="#" onclick="this.blur();">'+options.textPrev+'</a>\
    <a id="flexbox-next" href="#" onclick="this.blur();">'+options.textNext+'</a>\
    <a href="#" id="flexbox-close">'+options.textClose+'</a>\
  </div>\
  ';
      var flexBox=$(html);

      if (options.caption=="top") {
        options.captionWidth=0;
      } else {
        // rechts
        $("#flexbox-caption", flexBox).css("width", options.captionWidth+"px");
        $("#flexbox-count", flexBox).hide().css("width", options.captionWidth+"px");
      }

      $("#flexbox-next", flexBox).css("right", options.captionWidth+(options.caption=="right"?20:10)+"px");


      $("#flexbox-close", flexBox).hide().click(close);

      var screenWidth=$(window).width();
      var screenHeight=$(window).height();
      flexBox.css("width", "60px").css("height", "60px")
             .css("left", parseInt(screenWidth/2-30)+"px").css("top", parseInt(screenHeight/2-30)+"px");

      $("#flexbox-prev", flexBox).click(showPrev);
      $("#flexbox-next", flexBox).click(showNext);

      // overlay
      var overlay=$('<div id="flexbox-overlay"></div>');
      $(document.body).append(overlay);
      overlay.css({
          backgroundColor:  options.overlayColor,
          opacity:      options.overlayOpacity,
          width:      screenWidth,
          height:     $(document).height(),
          top:        0
      }).show();

      $(document.body).append(flexBox);

    }

    function show() {
      var link=options.imageLinks[options.currentImage];


      var text=$('#'+link.id+'-text').html();
      if (text) {
        $('#flexbox-caption-text').html(text);
      } else {
        var title=link.getAttribute("title");
        $('#flexbox-caption-text').html(title);
      }

      if (jQueryMatches.length>1) {
        // Image 2 of 3
        $("#flexbox-count").html(options.textImage+" "+(options.currentImage+1)+" "+options.textOf+" "+jQueryMatches.length);
      }



      $('#flexbox-image').attr("src", "loading.gif");
      $('#flexbox-image').show();
      $("#flexbox-container").show();

      var preLoader = new Image();
      preLoader.onload = function() {
        $('#flexbox-image').attr("src", link.href);


        if (jQueryMatches.length>1) {
          if (options.currentImage>0) {
            /*
            $("#flexbox-prev").show().mouseover(function() {
              $("#flexbox-prev").fadeIn(300);
            }).mouseout(function() {
              $("#flexbox-prev").fadeOut(300);
            });*/
            $("#flexbox-prev").show();
          } else {
            $("#flexbox-prev").hide();
          }

          if (options.currentImage<jQueryMatches.length-1) {
            /*
            $("#flexbox-next").show().mouseover(function() {
              $("#flexbox-next").fadeIn(300);
            }).mouseout(function() {
              $("#flexbox-next").fadeOut(300);
            });
            */
            $("#flexbox-next").show();
          } else {
            $("#flexbox-next").hide();
          }
        } else {
          $("#flexbox-prev").hide();
          $("#flexbox-next").hide();
        }

        resize(preLoader.width, preLoader.height)
        //  clear onload
        preLoader.onload=function(){};
      };
      preLoader.src = link.href;
    }

    function showNext() {
      options.currentImage++;
      show();
      return false;
    }

    function showPrev() {
       options.currentImage--;
       show();
       return false;
    }

    function resize(width, height) {
      var screenWidth=$(window).width();
      var screenHeight=$(window).height();

      var boxWidth=width + options.captionWidth + (options.caption=="right"?10:0);
      var boxHeight=height + (options.caption=="right"?0:30);
      var boxLeft=parseInt(screenWidth / 2 - boxWidth / 2);
      var scrollTop=$(window).scrollTop();
      var boxTop=parseInt(scrollTop + screenHeight / 2 - boxHeight / 2);

      if (boxTop<0) {
        boxTop=10;
      }

      $("#flexbox-image").hide();
      $("#flexbox-caption").hide();

      // position next link 40px down, so the close button remains clickable
      //$("#flexbox-next-link").css("top", "40px").css("height", (boxHeight-40)+"px");

      $("#flexbox-container").show();

      $("#flexbox-container").animate({
        left: boxLeft+"px",
        top: boxTop+"px",
        width: boxWidth+"px",
        height: boxHeight+"px"
      }, 500, function() {
        $("#flexbox-prev, #flexbox-next").css("height", boxHeight-(options.caption=="right"?0:30));
        $("#flexbox-image").fadeIn(300);
        $("#flexbox-caption").fadeIn(300);
        $("#flexbox-close").show();
        $("#flexbox-count").show();
      });

    }

    function close() {
      $("#flexbox-container").fadeOut(200, function() {
        $("#flexbox-container").remove();
        $("#flexbox-overlay").remove();
      });
      return false;
    }


  };


  // define and expose public function
  /**
   * activate flexbox on all links with rel="flexbox"
   * activate flexbox as gallery on all links with rel="flexbox[galleryid]"
   */
  $.fn.flexBox.init = function(options) {

    var galleries=new Array();

    var elements=$('a[rel]');
    for (var i=0; i<elements.length; i++) {
      var e=elements.eq(i);

      if (e.attr("rel")=="flexbox") {
        // single image
        e.flexBox(options);
      } else if (e.attr("rel").match(/^flexbox\[/) && galleries[e.attr("rel")]!=1) {
        // gallery
        $('a[rel="'+e.attr("rel")+'"]').flexBox(options);
        galleries[e.attr("rel")]=1;


      }
    }
  };

//
// end of closure
//
})(jQuery);

