/**
 * jQuery sBox plugin
 * This jQuery plugin was inspired and based on sBox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/sBox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-sBox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CCAttribution-ShareAlike 2.5 Brazil - http://creativecommons.org/licenses/by-sa/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/sBox/ for more informations about this jQuery plugin
 */

// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
(function($) {
	/**
	 * $ is an alias to jQuery object
	 *
	 */
	$.fn.sBox = function(config) {
		// Settings to configure the jQuery sBox plugin how you like
		var settings=$.extend({
			// Configuration related to overlay
			overlayBgColor: 		'#000',		// (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
			overlayOpacity:			0.8,		// (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
			// Configuration related to navigation
			fixedNavigation:		false,		// (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
			// Configuration related to images
			imageLoading:			'images/sBox-ico-loading.gif',		// (string) Path and the name of the loading icon
			imageBtnPrev:			'images/sBox-btn-prev.gif',			// (string) Path and the name of the prev button image
			imageBtnNext:			'images/sBox-btn-next.gif',			// (string) Path and the name of the next button image
			imageBtnClose:			'images/sBox-btn-close.gif',		// (string) Path and the name of the close btn
			imageBlank:				'images/sBox-blank.gif',			// (string) Path and the name of a blank image (one pixel)
			// Configuration related to container image box
			containerBorderSize:	10,			// (integer) If you adjust the padding in the CSS for the container, #sBox-container-image-box, you will need to update this value
			containerResizeSpeed:	400,		// (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
			// Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
			txtImage:				'Image',	// (string) Specify text "Image"
			txtOf:					'of',		// (string) Specify text "of"
			
			// Don´t alter these variables in any way
			imageArray:				[],
			activeImage:			0},config);
		// Caching the jQuery object with all elements matched
		var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
		/**
		 * Initializing the plugin calling the start function
		 *
		 * @return boolean false
		 */
		function _initialize() {
			_start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
			return false; // Avoid the browser following the link
		}
		/**
		 * Start the jQuery sBox plugin
		 *
		 * @param object objClicked The object (link) whick the user have clicked
		 * @param object jQueryMatchedObj The jQuery object with all elements matched
		 */
		function _start(objClicked,jQueryMatchedObj) {
  // visual fb
      $("#controller .sBoxControl").removeClass("sBoxSelected");
      $(objClicked).addClass("sBoxSelected");
      
			// Unset total images in imageArray
			settings.imageArray.length = 0;
			// Unset image active information
			settings.activeImage = 0;
			// We have an image set? Or just an image? Let´s see it.
			if ( jQueryMatchedObj.length == 1 ) {
				settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
			} else {
				// Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references		
				for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
					settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));
				}
			}
			while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
				settings.activeImage++;
			}
			// Call the function that prepares image exibition
			_set_image_to_view();
		}
		
		/**
		 * Prepares image exibition; doing a image´s preloader to calculate it´s size
		 *
		 */
		 var swtch,s_t_h;
		function _set_image_to_view() {
		  s_t_h=(swtch!="-load")?"":"-load";
      swtch=(swtch=="-load")?"":"-load";
			// Show the loading
			$('#sBox-loading').show();

			$('#sBox-label').hide();
			// Image preload process
			var objImagePreloader = new Image();
			objImagePreloader.onload = function() {
				$('#sBox-image'+swtch).attr('src',settings.imageArray[settings.activeImage][0]);
				
        _show_image();
				//	clear onLoad, IE behaves irratically with animated gifs otherwise
				objImagePreloader.onload=function(){};
			};
			objImagePreloader.src = settings.imageArray[settings.activeImage][0];
		};
		
		/**
		 * Show the prepared image
		 *
		 */
		function _show_image() {
			$('#sBox-loading').hide();
			
      //$('#sBox-image'+s_t_h).hide();
      if(swtch=="-load"){
        $('#sBox-image'+swtch).fadeIn(function() {
  				_show_image_data();
  			});
			}else{
        $('#sBox-image'+s_t_h).fadeOut(function() {
  				_show_image_data();
  			});
			}
			_preload_neighbor_images();
		};
		/**
		 * Show the image information
		 *
		 */
		function _show_image_data() {
			//$('#sBox-container-image-data-box').slideDown('fast');
				
			$('#sBox-label').html(settings.imageArray[settings.activeImage][1]).show();
      //$('#sBox-label').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
				
		}
		/**
		 * Preload prev and next images being showed
		 *
		 */
		function _preload_neighbor_images() {
			if ( (settings.imageArray.length -1) > settings.activeImage ) {
				objNext = new Image();
				objNext.src = settings.imageArray[settings.activeImage + 1][0];
			}
			if ( settings.activeImage > 0 ) {
				objPrev = new Image();
				objPrev.src = settings.imageArray[settings.activeImage -1][0];
			}
		}
		
		function _prepara() {	
    
      var maskHide;
      var F=0;
      var B=$(".sBoxControl").length;
      
      $(settings.slides).append('<img alt="" id="sBox-image-load" style="display:none;position:absolute;z-index:2000"/>');
    	
      if(settings.mask){
        $(settings.slides).append('<div id="maskslide"></div>');	
        $('#maskslide').css({ 'width' : settings.width, 'height' : settings.height, 'opacity' : settings.maskOpacity, 'background-color' : settings.mask});
        
        $('#controller').mouseover(function(){
          clearTimeout(maskHide);
          $('#maskslide').fadeOut();
          $('#sBox-label').fadeIn();
        });
  
        $('#controller').mouseout(function(){
          maskHide=setTimeout("$('#sBox-label').hide();$('#maskslide').fadeIn();",3000);
          
        });	
      }
      
      $('#sBox-label').html(jQueryMatchedObj[0].getAttribute('title'));
			$('#sBox-loading').hide();
      /*
    
      $(".sBoxPrev").click(function(){
        if(F>0){F--}else{F=B-1}
        _set_image_to_view(F);
      });
      $(".sBoxNext").click(function(){
        if(F<B-1){F++}else{F=0}
        _set_image_to_view(F);
      });*/
		}
		
		_prepara();
		// Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
		return this.unbind('click').click(_initialize);
	};
})(jQuery); // Call and execute the function immediately passing the jQuery object
