
// 'stacks' is the Stacks global object.
// All of the other Stacks related Javascript will 
// be attatched to it.
var stacks = {};


// this call to jQuery gives us access to the globaal
// jQuery object. 
// 'noConflict' removes the '$' variable.
// 'true' removes the 'jQuery' variable.
// removing these globals reduces conflicts with other 
// jQuery versions that might be running on this page.
stacks.jQuery = jQuery.noConflict(true);

// Javascript for stacks_in_666_page0
// ---------------------------------------------------------------------

// Each stack has its own object with its own namespace.  The name of
// that object is the same as the stack's id.
stacks.stacks_in_666_page0 = {};

// A closure is defined and assigned to the stack's object.  The object
// is also passed in as 'stack' which gives you a shorthand for referring
// to this object from elsewhere.
stacks.stacks_in_666_page0 = (function(stack) {

	// When jQuery is used it will be available as $ and jQuery but only
	// inside the closure.
	var jQuery = stacks.jQuery;
	var $ = jQuery;
	

                    
                    
                    
                    $(document).ready(function() {
                    



(function($) {

  $.fn.expander = function(options) {

    var opts = $.extend({}, $.fn.expander.defaults, options);
    var delayedCollapse;
    return this.each(function() {
      var $this = $(this);
      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
     	var cleanedTag, startTags, endTags;	
     	var allText = $this.html();
     	var startText = allText.slice(0, o.slicePoint).replace(/\w+$/,'');
     	startTags = startText.match(/<\w[^>]*>/g);
   	  if (startTags) {startText = allText.slice(0,o.slicePoint + startTags.join('').length).replace(/\w+$/,'');}
   	  
     	if (startText.lastIndexOf('<') > startText.lastIndexOf('>') ) {
     	  startText = startText.slice(0,startText.lastIndexOf('<'));
     	}
     	var endText = allText.slice(startText.length);    	  
     	// create necessary expand/collapse elements if they don't already exist
   	  if (!$('span.details', this).length) {
        // end script if text length isn't long enough.
       	if ( endText.replace(/\s+$/,'').split(' ').length < o.widow ) { return; }
       	// otherwise, continue...    
       	if (endText.indexOf('</') > -1) {
         	endTags = endText.match(/<(\/)?[^>]*>/g);
          for (var i=0; i < endTags.length; i++) {

            if (endTags[i].indexOf('</') > -1) {
              var startTag, startTagExists = false;
              for (var j=0; j < i; j++) {
                startTag = endTags[j].slice(0, endTags[j].indexOf(' ')).replace(/(\w)$/,'$1>');
                if (startTag == rSlash(endTags[i])) {
                  startTagExists = true;
                }
              }              
              if (!startTagExists) {
                startText = startText + endTags[i];
                var matched = false;
                for (var s=startTags.length - 1; s >= 0; s--) {
                  if (startTags[s].slice(0, startTags[s].indexOf(' ')).replace(/(\w)$/,'$1>') == rSlash(endTags[i]) 
                  && matched == false) {
                    cleanedTag = cleanedTag ? startTags[s] + cleanedTag : startTags[s];
                    matched = true;
                  }
                };
              }
            }
          }

          endText = cleanedTag && cleanedTag + endText || endText;
        }
     	  $this.html([
     		startText,
     		'<span class="read-more">',
     		o.expandPrefix,
       		'<a href="#">',
       		  o.expandText,
       		'</a>',
        '</span>',
     		'<span class="details">',
     		  endText,
     		'</span>'
     		].join('')
     	  );
      }
      var $thisDetails = $('span.details', this),
        $readMore = $('span.read-more', this);
   	  $thisDetails.hide();
 	    $readMore.find('a').click(function() {
 	      $readMore.hide();

 	      if (o.expandEffect === 'show' && !o.expandSpeed) {
          o.beforeExpand($this);
 	        $thisDetails.show();
          o.afterExpand($this);
          delayCollapse(o, $thisDetails);
 	      } else {
          o.beforeExpand($this);
 	        $thisDetails[o.expandEffect](o.expandSpeed, function() {
            $thisDetails.css({zoom: ''});
            o.afterExpand($this);
            delayCollapse(o, $thisDetails);
 	        });
 	      }
        return false;
 	    });
      if (o.userCollapse) {
        $this
        .find('span.details').append('<span class="re-collapse">' + o.userCollapsePrefix + '<a href="#">' + o.userCollapseText + '</a></span>');
        $this.find('span.re-collapse a').click(function() {

          clearTimeout(delayedCollapse);
          var $detailsCollapsed = $(this).parents('span.details');
          reCollapse($detailsCollapsed);
          o.onCollapse($this, true);
          return false;
        });
      }
    });
    function reCollapse(el) {
       el.hide()
        .prev('span.read-more').show();
    }
    function delayCollapse(option, $collapseEl) {
      if (option.collapseTimer) {
        delayedCollapse = setTimeout(function() {  
          reCollapse($collapseEl);
          option.onCollapse($collapseEl.parent(), false);
          },
          option.collapseTimer
        );
      }
    }
    function rSlash(rString) {
      return rString.replace(/\//,'');
    }    
  };
    // plugin defaults
    var length = 400;
                    // var minTrail = 10;
                    var moreText = "[Read More]";
                    var lessText = "[Close]";
                    var ellipsisText = "...";
                    var dooOpenSpeed = "";
                    var dooCloseSpeed = "";
                    
                    
  $.fn.expander.defaults = {
    slicePoint:       400,  // the number of characters at which the contents will be sliced into two parts. 
                            // Note: any tag names in the HTML that appear inside the sliced element before 
                            // the slicePoint will be counted along with the text characters.
    widow:            1,  // a threshold of sorts for whether to initially hide/collapse part of the element's contents. 
                          // If after slicing the contents in two there are fewer words in the second part than 
                          // the value set by widow, we won't bother hiding/collapsing anything.
    expandText:       "[Read More]", // text displayed in a link instead of the hidden part of the element. 
                                      // clicking this will expand/show the hidden/collapsed text
    expandPrefix:     "... ",
    collapseTimer:    0, // number of milliseconds after text has been expanded at which to collapse the text again
    expandEffect:     'fadeIn',
    expandSpeed:      'slow',   // speed in milliseconds of the animation effect for expanding the text
    userCollapse:     true, // allow the user to re-collapse the expanded text.
    userCollapseText: "[Close]",  // text to use for the link to re-collapse the text
    userCollapsePrefix: ' ',
    beforeExpand: function($thisEl) {},
    afterExpand: function($thisEl) {},
    onCollapse: function($thisEl, byUser) {}
  };
  
  $('#stacks_in_666_page0 .trunky').expander();

})(jQuery);
                    
                    
                    
                    
                    
                    
                    });
                    
                    
                    
                    
                    
                    
                      
	return stack;
})(stacks.stacks_in_666_page0);


// Javascript for stacks_in_144_page0
// ---------------------------------------------------------------------

// Each stack has its own object with its own namespace.  The name of
// that object is the same as the stack's id.
stacks.stacks_in_144_page0 = {};

// A closure is defined and assigned to the stack's object.  The object
// is also passed in as 'stack' which gives you a shorthand for referring
// to this object from elsewhere.
stacks.stacks_in_144_page0 = (function(stack) {

	// When jQuery is used it will be available as $ and jQuery but only
	// inside the closure.
	var jQuery = stacks.jQuery;
	var $ = jQuery;
	
                             
$(document).ready(function(){
            

$.fn.reverseOrder = function() {
	return this.each(function() {
		$(this).prependTo( $(this).parent() );
	});
};





            $('#stacks_in_144_page0 .listContainer').hover(function(){
					$(".sliderBox", this).stop().animate({top:'-60px'},{queue:false,duration:100});
				}, function() {
					$(".sliderBox", this).stop().animate({top:'0px'},{queue:false,duration:300});
                       
            });
                
                

               
               

       
});
            
     

 

	return stack;
})(stacks.stacks_in_144_page0);


// Javascript for stacks_in_573_page0
// ---------------------------------------------------------------------

// Each stack has its own object with its own namespace.  The name of
// that object is the same as the stack's id.
stacks.stacks_in_573_page0 = {};

// A closure is defined and assigned to the stack's object.  The object
// is also passed in as 'stack' which gives you a shorthand for referring
// to this object from elsewhere.
stacks.stacks_in_573_page0 = (function(stack) {

	// When jQuery is used it will be available as $ and jQuery but only
	// inside the closure.
	var jQuery = stacks.jQuery;
	var $ = jQuery;
	

  

  jQuery(document).ready(function($){

function findPlainTextExceptInLinks(element, substring, callback) {
    for (var childi= element.childNodes.length; childi-->0;) {
        var child= element.childNodes[childi];
        if (child.nodeType===1) {
            if (child.tagName.toLowerCase()!=='a')
                findPlainTextExceptInLinks(child, substring, callback);
        } else if (child.nodeType===3) {
            var index= child.data.length;
            while (true) {
                index= child.data.lastIndexOf(substring, index);
                if (index===-1)
                    break;
                callback.call(window, child, index)
            }
        }
    }
}

var substring= 'TeleportMe';
findPlainTextExceptInLinks(document.body, substring, function(node, index) {
    node.splitText(index+substring.length);
    var span= document.createElement('span');
    span.className = "teleportHere";
    span.appendChild(node.splitText(index));
    node.parentNode.insertBefore(span, node.nextSibling);
});


var injectionStack = $("#stacks_in_573_page0 .teleportMe").html();


$(".teleportHere").replaceWith(injectionStack);
$("#stacks_in_573_page0 .teleportMe").hide();

});
	return stack;
})(stacks.stacks_in_573_page0);


// Javascript for stacks_in_579_page0
// ---------------------------------------------------------------------

// Each stack has its own object with its own namespace.  The name of
// that object is the same as the stack's id.
stacks.stacks_in_579_page0 = {};

// A closure is defined and assigned to the stack's object.  The object
// is also passed in as 'stack' which gives you a shorthand for referring
// to this object from elsewhere.
stacks.stacks_in_579_page0 = (function(stack) {

	// When jQuery is used it will be available as $ and jQuery but only
	// inside the closure.
	var jQuery = stacks.jQuery;
	var $ = jQuery;
	
/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 *
 * RGBA support by Mehdi Kabab <http://pioupioum.fr>
 */

(function(jQuery){
    jQuery.extend(jQuery.support, {
        "rgba": supportsRGBA()
    });

    // We override the animation for all of these color styles
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
        jQuery.fx.step[attr] = function(fx){
            var tuples = [];
            if ( !fx.colorInit ) {
                fx.start = getColor( fx.elem, attr );
                fx.end = getRGB( fx.end );
                fx.alphavalue = {
                    start: 4 === fx.start.length,
                    end:   4 === fx.end.length
                };
                if ( !fx.alphavalue.start ) {
                    fx.start.push( 1 );
                }
                if ( !fx.alphavalue.end ) {
                    fx.end.push( 1 );
                }
                if ( jQuery.support.rgba &&
                     (!fx.alphavalue.start && fx.alphavalue.end) || // RGB => RGBA
                     (fx.alphavalue.start && fx.alphavalue.end)  || // RGBA => RGBA
                     (fx.alphavalue.start && !fx.alphavalue.end)    // RGBA => RGB
                ) {
                    fx.colorModel = 'rgba';
                } else {
                    fx.colorModel = 'rgb';
                }
                fx.colorInit = true;
            }

            tuples.push( Math.max(Math.min( parseInt( (fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0) ); // R
            tuples.push( Math.max(Math.min( parseInt( (fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0) ); // G
            tuples.push( Math.max(Math.min( parseInt( (fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0) ); // B

            if ( fx.colorModel == 'rgba' ) {
                // Alpha
                tuples.push( Math.max(Math.min( parseFloat((fx.pos * (fx.end[3] - fx.start[3])) + fx.start[3]), 1), 0).toFixed(2) );
            }

            fx.elem.style[attr] = fx.colorModel + "(" + tuples.join(",") + ")";
        };
    });

    // Color Conversion functions from highlightFade
    // By Blair Mitchelmore
    // http://jquery.offput.ca/highlightFade/

    // Parse strings looking for color tuples [255,255,255[,1]]
    function getRGB(color) {
        var result, ret,
            ralpha = '(?:,\\s*((?:1|0)(?:\\.0+)?|(?:0?\\.[0-9]+))\\s*)?\\)',
            rrgbdecimal = new RegExp( 'rgb(a)?\\(\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*,\\s*([0-9]{1,3})\\s*' + ralpha ),
            rrgbpercent = new RegExp( 'rgb(a)?\\(\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*,\\s*([0-9]+(?:\\.[0-9]+)?)\\%\\s*' + ralpha );

        // Check if we're already dealing with an array of colors
        if ( color && color.constructor == Array && color.length >= 3 && color.length <= 4 ) {
            return color;
        }

        // Look for #a0b1c2
        if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) {
            return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
        }

        // Look for #fff
        if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) {
            return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
        }

        // Look for rgb[a](num,num,num[,num])
        if (result = rrgbdecimal.exec(color)) {
            ret = [parseInt(result[2]), parseInt(result[3]), parseInt(result[4])];
            // is rgba?
            if (result[1] && result[5]) {
                ret.push(parseFloat(result[5]));
            }

            return ret;
        }

        // Look for rgb[a](num%,num%,num%[,num])
        if (result = rrgbpercent.exec(color)) {
            ret = [parseFloat(result[2]) * 2.55, parseFloat(result[3]) * 2.55, parseFloat(result[4]) * 2.55];
            // is rgba?
            if (result[1] && result[5]) {
                ret.push(parseFloat(result[5]));
            }

            return ret;
        }

        // Otherwise, we're most likely dealing with a named color
        return colors[jQuery.trim(color).toLowerCase()];
    }

    function getColor(elem, attr) {
        var color;

        do {
            color = jQuery.curCSS(elem, attr);

            // Keep going until we find an element that has color, or we hit the body
            if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
                break;

            attr = "backgroundColor";
        } while ( elem = elem.parentNode );

        return getRGB(color);
    };

    function supportsRGBA() {
        var $script = jQuery('script:first'),
            color = $script.css('color'),
            result = false;
        if (/^rgba/.test(color)) {
                result = true;
        } else {
            try {
                result = ( color != $script.css('color', 'rgba(0, 0, 0, 0.5)').css('color') );
                $script.css('color', color);
            } catch (e) {};
        }

        return result;
    };

    // Some named colors to work with
    // From Interface by Stefan Petre
    // http://interface.eyecon.ro/

    var colors = {
        aqua:[0,255,255],
        azure:[240,255,255],
        beige:[245,245,220],
        black:[0,0,0],
        blue:[0,0,255],
        brown:[165,42,42],
        cyan:[0,255,255],
        darkblue:[0,0,139],
        darkcyan:[0,139,139],
        darkgrey:[169,169,169],
        darkgreen:[0,100,0],
        darkkhaki:[189,183,107],
        darkmagenta:[139,0,139],
        darkolivegreen:[85,107,47],
        darkorange:[255,140,0],
        darkorchid:[153,50,204],
        darkred:[139,0,0],
        darksalmon:[233,150,122],
        darkviolet:[148,0,211],
        fuchsia:[255,0,255],
        gold:[255,215,0],
        green:[0,128,0],
        indigo:[75,0,130],
        khaki:[240,230,140],
        lightblue:[173,216,230],
        lightcyan:[224,255,255],
        lightgreen:[144,238,144],
        lightgrey:[211,211,211],
        lightpink:[255,182,193],
        lightyellow:[255,255,224],
        lime:[0,255,0],
        magenta:[255,0,255],
        maroon:[128,0,0],
        navy:[0,0,128],
        olive:[128,128,0],
        orange:[255,165,0],
        pink:[255,192,203],
        purple:[128,0,128],
        violet:[128,0,128],
        red:[255,0,0],
        silver:[192,192,192],
        white:[255,255,255],
        yellow:[255,255,0],
        transparent: ( jQuery.support.rgba ) ? [0,0,0,0] : [255,255,255]
    };

})(jQuery);

function HexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function HexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function HexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}
function opaHex(o) {
	var i = Math.floor(0.5 * 255);
	return i.toString(16);
	
}

$(document).ready(function(){
	$('#stacks_in_579_page0 .transbox').css('background','rgb('+HexToR('C3C3C3')+', '+HexToG('C3C3C3')+', '+HexToB('C3C3C3')+')');
	$('#stacks_in_579_page0 .transbox').css('background','rgba('+HexToR('C3C3C3')+', '+HexToG('C3C3C3')+', '+HexToB('C3C3C3')+', 0.5)');  
	if ( $.browser.msie && parseInt($.browser.version, 10) < 9) {
		var ho = opaHex(0.5);
		$('#stacks_in_579_page0 .transbox').css('filter', 'progid:DXImageTransform.Microsoft.gradient(startColorstr=#'+ho+'C3C3C3, endColorstr=#'+ho+'C3C3C3)');  
		$('#stacks_in_579_page0 .transbox').css('-ms-filter', 'progid:DXImageTransform.Microsoft.gradient(startColorstr=#'+ho+'C3C3C3, endColorstr=#'+ho+'C3C3C3)');
	}
	if(false){
		$('#stacks_in_579_page0 .transbox').addClass('shadow');
	}

	if(true){
		$('#stacks_in_579_page0 .transbox').mouseenter(function(){
			$(this).animate({ "backgroundColor": 'rgba('+HexToR('C3C3C3')+', '+HexToG('C3C3C3')+', '+HexToB('C3C3C3')+', 1.0)' }, 250);
			if(false){
				$(this).addClass('shadow');
			}
			else{
				$(this).removeClass('shadow');
			}
		});
	
		$('#stacks_in_579_page0 .transbox').mouseleave(function(){
			$(this).animate({ "backgroundColor": 'rgba('+HexToR('C3C3C3')+', '+HexToG('C3C3C3')+', '+HexToB('C3C3C3')+', 0.5)' }, 250);
			if ( $.browser.msie && parseInt($.browser.version, 10) < 9) {
				$(this).css('filter', 'progid:DXImageTransform.Microsoft.gradient(startColorstr=#'+opaHex(0.5)+'C3C3C3, endColorstr=#88C3C3C3)');  
				$(this).css('-ms-filter', 'progid:DXImageTransform.Microsoft.gradient(startColorstr=#'+opaHex(0.5)+'C3C3C3, endColorstr=#88C3C3C3)');
			}
			if(false){
				$(this).addClass('shadow');
			}
			else{
				$(this).removeClass('shadow');
			}			
		});
	}
	
});
	return stack;
})(stacks.stacks_in_579_page0);


// Javascript for stacks_in_577_page0
// ---------------------------------------------------------------------

// Each stack has its own object with its own namespace.  The name of
// that object is the same as the stack's id.
stacks.stacks_in_577_page0 = {};

// A closure is defined and assigned to the stack's object.  The object
// is also passed in as 'stack' which gives you a shorthand for referring
// to this object from elsewhere.
stacks.stacks_in_577_page0 = (function(stack) {

	// When jQuery is used it will be available as $ and jQuery but only
	// inside the closure.
	var jQuery = stacks.jQuery;
	var $ = jQuery;
	

//-- Fancy Image Zoom Stack v2.1.3 by Joe Workman --//
(function($) {
	$.fn.shadowEnable  = function() { return $(this).find("+ .fx-shadow").show().end();   };
	$.fn.shadowDisable = function() { return $(this).find("+ .fx-shadow").hide().end();   };
	$.fn.shadowDestroy = function() { return $(this).find("+ .fx-shadow").remove().end(); };
	
	$.fn.shadow = function(options) {
		options = $.extend({
			offset:  1,
			opacity: 0.2,
			color:   "#000",
			monitor: false
		}, options || {});
		options.offset -= 1;
		
		return this.each(function() {
			
			// Remove an existing shadow if it exists
			var $element = $(this).shadowDestroy(),
			
			// Create a shadow element
			$shadow = $("<div class='fx-shadow' style='position: relative;'></div>").hide().insertAfter($element);
			
			// Figure the base height and width
			baseWidth  = $element.outerWidth(),
			baseHeight = $element.outerHeight(),
			
			// Get the offset
			position = $element.position(),
			
			// Get z-index
			zIndex = parseInt($element.css("zIndex")) || 0;
			
			// Append smooth corners
			$('<div class="fx-shadow-color fx-shadow-layer-1"></div>').css({ position: 'absolute', opacity: options.opacity - 0.05,  left: options.offset,     top: options.offset,     width: baseWidth + 1, height: baseHeight + 1 }).appendTo($shadow);
			$('<div class="fx-shadow-color fx-shadow-layer-2"></div>').css({ position: 'absolute', opacity: options.opacity - 0.10,  left: options.offset + 2, top: options.offset + 2, width: baseWidth,     height: baseHeight - 3 }).appendTo($shadow);
			$('<div class="fx-shadow-color fx-shadow-layer-3"></div>').css({ position: 'absolute', opacity: options.opacity - 0.10,  left: options.offset + 2, top: options.offset + 2, width: baseWidth - 3, height: baseHeight     }).appendTo($shadow);
			$('<div class="fx-shadow-color fx-shadow-layer-4"></div>').css({ position: 'absolute', opacity: options.opacity,         left: options.offset + 1, top: options.offset + 1, width: baseWidth - 1, height: baseHeight - 1 }).appendTo($shadow);
			
			// Add color
			$("div.fx-shadow-color", $shadow).css("background-color", options.color);
			
			// Set zIndex +1 and make sure position is at least relative
			// Attention: the zIndex will get one higher!
			$element
				.css({
					zIndex: zIndex + 1,
					position: ($element.css("position") == "static" ? "relative" : "")
				});
			
			// Copy the original z-index and position to the clone
			// alert(shadow); If you insert this alert, opera will time correctly!!
			$shadow.css({
				position:     "absolute",
				zIndex:       zIndex,
				top:          position.top+"px",
				left:         position.left+"px",
				width:        baseWidth,
				height:       baseHeight,
				marginLeft:   $element.css("marginLeft"),
				marginRight:  $element.css("marginRight"),
				marginBottom: $element.css("marginBottom"),
				marginTop:    $element.css("marginTop")
			}).fadeIn();
			
			
			if ( options.monitor ) {
				function rearrangeShadow() {
					var $element = $(this), $shadow = $element.next();
					// $shadow.css( $element.position() );
					$shadow.css({
						top:  parseInt($element.css("top"))  +"px",
						left: parseInt($element.css("left")) +"px"
					})
					$(">*", $shadow).css({ height: this.offsetHeight+"px", width: this.offsetWidth+"px" });
				}
			
				// Attempt to use DOMAttrModified event
				$element.bind("DOMAttrModified", rearrangeShadow);
			
				// Use expressions if they exist (IE)
				if( $shadow[0].style.setExpression ) {
					$shadow[0].style.setExpression("top" , "parseInt(this.previousSibling.currentStyle.top ) + 'px'");
					$shadow[0].style.setExpression("left", "parseInt(this.previousSibling.currentStyle.left) + 'px'");
				}
			}

		});
	};
	
})(jQuery);

/**
* jQuery fancyzoom plugin.
* This is an adaptation of the fancyzoom effect as a jQuery plugin
*
* Author: Mathieu Vilaplana <mvilaplana@df-e.com>
* Date: March 2008
* rev 1.0
* rev: 1.1
* Add title if alt in the img
* rev 1.2
* Correction of the image dimension and close button on top right of the image
* rev 1.3
* now fancyzoom can be apply on an image, no need any more link wrapper
* rev 1.4 correct the bug for the overlay in ie6
* rev 1.6 (09/2009), lot of impovement, now image get out of its context.
*/
(function($) {
	
	$.fn.fancyzoom = function(userOptions) {
		//the var to the image box div
	 	var oOverlay = $('<div>').css({
			height: '100%',
			width: '100%',
   			position:'fixed',
   			zIndex:100,
			left: 0,
			top: 0,
			cursor:"wait"
		});
		
		function openZoomBox(imgSrc,o){
			if(o.showoverlay) {
				oOverlay
					.appendTo('body')
					.click(function(){closeZoomBox(o);});
				if( $.browser.msie && $.browser.version < 7 ){
					oOverlay.css({position:'absolute',height:$(document).height(),width:$(document).width()});
				}
			}
			var oImgZoomBox = o.oImgZoomBox;

            //calculate the start point of the animation, it start from the image of the element clicked
            pos=imgSrc.offset();
			o=$.extend(o,{imgSrc:imgSrc,dimOri:{width:imgSrc.outerWidth(),height:imgSrc.outerHeight(),left:pos.left,top:pos.top,'opacity':1}});
			if(!imgSrc.is('img')){
				o.dimOri = $.extend(o.dimOri,{width:0,height:0});
			}

			//calculate the end point of the animaton
			oImgZoomBox.css({'text-align':'center','border':'0px solid red'}).appendTo('body');
			var iWidth = oImgZoomBox.outerWidth();
			var iHeight = oImgZoomBox.outerHeight();
			
			//the target is in the center without the extra margin du to close Image
			dimBoxTarget=$.extend({},{width:iWidth,height:iHeight,'opacity':1}, __posCenter((iWidth),(iHeight+30)));
            
            //place the close button at the right of the zoomed Image
            o.oImgClose.css({left:(dimBoxTarget.left+dimBoxTarget.width-15),top:(dimBoxTarget.top-15)});
            
            var $fctEnd = function(){
            	//end of open, show the shadow
            	if($.fn.shadow && o.shadow && !$.browser.msie){ $('img:first',oImgZoomBox).shadow(o.shadowOpts);}
				if(o.Speed>0 && !$.browser.msie) {o.oImgClose.fadeIn('slow');$('div',oImgZoomBox).fadeIn('slow');}
				else {o.oImgClose.show();$('div',oImgZoomBox).show();}			
            };
            
            
            $('div',oImgZoomBox).hide();//cache le titre
            //cache l'image source
            if(o.imgSrc.is('img')){o.imgSrc.css({'opacity':0});}
            var oImgDisplay = $('img:first', oImgZoomBox).css({'width':'100%','height':'auto'});
  			if(o.Speed > 0) {
  				oImgZoomBox.css(o.dimOri).animate(dimBoxTarget,o.Speed,$fctEnd);
  			}
  			else {
  				oImgZoomBox.css(dimBoxTarget);
  				$fctEnd();
  			}
	 	 }//end openZoomBox
 	 	 
 	 	 /**
 	 	  * First hide the closeBtn, then remove the ZoomBox and the overlay
 	 	  * Animate if Speed > 0 
 	 	  */
 	 	 function closeZoomBox(o){
 	 	 	var oImgZoomBox = o.oImgZoomBox;
	 	 	o.oImgClose.remove();
	 	 	$('div',oImgZoomBox).remove();
	 	 	var endClose = function(){
	 	 		oImgZoomBox.empty().remove();
	 	 		o.imgSrc.css('opacity',1);
	 	 	};
		 	 if(o.Speed > 0){
		 	 	var pos = oImgZoomBox.offset();
		 	 	var iPercent = 0.15;
		 	 	var oDimPlus = {
		 	 		width:(oImgZoomBox.width()*(1+iPercent)),
		 	 		height:(oImgZoomBox.height()*(1+iPercent)),
		 	 		left:(pos.left-(oImgZoomBox.width()*(iPercent/2))),
		 	 		top:(pos.top-(oImgZoomBox.height()*(iPercent/2)))
		 	 	};
		 	 	oImgZoomBox.animate(oDimPlus,o.Speed*0.2,function(){
			 	 	oImgZoomBox.animate(o.dimOri,o.Speed,function(){endClose();});
					if(o.showoverlay) {oOverlay.animate({'opacity':0},o.Speed,function(){$(this).remove();});}
		 	 	});
	 	 	}else {
			 	endClose();
				if(o.showoverlay) {oOverlay.remove();}
	 	 	}
 	 	 }
    		
		/**
		 * The plugin chain.
		 */
   		return this.each(function() {
   			var $this = $(this);
   			var imgTarget = $this.is('img')?$this:($('img:first',$this).length==0)?$this:$('img:first',$this);
   			var imgTargetSrc=null;
   			if($this.attr('href')) {imgTargetSrc = $this.attr('href');}
		 	var oImgClose = $('<img class="jqfancyzoomclosebox">').css({position:'absolute',top:0,left:0,cursor:'pointer'});

			// build main options before element iteration		
	    	var opts = $.extend({},$.fn.fancyzoom.defaultsOptions, userOptions||{},{dimOri:{},
	    		oImgZoomBoxProp:{position:'absolute',left:0,top:0},
	    		oImgClose:oImgClose
	    	});
	    	
			if(imgTarget.is('img')){
		    	var oImgHover = $("<img class='zoom_hover_img' src='"+opts.imgDir+"zoom.png'>").css({position:'absolute',top:0,left:0});
				imgTarget.hover(function(){
					if(imgTarget.css('opacity') != 0){
						oImgHover.appendTo(imgTarget.parent()).hide();
						var pos = imgTarget.position();
						var marginLeft = parseInt(imgTarget.css('margin-left').replace(/px/,''));
						var marginTop = parseInt(imgTarget.css('margin-top').replace(/px/,''));
						marginTop = (marginTop)?marginTop:0;
						marginLeft = (marginLeft)?marginLeft:0;
						oImgHover.css({left:(pos.left+marginLeft),top:(pos.top+marginTop)}).show();
						if($.fn.ifixpng) {oImgHover.ifixpng(opts.imgDir+'blank.gif');}
					}
				},function(){
					oImgHover.remove();
				});
			}
			
   			if($this.is('img')){
   				imgTargetSrc = $this.css('cursor','pointer').attr('src');
   				if(opts.imgResizeScript){
   					if( imgTargetSrc.match(new RegExp("^"+opts.imgResizeScript,"g")) ){
   						imgTargetSrc=imgTargetSrc.replace(/.*img=([^&]*).*/gi,'$1');
   					}
   				}
   			}
	    	oOverlay.css({
				opacity: opts.overlay,
				background:opts.overlayColor
	    	});

   			//make action only on link that point to an image
   			if( !/\.jpg|\.jpeg|\.png|\.gif/i.test(imgTargetSrc) ){
	   			return true;
   			}
   			
   			$this.click(function(){
   				var zoomOpened = $('div.jqfancyzoombox');
   				if( zoomOpened.length > 0  ){
   					//if user click on an other image, cancel the previous loading
					if($('img:first',zoomOpened).attr('src') != imgTargetSrc){
	   					if( oLoading && oLoading.is(':visible') ) {
	   						__cancelLoading();
	   					}
					}
	   				else {//solve the double click pb
	   					return false;
	   				}
   				}
   				var o = $.extend({},opts,userOptions);
   				var closeBtn = $("img.jqfancyzoomclosebox");
   				if(closeBtn.length > 0){
   					var imCurrent = $('img:first',zoomOpened);
   					if(imgTargetSrc == imCurrent.attr('src')){
						//calculate the start point of the animation, it start from the image of the element clicked
						pos=imgTarget.offset();
						o=$.extend(
								o,
								{dimOri:{width:(imgTarget.outerWidth()),height:(imgTarget.outerHeight()),left:pos.left,top:(pos.top),'opacity':0}
							});
						closeZoomBox(o);
						return false;
   					}else {
   						//user click on an other image, close the first one
   						closeBtn.trigger('click');
   						//return false;
   					}
   				}
   				
   				//remove the overlay and Reset
		 	 	if(o.showoverlay && oOverlay) {oOverlay.empty().remove().css({'opacity':o.overlay});}
				//reset the img close and fix png on it if plugin available
				oImgClose.attr('src',o.imgDir+'closebox.png').appendTo('body').hide();
				if($.fn.ifixpng) {$.ifixpng(o.imgDir+'blank.gif');oImgClose.ifixpng(o.imgDir+'blank.gif');}
				oImgClose.unbind('click').click(function(){closeZoomBox(o);});

				//reset zoom box prop and add image zoom with a margin top of 15px = imgclose height / 2
				var oImgZoomBox=$('<div class="jqfancyzoombox"></div>').css(o.oImgZoomBoxProp);
				o = $.extend(o,{oImgZoomBox:oImgZoomBox});

   				var strTitle = imgTarget.attr('alt');
   				if(strTitle){
   					var oTitle = $('<div><center><table height=0 border="0" cellspacing=0 cellpadding=0><tr><td></td><td class="fancyTitle">'+strTitle+'</td><td></td></table></center></div>').css({marginTop:10,marginRight:15});
   					
   					var tdL = oTitle.find('td:first').css({'background':'url('+o.imgDir+'zoom-caption-l.png)',width:'13px',height:'26px'});
   					var tdR = oTitle.find('td:last').css({'background':'url('+o.imgDir+'zoom-caption-r.png)',width:'13px',height:'26px'});
   					var tdC = $('.fancyTitle',oTitle).css({'background':'url('+o.imgDir+'zoom-caption-fill.png)',
   							'padding':'0px 20px',
   							color:'#FFF',
   							'font-size':'14px'
   							});

   					if($.fn.ifixpng){
   						tdL.ifixpng(o.imgDir+'blank.gif');
   						tdR.ifixpng(o.imgDir+'blank.gif');
   						tdC.ifixpng(o.imgDir+'blank.gif');
   					}
   					oTitle.appendTo(oImgZoomBox);   					
   				}
   				var oImgZoom=$('<img />').attr('src',imgTargetSrc).click(function(){closeZoomBox(o);}).prependTo(oImgZoomBox);
				/** Manage zIndex **/
				var imagezindex= opts.imagezindex;
				oOverlay.css('zIndex', imagezindex-1);
				oImgZoomBox.css('zIndex',imagezindex);
				oImgClose.css('zIndex',(imagezindex+10));
				
				//be shure that the image to display is loaded open the zoom box, if not display a loading Image.
   				var imgPreload = new Image();
   				imgPreload.src = imgTargetSrc;
   				var $fctEndLoading = function(){
					if(bCancelLoading) {bCancelLoading=false;}
					else {
						if(__getFileName(imgPreload.src) == __getFileName($('img:first',oImgZoomBox).attr('src')) ){
							fctCalculateImageSize(o.autoresize);
							openZoomBox(imgTarget, o);
							__stoploading();
						}
					}
   				};
   				var fctCalculateImageSize = function (autoresize) {
   					//calcul de la taille de l'image
   					if(autoresize){
	   					var divCalculate = $('<div></div>').css({position:'absolute','top':0,'left':0,opacity:0,'border':'0px solid red'});
	   					var bResize = false;
	   					oImgZoom.appendTo(divCalculate);
						divCalculate.appendTo('body');
						imWidth = oImgZoom.width();
						imHeight = oImgZoom.height();
						maxWidth = $(window).width()*0.9;
						maxHeight = $(window).height()-100;
						if( maxHeight < imHeight ){
							bResize = true;
							oImgZoom.height(maxHeight);
							imWidth= (imWidth*maxHeight)/imHeight;
							oImgZoom.width(imWidth);
							if( maxWidth < imWidth ){
								oImgZoom.width(maxWidth);
								oImgZoom.height(imHeight*maxWidth/imWidth);
							}
						}else if( maxWidth < imWidth ){
							bResize = true;
							oImgZoom.width(maxWidth);
							oImgZoom.height(imHeight*maxWidth/imWidth);
						}
						//because ie do not resize image correctly
						if( bResize && o.imgResizeScript /*&& $.browser.msie*/ ){
							var tWidth = oImgZoom.width();
							var tHeight = oImgZoom.height();
							var finalWidth = tWidth;
							var tabSizes = new Array(1440,1280,1024,800,640,480,360);
							for(i=0;i<tabSizes.length;i++){
								if(tWidth > tabSizes[i]){
									finalWidth = tabSizes[i];
									break;
								}
							}
							oImgZoom.width(finalWidth);
							oImgZoom.height(parseInt(tHeight*finalWidth/tWidth));
							
							var args = "img="+encodeURI(oImgZoom.attr('src'));
							args += "&width="+oImgZoom.width();
							args += "&height="+oImgZoom.height();
							oImgZoom.attr('src',o.imgResizeScript+"?"+args);
						}
						divCalculate.remove();
					}	
	   				oImgZoom.prependTo(oImgZoomBox);
   				};
   				
   				if(imgPreload.complete)	{
   					fctCalculateImageSize(o.autoresize);
   					openZoomBox(imgTarget, o);	
	   				/*__displayLoading(imgPreload);
	   				setTimeout($fctEndLoading,4000);*/
   				}
	   			else {
	   				__displayLoading(o);
	   				imgPreload.onload = function(){
	   					//when loading is finish display the zoombox if user not click on cancel
	   					$fctEndLoading();
	   				};
	   			}
   				return false;		
   			});
   		}
   	);//end return this
    };//end Plugin

    
    //Default Options
    $.fn.fancyzoom.defaultsOptions = {
    	overlayColor: '#000',
    	overlay: 0.6,
    	imagezindex:100,
    	showoverlay:true,
    	Speed:400,
    	shadow:true,
    	shadowOpts:{ color: "#000", offset: 4, opacity: 0.2 },
    	imgDir:'ressources/',
    	imgResizeScript:null,
    	autoresize:true
 	 };
 	 
	function __posCenter(iWidth,iHeight){
		var iLeft = ($(window).width() - iWidth) / 2 + $(window).scrollLeft();
		var iTop = ($(window).height() - iHeight) / 2 + $(window).scrollTop();
		iLeft=(iLeft < 0)?0:iLeft;
		iTop=(iTop < 0)?0:iTop;
	  		return {left:iLeft,top:iTop};
    }
    
    //
    // LOADING MANAGEMENT
    //
    var oLoading =null ;
	var bCancelLoading = false;
	var timerLoadingImg = null;
	function __displayLoading(o){
		if(!oLoading){
			oLoading = $('<div></div>').css({width:50,height:50,position:'absolute','background':'transparent',
			opacity:8/10,color:'#FFF',padding:'5px','font-size':'10px'});
		}
		oLoading.css(__posCenter(50,50)).html('<img src="'+o.imgDir+'blank.gif" />').click(function(){__cancelLoading();}).appendTo('body').show();
		timerLoadingImg=setTimeout(function(){__changeimageLoading(o);},400);
	}
	function __cancelLoading(){
		bCancelLoading=true;
		__stoploading();
	}
	function __stoploading(){
		oLoading.hide().remove();
		if(timerLoadingImg){
			clearTimeout(timerLoadingImg);
			timerLoadingImg=null;
		}
	}
	
	/**
	 * Animate the png loading image.
	 */
	function __changeimageLoading(o){
		if(oLoading && !oLoading.is(':visible')){
			timerLoadingImg=null;
			return;
		}
		
		var $im=$('img',oLoading);
		//First call im.src ="", set it to the fire png zoom spin
		if(!$im.attr('src') || /blank\.gif/.test($im.attr('src'))){
			strImgSrc = o.imgDir+"zoom-spin-1.png";
		}
		//rotate the im src until 12
		else {
			tab = $im.attr('src').split(/[- .]+/);
			iImg = parseInt(tab[2]);
			iImg = (iImg < 12)? (iImg+1):1;
			strImgSrc= tab[0]+"-"+tab[1]+"-"+iImg+"."+tab[3];
		}
		var pLoad = new Image();
		pLoad.src=strImgSrc;
		var $fct = function (){
			
			oLoading && oLoading.css(__posCenter(50,50));
			$im.attr('src',strImgSrc);
			timerLoadingImg = setTimeout(__changeimageLoading,100);
		};
		//to preserve bug if img not exist change it only if load complete.
		if(pLoad.complete){$fct();}
		else{pLoad.onload=$fct;}
	}
 	
 	function __getFileName(strPath){
 		if(!strPath) {return false;}
		var tabPath = strPath.split('/');
		return ((tabPath.length<1)?strPath:tabPath[(tabPath.length-1)]);		
 	}
 	
})(jQuery);

$(document).ready(function(){
	var image_width = $("#stacks_in_577_page0 img").width();
	var image_height = $("#stacks_in_577_page0 img").height();
	var thumb_width = Math.round(image_width * (50/100));
	var thumb_height = Math.round(image_height * (50/100));
	$("#stacks_in_577_page0 img").attr('width',thumb_width);
	$("#stacks_in_577_page0 img").attr('height',thumb_height);
	
	var options = {	overlay: 0.8,
					imgDir: 'files/fancyimage-zoom-images/',
					showoverlay: true,
					overlayColor: '#000000',
	               	Speed: 600,
			    	shadow:true,
			    	shadowOpts:{ color: "#000000", offset: 4, opacity: 0.8 }
	}
	$("#stacks_in_577_page0 img").fancyzoom(options);
});
//-- End Fancy Image Zoom Stack --//

	return stack;
})(stacks.stacks_in_577_page0);



