/**
 * Interface Elements for jQuery
 * ImageBox
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Revision$
 *
 */

(function($) {

$.defineTag = function( tag ) {
    $[tag.toUpperCase()] = function() {
        return $._createNode( tag, arguments );
    }
};

(function() {
    var tags = [
        'a', 'br', 'button', 'canvas', 'div', 'fieldset', 'form',
        'h1', 'h2', 'h3', 'hr', 'img', 'input', 'iframe', 'label', 'legend',
        'li', 'ol', 'optgroup', 'option', 'p', 'pre', 'select',
        'span', 'strong', 'table', 'tbody', 'td', 'textarea',
        'tfoot', 'th', 'thead', 'tr', 'tt', 'ul' ];
    for( var i = tags.length - 1;  i >= 0;  i-- ) {
        $.defineTag( tags[i] );
    }
})();

$.NBSP = '\u00a0';

$._createNode = function( tag, args ) {
    var fix = { 'class':'className', 'Class':'className' };
    var e;
    try {
        var attrs = args[0] || {};
        e = document.createElement( tag );
        for( var attr in attrs ) {
            var a = fix[attr] || attr;
            e[a] = attrs[attr];
        }
        for( var i = 1;  i < args.length;  i++ ) {
            var arg = args[i];
            if( arg == null ) continue;
            if( arg.constructor != Array ) jQuery(e).append( arg );
            else for( var j = 0;  j < arg.length;  j++ )
                if(arg != null) jQuery(e).append( arg[j] );
        }
    }
    catch( ex ) {
        alert( 'Cannot create <' + tag + '> element:\n' +
            args.toSource() + '\n' + args );
        e = null;
    }

    return e;
};

jQuery.ImageBox = {
options : {
border: 10,
loaderSRC: '/images/imagebox/loading.gif',
closeHTML: '<img src="/images/imagebox/close.jpg" />',
overlayOpacity: 0.8,
textImage: 'Showing image',
textImageFrom: 'of',
fadeDuration: 400
},
imageLoaded : false,
firstResize: false,

denit: function() {
  jQuery("a[@rel^=imagebox]").unbind("click");
  jQuery("#ImageBoxOverlay, #ImageBoxIframe, #ImageBoxOuterContainer").remove();  
},

init: function(options)
{
if (options)
jQuery.extend(jQuery.ImageBox.options, options);
jQuery('a[@rel^=imagebox]').click(jQuery.ImageBox.start);
    if (jQuery.browser.msie) {
      iframe = jQuery($.IFRAME({id: 'ImageBoxIframe', src: 'javascript:false', frameborder: 'no', scrolling: 'no'}))
        .css (
          {
            display: 'none',
            position: 'absolute',
            top: '0',
            left: '0',
            width: '100%',
            filter: 'progid:DXImageTransform.Microsoft.Alpha(opacity=0)'
          }
        );
      jQuery('body').append(iframe);
    }

    overlay = jQuery($.DIV({id: 'ImageBoxOverlay'}, ' '))
      .click(jQuery.ImageBox.hideImage)[0];

    captionText = jQuery($.DIV({id: 'ImageBoxCaptionText'}, ' '))
      .css({ paddingLeft: jQuery.ImageBox.options.border + 'px' })[0];

    captionImages = jQuery($.DIV({id: 'ImageBoxCaptionImages'}, ' '))
      .css(
        {
          paddingLeft: jQuery.ImageBox.options.border + 'px',
          paddingBottom: jQuery.ImageBox.options.border + 'px'
        }
      )[0];

    closeEl = jQuery($.A({id: 'ImageBoxClose', href: '#'}, jQuery.ImageBox.options.closeHTML))
      .click(jQuery.ImageBox.hideImage)[0];

    captionEl = $.DIV({id: 'ImageBoxCaption'}, captionText, captionImages, closeEl);

    loader = jQuery($.IMG({id: 'ImageBoxLoader', src: jQuery.ImageBox.options.loaderSRC}))
      .css({position: 'absolute'})[0];

    prevImage = $.A({id: 'ImageBoxPrevImage', href: '#'}, ' ');

    nextImage = $.A({id: 'ImageBoxNextImage', href: '#'}, ' ');

    container = $.DIV({id: 'ImageBoxContainer'}, loader, prevImage, nextImage);

    outerContainer = $.DIV({id: 'ImageBoxOuterContainer'}, container, captionEl);
      
    jQuery('body').append(overlay).append(outerContainer);
    
    jQuery("#ImageBoxOuterContainer").click(function(e) { 
      if(e.target == this) jQuery.ImageBox.hideImage();
      return false;
      e.stopPropagation();  
    });    
  },

  start: function(e, elm)
  {
    jQuery.ImageBox.cancelled = false;
    jQuery("body, html").css("overflow", "hidden");
    el = elm ? jQuery(elm): jQuery(this);
    linkRel =  el.attr('rel');
    if (linkRel != 'imagebox') {
      gallery = jQuery('a[@rel=' + linkRel + ']');
      totalImages = gallery.size();
      iteration = gallery.index(elm ? elm: this);
      prevImage = gallery.get(iteration - 1);
      nextImage = gallery.get(iteration + 1);
    }
    imageSrc =  el.attr('href');
    captionText = el.attr('title');
    pageSize = jQuery.iUtil.getScroll();
    overlay = jQuery('#ImageBoxOverlay')
    if (overlay.css('display') == 'none') {
      if (jQuery.browser.msie) {
        jQuery('#ImageBoxIframe')
          .css ('height', pageSize.ih + 'px')
          .show();
      }
      overlay.css("height", pageSize.ih + (!jQuery.browser.msie ? "px" : 0))
        .css("top", pageSize.t + (!jQuery.browser.msie ? "px" : 0))
        .show()
        .fadeTo(
          300,
          jQuery.ImageBox.options.overlayOpacity,
          jQuery.ImageBox.loadThisImage
        );
    } else {
      jQuery('#ImageBoxPrevImage').unbind("click");
      jQuery('#ImageBoxNextImage').unbind("click");
      jQuery.ImageBox.loadThisImage();
    }
    return false;
  },

  loadThisImage: function() {
    if(jQuery.ImageBox.cancelled) return;    
    jQuery.ImageBox.loadImage(
      imageSrc,
      captionText,
      pageSize,
      totalImages,
      iteration,
      prevImage,
      nextImage)
  },

  loadImage: function(imageSrc, captiontext, pageSize, totalImages, iteration, prevImage, nextImage)
  {
    jQuery('#ImageBoxCurrentImage').remove();
    prevImageEl = jQuery('#ImageBoxPrevImage').hide();
    nextImageEl = jQuery('#ImageBoxNextImage').hide();
    loader = jQuery('#ImageBoxLoader');
    container = jQuery('#ImageBoxContainer');
    outerContainer = jQuery('#ImageBoxOuterContainer');
    captionEl = jQuery('#ImageBoxCaption').hide();
    jQuery('#ImageBoxCaptionText').html(captionText);
    if (totalImages)
      jQuery('#ImageBoxCaptionImages').html(
        jQuery.ImageBox.options.textImage
        + ' ' + (iteration + 1) + ' '
        + jQuery.ImageBox.options.textImageFrom
        + ' ' + totalImages
      );
    if (prevImage) {
      prevImageEl.get(0).onclick = function()
      {
        this.blur();
        jQuery.ImageBox.start(null, prevImage);
        return false;
      };
    }
    if (nextImage) {
      nextImageEl[0].onclick =function()
      {
        this.blur();
        jQuery.ImageBox.start(null, nextImage);
        return false;
      };
    }
    if(jQuery.ImageBox.cancelled) return;    
    loader.show();
    containerSize = jQuery.iUtil.getSize(container[0]);
    containerW = Math.min(Math.max(containerSize.wb, loader[0].width + jQuery.ImageBox.options.border * 2), pageSize.iw * .7);
    containerH = Math.min(Math.max(containerSize.hb, loader[0].height + jQuery.ImageBox.options.border * 2), pageSize.ih * .7);
    loader
      .css(
        {
          left: (pageSize.iw - loader[0].width)/2 + 'px',
          top: (pageSize.ih - loader[0].height)/2 + pageSize.t + 'px'
        }
      );
    container
      .css(
        {
          width: containerW + 'px',
          height: containerH + 'px'
        }
      )
      .show();
    clientSize = jQuery.iUtil.getClient();
    outerContainer
      .css('top', pageSize.t +  (clientSize.h / 15) + 'px');
    if (outerContainer.css('display') == 'none') {
      outerContainer
        .show()
        .fadeIn(
          jQuery.ImageBox.options.fadeDuration
        );
    }
    imageEl = jQuery($.IMG({id: 'ImageBoxCurrentImage'}))
      .load(
      function()
      {
        this.style.width = Math.min(parseInt(this.width), pageSize.iw * 0.7) + "px";
        var h = (parseInt(this.style.width) / this.width) * this.height;
        if(pageSize.ih * 0.7 < h) {
          h = (pageSize.ih * 0.7) - (jQuery.ImageBox.options.border * 2);
          var w = (h / this.height) * this.width;
          this.style.width = w + "px"
        }
        this.style.height = h + "px";
        containerW = parseInt(parseInt(this.style.width)) + (jQuery.ImageBox.options.border * 2);
        containerH = h + (jQuery.ImageBox.options.border * 2);
        loader.hide();
        outerContainer.animate({top: (pageSize.ih - containerH) / 2 + pageSize.t});
        container.animate(
          {
            height: containerH - jQuery.ImageBox.options.border
          },
          containerSize.hb != containerH ? jQuery.ImageBox.options.fadeDuration: 1,
          function()
          {
            container.animate(
              {
                width: containerW
              },
              containerSize.wb != containerW ? jQuery.ImageBox.options.fadeDuration: 1,
              function()
              {
                container.prepend(imageEl);
                jQuery(imageEl)
                  .css(
                    {
                      position: 'absolute',
                      left: jQuery.ImageBox.options.border + 'px',
                      top: jQuery.ImageBox.options.border + 'px'
                    }
                  )
                  .fadeIn(
                    jQuery.ImageBox.options.fadeDuration,
                    function()
                    {
                      captionSize = jQuery.iUtil.getSize(captionEl.get(0));
                      if (prevImage) {
                        prevImageEl
                          .css(
                            {
                              left: jQuery.ImageBox.options.border + 'px',
                              top: jQuery.ImageBox.options.border + 'px',
                              width: containerW/2 - jQuery.ImageBox.options.border * 3 + 'px',
                              height: containerH - jQuery.ImageBox.options.border * 2 + 'px'
                            }
                          )
                          .fadeIn("fast");
                      }
                      if (nextImage) {
                        nextImageEl
                          .css(
                            {
                              left: containerW/2 + jQuery.ImageBox.options.border * 2 + 'px',
                              top: jQuery.ImageBox.options.border + 'px',
                              width: containerW/2 - jQuery.ImageBox.options.border * 3 + 'px',
                              height: containerH - jQuery.ImageBox.options.border * 2 + 'px'
                            }
                          )
                          .fadeIn("fast");
                      }
                      captionEl
                        .css(
                          {
                            width: containerW + 'px',
                            opacity: 0.5,
                            top: - captionSize.hb + 'px'
                          }
                        )
                        .show()
                        .animate(
                          {
                            opacity: 1,
                            top: 1
                          },
                          jQuery.ImageBox.options.fadeDuration
                        );
                    }
                  );
                  if(jQuery.ImageBox.cancelled) jQuery.ImageBox.hideImage();
              }
            );
          }
        );
      }
    )[0];
    imageEl.src = imageSrc;
  },

  hideImage: function()
  {
    jQuery.ImageBox.cancelled = true;
    jQuery('#ImageBoxCurrentImage').remove();
    jQuery('#ImageBoxOuterContainer').hide();
    jQuery('#ImageBoxCaption').hide();
    jQuery('#ImageBoxOverlay').fadeTo(
      300,
      0,
      function(){
        jQuery(this).hide();
        if (jQuery.browser.msie) {
          jQuery('#ImageBoxIframe').hide();
        }
      }
    );
    jQuery('#ImageBoxPrevImage').unbind("click");
    jQuery('#ImageBoxNextImage').unbind("click");
    jQuery("body, html").css("overflow", "auto");
    return false;
  }
}

})(jQuery);