// usage: log('inside coolFunc', this, arguments);
// paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function(){
  log.history = log.history || [];   // store logs to an array for reference
  log.history.push(arguments);
  if(this.console) {
    arguments.callee = arguments.callee.caller;
    var newarr = [].slice.call(arguments);
    (typeof console.log === 'object' ? log.apply.call(console.log, console, newarr) : console.log.apply(console, newarr));
  }
};

// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,timeStamp,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}})((function(){try
{console.log();return window.console;}catch(err){return window.console={};}})());


// place any jQuery/helper plugins in here, instead of separate, slower script files.

// ** ==================================================================== ** //
// ** jQuery Tiny Carousel

// ** http://www.baijs.nl/tinycarousel/
// ** source: jquery.tinycarousel.min.js

(function($){$.tiny=$.tiny||{};$.tiny.carousel={options:{start:1,display:1,axis:'x',controls:true,pager:false,interval:false,intervaltime:3000,rewind:false,animation:true,duration:1000,callback:null}};$.fn.tinycarousel=function(options){var options=$.extend({},$.tiny.carousel.options,options);this.each(function(){$(this).data('tcl',new Carousel($(this),options));});return this;};$.fn.tinycarousel_start=function(){$(this).data('tcl').start();};$.fn.tinycarousel_stop=function(){$(this).data('tcl').stop();};$.fn.tinycarousel_move=function(iNum){$(this).data('tcl').move(iNum-1,true);};function Carousel(root,options){var oSelf=this;var oViewport=$('.viewport:first',root);var oContent=$('.overview:first',root);var oPages=oContent.children();var oBtnNext=$('.next:first',root);var oBtnPrev=$('.prev:first',root);var oPager=$('.pager:first',root);var iPageSize,iSteps,iCurrent,oTimer,bPause,bForward=true,bAxis=options.axis=='x';function initialize(){iPageSize=bAxis?$(oPages[0]).outerWidth(true):$(oPages[0]).outerHeight(true);var iLeftover=Math.ceil(((bAxis?oViewport.outerWidth():oViewport.outerHeight())/(iPageSize*options.display))-1);iSteps=Math.max(1,Math.ceil(oPages.length/options.display)-iLeftover);iCurrent=Math.min(iSteps,Math.max(1,options.start))-2;oContent.css(bAxis?'width':'height',(iPageSize*oPages.length));oSelf.move(1);setEvents();return oSelf;};function setEvents(){if(options.controls&&oBtnPrev.length>0&&oBtnNext.length>0){oBtnPrev.click(function(){oSelf.move(-1);return false;});oBtnNext.click(function(){oSelf.move(1);return false;});}if(options.interval){root.hover(oSelf.stop,oSelf.start);}if(options.pager&&oPager.length>0){$('a',oPager).click(setPager);}};function setButtons(){if(options.controls){oBtnPrev.toggleClass('disable',!(iCurrent>0));oBtnNext.toggleClass('disable',!(iCurrent+1<iSteps));}if(options.pager){var oNumbers=$('.pagenum',oPager);oNumbers.removeClass('active');$(oNumbers[iCurrent]).addClass('active');}};function setPager(oEvent){if($(this).hasClass('pagenum')){oSelf.move(parseInt(this.rel),true);}return false;};function setTimer(){if(options.interval&&!bPause){clearTimeout(oTimer);oTimer=setTimeout(function(){iCurrent=iCurrent+1==iSteps?-1:iCurrent;bForward=iCurrent+1==iSteps?false:iCurrent==0?true:bForward;oSelf.move(bForward?1:-1);},options.intervaltime);}};this.stop=function(){clearTimeout(oTimer);bPause=true;};this.start=function(){bPause=false;setTimer();};this.move=function(iDirection,bPublic){iCurrent=bPublic?iDirection:iCurrent+=iDirection;if(iCurrent>-1&&iCurrent<iSteps){var oPosition={};oPosition[bAxis?'left':'top']=-(iCurrent*(iPageSize*options.display));oContent.animate(oPosition,{queue:false,duration:options.animation?options.duration:0,complete:function(){if(typeof options.callback=='function')options.callback.call(this,oPages[iCurrent],iCurrent);}});setButtons();setTimer();}};return initialize();};})(jQuery);

// ** ==================================================================== ** //
// ** jKwicks for jQuery (version 1.5.1)

// ** Copyright (c) 2008 Jeremy Martin
// ** http://www.jeremymartin.name/projects.php?project=kwicks
// ** Licensed under the MIT license:
// ** http://www.opensource.org/licenses/mit-license.php
// ** Any and all use of this script must be accompanied by this copyright/license notice in its present form.

(function($){
	$.fn.kwicks = function(options) {
		var defaults = {
			isVertical: false,
			sticky: false,
			defaultKwick: 0,
			event: 'mouseover',
			spacing: 0,
			duration: 500
		};
		var o = $.extend(defaults, options);
		var WoH = (o.isVertical ? 'height' : 'width'); // WoH = Width or Height
		var LoT = (o.isVertical ? 'top' : 'left'); // LoT = Left or Top
		
		return this.each(function() {
			container = $(this);
			var kwicks = container.children('li');
			var normWoH = kwicks.eq(0).css(WoH).replace(/px/,''); // normWoH = Normal Width or Height
			if(!o.max) {
				o.max = (normWoH * kwicks.size()) - (o.min * (kwicks.size() - 1));
			} else {
				o.min = ((normWoH * kwicks.size()) - o.max) / (kwicks.size() - 1);
			}
			// set width of container ul
			if(o.isVertical) {
				container.css({
					width : kwicks.eq(0).css('width'),
					height : (normWoH * kwicks.size()) + (o.spacing * (kwicks.size() - 1)) + 'px'
				});				
			} else {
				container.css({
					width : (normWoH * kwicks.size()) + (o.spacing * (kwicks.size() - 1)) + 'px',
					height : kwicks.eq(0).css('height')
				});				
			}

			// pre calculate left or top values for all kwicks but the first and last
			// i = index of currently hovered kwick, j = index of kwick we're calculating
			var preCalcLoTs = []; // preCalcLoTs = pre-calculated Left or Top's
			for(i = 0; i < kwicks.size(); i++) {
				preCalcLoTs[i] = [];
				// don't need to calculate values for first or last kwick
				for(j = 1; j < kwicks.size() - 1; j++) {
					if(i == j) {
						preCalcLoTs[i][j] = o.isVertical ? j * o.min + (j * o.spacing) : j * o.min + (j * o.spacing);
					} else {
						preCalcLoTs[i][j] = (j <= i ? (j * o.min) : (j-1) * o.min + o.max) + (j * o.spacing);
					}
				}
			}
			
			// loop through all kwick elements
			kwicks.each(function(i) {
				var kwick = $(this);
				// set initial width or height and left or top values
				// set first kwick
				if(i === 0) {
					kwick.css(LoT, '0px');
				} 
				// set last kwick
				else if(i == kwicks.size() - 1) {
					kwick.css(o.isVertical ? 'bottom' : 'right', '0px');
				}
				// set all other kwicks
				else {
					if(o.sticky) {
						kwick.css(LoT, preCalcLoTs[o.defaultKwick][i]);
					} else {
						kwick.css(LoT, (i * normWoH) + (i * o.spacing));
					}
				}
				// correct size in sticky mode
				if(o.sticky) {
					if(o.defaultKwick == i) {
						kwick.css(WoH, o.max + 'px');
						kwick.addClass('active');
					} else {
						kwick.css(WoH, o.min + 'px');
					}
				}
				kwick.css({
					margin: 0,
					position: 'absolute'
				});
				
				kwick.bind(o.event, function() {
					// calculate previous width or heights and left or top values
					var prevWoHs = []; // prevWoHs = previous Widths or Heights
					var prevLoTs = []; // prevLoTs = previous Left or Tops
					kwicks.stop().removeClass('active');
					for(j = 0; j < kwicks.size(); j++) {
						prevWoHs[j] = kwicks.eq(j).css(WoH).replace(/px/, '');
						prevLoTs[j] = kwicks.eq(j).css(LoT).replace(/px/, '');
					}
					var aniObj = {};
					aniObj[WoH] = o.max;
					var maxDif = o.max - prevWoHs[i];
					var prevWoHsMaxDifRatio = prevWoHs[i]/maxDif;
					kwick.addClass('active').animate(aniObj, {
						step: function(now) {
							// calculate animation completeness as percentage
							var percentage = maxDif != 0 ? now/maxDif - prevWoHsMaxDifRatio : 1;
							// adjsut other elements based on percentage
							kwicks.each(function(j) {
								if(j != i) {
									kwicks.eq(j).css(WoH, prevWoHs[j] - ((prevWoHs[j] - o.min) * percentage) + 'px');
								}
								if(j > 0 && j < kwicks.size() - 1) { // if not the first or last kwick
									kwicks.eq(j).css(LoT, prevLoTs[j] - ((prevLoTs[j] - preCalcLoTs[i][j]) * percentage) + 'px');
								}
							});
						},
						duration: o.duration,
						easing: o.easing
					});
				});
			});
			if(!o.sticky) {
				container.bind("mouseleave", function() {
					var prevWoHs = [];
					var prevLoTs = [];
					kwicks.removeClass('active').stop();
					for(i = 0; i < kwicks.size(); i++) {
						prevWoHs[i] = kwicks.eq(i).css(WoH).replace(/px/, '');
						prevLoTs[i] = kwicks.eq(i).css(LoT).replace(/px/, '');
					}
					var aniObj = {};
					aniObj[WoH] = normWoH;
					var normDif = normWoH - prevWoHs[0];
					kwicks.eq(0).animate(aniObj, {
						step: function(now) {
							var percentage = normDif != 0 ? (now - prevWoHs[0])/normDif : 1;
							for(i = 1; i < kwicks.size(); i++) {
								kwicks.eq(i).css(WoH, prevWoHs[i] - ((prevWoHs[i] - normWoH) * percentage) + 'px');
								if(i < kwicks.size() - 1) {
									kwicks.eq(i).css(LoT, prevLoTs[i] - ((prevLoTs[i] - ((i * normWoH) + (i * o.spacing))) * percentage) + 'px');
								}
							}
						},
						duration: o.duration,
						easing: o.easing
					});
				});
			}
		});
	};
})(jQuery);

// ** ==================================================================== ** //
// ** jQuery elastislide

// ** http://tympanus.net/codrops/2011/09/12/elastislide-responsive-carousel/
(function( window, $, undefined ) {
	
	// http://www.netcu.de/jquery-touchwipe-iphone-ipad-library
	$.fn.touchwipe 				= function(settings) {
		
		var config = {
			min_move_x: 20,
			min_move_y: 20,
			wipeLeft: function() { },
			wipeRight: function() { },
			wipeUp: function() { },
			wipeDown: function() { },
			preventDefaultEvents: true
		};
     
		if (settings) $.extend(config, settings);
 
		this.each(function() {
			var startX;
			var startY;
			var isMoving = false;

			function cancelTouch() {
				this.removeEventListener('touchmove', onTouchMove);
				startX = null;
				isMoving = false;
			}	
		 
			function onTouchMove(e) {
				if(config.preventDefaultEvents) {
					e.preventDefault();
				}
				if(isMoving) {
					var x = e.touches[0].pageX;
					var y = e.touches[0].pageY;
					var dx = startX - x;
					var dy = startY - y;
					if(Math.abs(dx) >= config.min_move_x) {
						cancelTouch();
						if(dx > 0) {
							config.wipeLeft();
						}
						else {
							config.wipeRight();
						}
					}
					else if(Math.abs(dy) >= config.min_move_y) {
						cancelTouch();
						if(dy > 0) {
							config.wipeDown();
						}
						else {
							config.wipeUp();
						}
					}
				}
			}
		 
			function onTouchStart(e)
			{
				if (e.touches.length == 1) {
					startX = e.touches[0].pageX;
					startY = e.touches[0].pageY;
					isMoving = true;
					this.addEventListener('touchmove', onTouchMove, false);
				}
			}    	 
			if ('ontouchstart' in document.documentElement) {
				this.addEventListener('touchstart', onTouchStart, false);
			}
		});
 
		return this;
	};
	
	$.elastislide 				= function( options, element ) {
		this.$el	= $( element );
		this._init( options );
	};
	
	$.elastislide.defaults 		= {
		speed		: 450,	// animation speed
		easing		: '',	// animation easing effect
		imageW		: 190,	// the images width
		margin		: 3,	// image margin right
		border		: 2,	// image border
		minItems	: 1,	// the minimum number of items to show. 
							// when we resize the window, this will make sure minItems are always shown 
							// (unless of course minItems is higher than the total number of elements)
		current		: 0,	// index of the current item
							// when we resize the window, the carousel will make sure this item is visible 
		onClick		: function() { return false; } // click item callback
    };
	
	$.elastislide.prototype 	= {
		_init 				: function( options ) {
			
			this.options 		= $.extend( true, {}, $.elastislide.defaults, options );
			
			// <ul>
			this.$slider		= this.$el.find('ul.es-ul');
			
			// <li>
			this.$items			= this.$slider.children('li');
			
			// year values
			$years     = [];
			$currentSlide = 0;
			this.$getYears	= this.$slider.children('li').each(function(n){
			  $years.push($(this).data("date"));
			});
			
			// total number of elements / images
			this.itemsCount		= this.$items.length;
			
			// cache the <ul>'s parent, since we will eventually need to recalculate its width on window resize
			this.$esCarousel	= this.$slider.parent();
			
			// validate options
			this._validateOptions();
			
			// set sizes and initialize some vars...
			this._configure();
			
			// add navigation buttons
			this._addControls();
			
			// initialize the events
			this._initEvents();
			
			// show the <ul>
			this.$slider.show();
			
			// slide to current's position
			this._slideToCurrent( false );
			
		},
		_validateOptions	: function() {
		
			if( this.options.speed < 0 )
				this.options.speed = 450;
			if( this.options.margin < 0 )
				this.options.margin = 4;
			if( this.options.border < 0 )
				this.options.border = 1;
			if( this.options.minItems < 1 || this.options.minItems > this.itemsCount )
				this.options.minItems = 1;
			if( this.options.current > this.itemsCount - 1 )
				this.options.current = 0;
				
		},
		_configure			: function() {
			
			// current item's index
			this.current		= this.options.current;
			
			// the ul's parent's (div.es-carousel) width is the "visible" width
			this.visibleWidth	= this.$esCarousel.width();
			
			// test to see if we need to initially resize the items
			if( this.visibleWidth < this.options.minItems * ( this.options.imageW + 2 * this.options.border ) + ( this.options.minItems - 1 ) * this.options.margin ) {
				this._setDim( ( this.visibleWidth - ( this.options.minItems - 1 ) * this.options.margin ) / this.options.minItems );
				this._setCurrentValues();
				// how many items fit with the current width
				this.fitCount	= this.options.minItems;
			}
			else {
				this._setDim();
				this._setCurrentValues();
			}
			
			// set the <ul> width
			this.$slider.css({
				width	: this.sliderW
			});
			
		},
		_setDim				: function( elW ) {
			
			// <li> style
			this.$items.css({
				marginRight	: this.options.margin,
				width		: ( elW ) ? elW : this.options.imageW + 2 * this.options.border
			}).children('a').css({ // <a> style
				borderWidth		: this.options.border
			});
			
		},
		_setCurrentValues	: function() {
			
			// the total space occupied by one item
			this.itemW			= this.$items.outerWidth(true);
			
			// total width of the slider / <ul>
			// this will eventually change on window resize
			this.sliderW		= this.itemW * this.itemsCount;
			
			// the ul parent's (div.es-carousel) width is the "visible" width
			this.visibleWidth	= this.$esCarousel.width();
			
			// how many items fit with the current width
			this.fitCount		= Math.floor( this.visibleWidth / this.itemW );
			
		},
		_addControls		: function() {
			
			this.$navNext	= $('<span class="es-nav-next">' + $years[$currentSlide+1] + '</span>');
			this.$navPrev	= $('<span class="es-nav-prev">' + 'Null' + '</span>');
			$('<div class="es-nav"/>')
			.append( this.$navPrev )
			.append( this.$navNext )
			.appendTo( this.$el );
			
			//this._toggleControls();
				
		},
		_toggleControls		: function( dir, status ) {
			
			// show / hide navigation buttons
			if( dir && status ) {
				if( status === 1 ) {
					( dir === 'right' ) ? this.$navNext.show() : this.$navPrev.show();
				}
				else {
					( dir === 'right' ) ? this.$navNext.hide() : this.$navPrev.hide();
				}
			}
			else if( this.current === this.itemsCount - 1 || this.fitCount >= this.itemsCount )
					this.$navNext.hide();

		},
		_initEvents			: function() {
			
			var instance	= this;
			
			// window resize
			$(window).bind('resize.elastislide', function( event ) {
				
				// set values again
				instance._setCurrentValues();
				
				// need to resize items
				if( instance.visibleWidth < instance.options.minItems * ( instance.options.imageW + 2 * instance.options.border ) + ( instance.options.minItems - 1 ) * instance.options.margin ) {
					instance._setDim( ( instance.visibleWidth - ( instance.options.minItems - 1 ) * instance.options.margin ) / instance.options.minItems );
					instance._setCurrentValues();
					instance.fitCount	= instance.options.minItems;
				}	
				else{
					instance._setDim();
					instance._setCurrentValues();
				}
				
				instance.$slider.css({
					width	: instance.sliderW + 10 // TODO: +10px seems to solve a firefox "bug" :S
				});
						
				// slide to the current element
				clearTimeout( instance.resetTimeout );
				instance.resetTimeout	= setTimeout(function() {
					instance._slideToCurrent();
					$currentSlide = 0;
					instance._updateButtons();
				}, 200);
				
			});
			
			// navigation buttons events
			this.$navNext.bind('click.elastislide', function( event ) {
				instance._slide('right');
				$currentSlide ++;
				instance._updateButtons();
			});
			
			this.$navPrev.bind('click.elastislide', function( event ) {
				instance._slide('left');
				$currentSlide --;
				instance._updateButtons();
			});
			
			// item click event
			this.$items.bind('click.elastislide', function( event ) {
				instance.options.onClick( $(this) );
				return false;
			});
			
			// touch events
			/**
			instance.$slider.touchwipe({
				wipeLeft			: function() {
					instance._slide('right');
					$currentSlide ++;
  				instance._updateButtons();
				},
				wipeRight			: function() {
					instance._slide('left');
					$currentSlide --;
  				instance._updateButtons();
				}
			});
			*/
		},
		_updateButtons: function() {
		  this.$navNext.html($years[$currentSlide + 1]);
		  this.$navPrev.html($years[$currentSlide - 1]);
		},
		_slide				: function( dir, val, anim, callback ) {
		  
			// if animating return
			if( this.$slider.is(':animated') )
				return false;
			
			// current margin left
			var ml		= parseFloat( this.$slider.css('margin-left') );
			
			// val is just passed when we want an exact value for the margin left (used in the _slideToCurrent function)
			if( val === undefined ) {
			
				// how much to slide?
				var amount	= this.fitCount * this.itemW, val;
				
				if( amount < 0 ) return false;
				
				// make sure not to leave a space between the last item / first item and the end / beggining of the slider available width
				if( dir === 'right' && this.sliderW - ( Math.abs( ml ) + amount ) < this.visibleWidth ) {
					amount	= this.sliderW - ( Math.abs( ml ) + this.visibleWidth ) - this.options.margin; // decrease the margin left
					// show / hide navigation buttons
					this._toggleControls( 'right', -1 );
					this._toggleControls( 'left', 1 );
				}
				else if( dir === 'left' && Math.abs( ml ) - amount < 0 ) {				
					amount	= Math.abs( ml );
					// show / hide navigation buttons
					this._toggleControls( 'left', -1 );
					this._toggleControls( 'right', 1 );
				}
				else {
					var fml; // future margin left
					( dir === 'right' ) 
						? fml = Math.abs( ml ) + this.options.margin + Math.abs( amount ) 
						: fml = Math.abs( ml ) - this.options.margin - Math.abs( amount );
					// show / hide navigation buttons
					
					if( fml > 0 )
						this._toggleControls( 'left', 1 );
					else	
						this._toggleControls( 'left', -1 );
					
					if( fml < this.sliderW - this.visibleWidth )
						this._toggleControls( 'right', 1 );
					else	
						this._toggleControls( 'right', -1 );
						
				}
				
				( dir === 'right' ) ? val = '-=' + amount : val = '+=' + amount
				
			}
			else {
				var fml		= Math.abs( val ); // future margin left
				
				if( Math.max( this.sliderW, this.visibleWidth ) - fml < this.visibleWidth ) {
					val	= - ( Math.max( this.sliderW, this.visibleWidth ) - this.visibleWidth );
					if( val !== 0 )
						val += this.options.margin;	// decrease the margin left if not on the first position
						
					// show / hide navigation buttons
					this._toggleControls( 'right', -1 );
					fml	= Math.abs( val );
				}
				
				// show / hide navigation buttons
				if( fml > 0 )
					this._toggleControls( 'left', 1 );
				else
					this._toggleControls( 'left', -1 );
				
				if( Math.max( this.sliderW, this.visibleWidth ) - this.visibleWidth > fml + this.options.margin )	
					this._toggleControls( 'right', 1 );
				else
					this._toggleControls( 'right', -1 );
					
			}
			
			$.fn.applyStyle = ( anim === undefined ) ? $.fn.animate : $.fn.css;
			
			var sliderCSS	= { marginLeft : val };
			
			var instance	= this;
			
			this.$slider.applyStyle( sliderCSS, $.extend( true, [], { duration : this.options.speed, easing : this.options.easing, complete : function() {
				if( callback ) callback.call();
			} } ) );
			
		},
		_slideToCurrent		: function( anim ) {
			
			// how much to slide?
			var amount	= this.current * this.itemW;
			this._slide('', -amount, anim );
		},
		add					: function( $newelems, callback ) {
			
			// adds new items to the carousel
			this.$items 		= this.$items.add( $newelems );
			this.itemsCount		= this.$items.length;
			this._setDim();
			this._setCurrentValues();
			this.$slider.css({
				width	: this.sliderW
			});
			this._slideToCurrent();
			
			if ( callback ) callback.call( $newelems );
			
		},
		destroy				: function( callback ) {
			this._destroy( callback );
		},
		_destroy 			: function( callback ) {
			this.$el.unbind('.elastislide').removeData('elastislide');
			$(window).unbind('.elastislide');
			if ( callback ) callback.call();
		}
	};
	
	var logError 				= function( message ) {
		if ( this.console ) {
			console.error( message );
		}
	};
	
	$.fn.elastislide 				= function( options ) {
		if ( typeof options === 'string' ) {
			var args = Array.prototype.slice.call( arguments, 1 );

			this.each(function() {
				var instance = $.data( this, 'elastislide' );
				if ( !instance ) {
					logError( "cannot call methods on elastislide prior to initialization; " +
					"attempted to call method '" + options + "'" );
					return;
				}
				if ( !$.isFunction( instance[options] ) || options.charAt(0) === "_" ) {
					logError( "no such method '" + options + "' for elastislide instance" );
					return;
				}
				instance[ options ].apply( instance, args );
			});
		} 
		else {
			this.each(function() {
				var instance = $.data( this, 'elastislide' );
				if ( !instance ) {
					$.data( this, 'elastislide', new $.elastislide( options, this ) );
				}
			});
		}
		return this;
	};
	
})( window, jQuery );

// ** ==================================================================== ** //
// ** jQuery Organic Tabs

// ** http://css-tricks.com/4530-organic-tabs/

(function($) {

    $.organicTabs = function(el, options) {

        var base = this;
        base.$el = $(el);
        base.$nav = base.$el.find(".filter-nav");

        base.init = function() {

            base.options = $.extend({},$.organicTabs.defaultOptions, options);

            // Accessible hiding fix
            $(".hide").css({
                "position": "relative",
                "top": 0,
                "left": 0,
                "display": "none"
            }); 

            base.$nav.delegate("li > a", "click", function() {

                // Figure out current list via CSS class
                var curList = base.$el.find("a.current").attr("href").substring(1),

                // List moving to
                    $newList = $(this),

                // Figure out ID of new list
                    listID = $newList.attr("href").substring(1),

                // Set outer wrapper height to (static) height of current inner list
                    $allListWrap = base.$el.find(".filter-wrap"),
                    curListHeight = $allListWrap.height();
                $allListWrap.height(curListHeight);

                if ((listID != curList) && ( base.$el.find(":animated").length == 0)) {

                    // Fade out current list
                    base.$el.find("#"+curList).fadeOut(base.options.speed, function() {

                        // Fade in new list on callback
                        base.$el.find("#"+listID).fadeIn(base.options.speed);

                        // Adjust outer wrapper to fit new list snuggly
                        var newHeight = base.$el.find("#"+listID).height();
                        $allListWrap.animate({
                            height: newHeight
                        });

                        // Remove highlighting - Add to just-clicked tab
                        base.$el.find(".filter-nav li a").removeClass("current");
                        $newList.addClass("current");

                    });

                }   

                // Don't behave like a regular link
                // Stop propegation and bubbling
                return false;
            });

        };
        base.init();
    };

    $.organicTabs.defaultOptions = {
        "speed": 300
    };

    $.fn.organicTabs = function(options) {
        return this.each(function() {
            (new $.organicTabs(this, options));
        });
    };

})(jQuery);

// ** ==================================================================== ** //
/*
 * nyroModal v2.0.0
 * Core
 *
 */
jQuery(function($, undefined) {

	var $w = $(window),
		$d = $(document),
		$b = $('body'),
		baseHref = $('base').attr('href'),
		// nyroModal Object
		_nmObj = {
			filters: [],	// List of filters used
			callbacks: {},	// Sepcific callbacks
			loadFilter: undefined,	// Name of the filter used for loading

			modal: false,	// Indicates if it's a modal window or not
			closeOnEscape: true,	// Indicates if the modal should close on Escape key
			closeOnClick: true,	// Indicates if a click on the background should close the modal
			useKeyHandler: false,	// Indicates if the modal has to handle key down event

			showCloseButton: true,	// Indicates if the closeButonn should be added
			closeButton: '<a href="#" class="nyroModalClose nyroModalCloseButton nmReposition" title="close">Close</a>',	// Close button HTML

			stack: false,	// Indicates if links automatically binded inside the modal should stack or not
			nonStackable: 'form',	// Filter to not stack DOM element

			header: undefined,	// header include in every modal
			footer: undefined,	// footer include in every modal
			
			// Specific confirguation for gallery filter
			galleryLoop: true,	// Indicates if the gallery should loop
			galleryCounts: true,	// Indicates if the gallery counts should be shown
			ltr: true, // Left to Right by default. Put to false for Hebrew or Right to Left language. Used in gallery filter

			// Specific confirguation for image filter
			imageRegex: '[^\.]\.(jpg|jpeg|png|tiff|gif|bmp)\s*$',	// Regex used to detect image link

			selIndicator: 'nyroModalSel', // Value added when a form or Ajax is sent with a filter content

			swfObjectId: undefined, // Object id for swf object
			swf:  {	// Default SWF attributes
				allowFullScreen: 'true',
				allowscriptaccess: 'always',
				wmode: 'transparent'
			},

			store: {},	// Storage object for filters.
			errorMsg: 'An error occured',	// Error message
			elts: {	// HTML elements for the modal
				all: undefined,
				bg: undefined,
				load: undefined,
				cont: undefined,
				hidden: undefined
			},
			sizes: {	// Size information
				initW: undefined,	// Initial width
				initH: undefined,	// Initial height
				w: undefined,		// width
				h: undefined,		// height
				minW: undefined,	// minimum Width
				minH: undefined,	// minimum height
				wMargin: undefined,	// Horizontal margin
				hMargin: undefined	// Vertical margin
			},
			anim: {	// Animation names to use
				def: undefined,			// Default animation set to use if sspecific are not defined or doesn't exist
				showBg: undefined,		// Set to use for showBg animation
				hideBg: undefined,		// Set to use for hideBg animation
				showLoad: undefined,	// Set to use for showLoad animation
				hideLoad: undefined,	// Set to use for hideLoad animation
				showCont: undefined,	// Set to use for showCont animation
				hideCont: undefined,	// Set to use for hideCont animation
				showTrans: undefined,	// Set to use for showTrans animation
				hideTrans: undefined,	// Set to use for hideTrans animation
				resize: undefined		// Set to use for resize animation
			},

			_open: false,	// Indicates if the modal is open
			_bgReady: false,	// Indicates if the background is ready
			_opened: false,	// Indicates if the modal was opened (useful for stacking)
			_loading: false,	// Indicates if the loading is shown
			_animated: false,	// Indicates if the modal is currently animated
			_transition: false,	//Indicates if the modal is in transition
			_nmOpener: undefined,	// nmObj of the modal that opened the current one in non stacking mode
			_nbContentLoading: 0,	// Counter for contentLoading call
			_scripts: '',	// Scripts tags to be included
			_scriptsShown: '',	//Scripts tags to be included once the modal is swhon

			// save the object in data
			saveObj: function() {
				this.opener.data('nmObj', this);
			},
			// Open the modal
			open: function() {
				if (this._nmOpener)
					this._nmOpener._close();
				this.getInternal()._pushStack(this.opener);
				this._opened = false;
				this._bgReady = false;
				this._open = true;
				this._initElts();
				this._load();
				this._nbContentLoading = 0;
				this._callAnim('showBg', $.proxy(function() {
					this._bgReady = true;
					if (this._nmOpener) {
						// fake closing of the opener nyroModal
						this._nmOpener._bgReady = false;
						this._nmOpener._loading = false;
						this._nmOpener._animated = false;
						this._nmOpener._opened = false;
						this._nmOpener._open = false;
						this._nmOpener.elts.cont = this._nmOpener.elts.hidden = this._nmOpener.elts.load = this._nmOpener.elts.bg = this._nmOpener.elts.all = undefined;
						this._nmOpener.saveObj();
						this._nmOpener = undefined;
					}
					this._contentLoading();
				}, this));
			},

			// Resize the modal according to sizes.initW and sizes.initH
			// Will call size function
			// @param recalc boolean: Indicate if the size should be recalaculated (useful when content has changed)
			resize: function(recalc) {
				if (recalc) {
					this.elts.hidden.append(this.elts.cont.children().first().clone());
					this.sizes.initW = this.sizes.w = this.elts.hidden.width();
					this.sizes.initH = this.sizes.h = this.elts.hidden.height();
					this.elts.hidden.empty();
				} else {
					this.sizes.w = this.sizes.initW;
					this.sizes.h = this.sizes.initH;
				}
				this._unreposition();
				this.size();
				this._callAnim('resize', $.proxy(function() {
					this._reposition();
				}, this));
			},

			// Update sizes element to not go outsize the viewport.
			// Will call 'size' callback filter
			size: function() {
				var maxHeight = this.getInternal().fullSize.viewH - this.sizes.hMargin,
					maxWidth = this.getInternal().fullSize.viewW - this.sizes.wMargin;
				if (this.sizes.minW && this.sizes.minW > this.sizes.w)
					this.sizes.w = this.sizes.minW;
				if (this.sizes.minH && this.sizes.minH > this.sizes.h)
					this.sizes.h = this.sizes.minH;
				if (this.sizes.h > maxHeight || this.sizes.w > maxWidth) {
					// We're gonna resize the modal as it will goes outside the view port
					this.sizes.h = Math.min(this.sizes.h, maxHeight);
					this.sizes.w = Math.min(this.sizes.w, maxWidth);
				}
				// Forces higher width to avoid unwanted horizontal scrollbar
        // when heigh exceeds the viewport's heigh
        if (maxHeight < this.sizes.initH) {
        	this.sizes.w += 15;
        }
				this._callFilters('size');
			},

			// Get the nmObject for a new nyroModal
			getForNewLinks: function(elt) {
				var ret;
				if (this.stack && (!elt || this.isStackable(elt))) {
					ret = $.extend(true, {}, this);
					ret._nmOpener = undefined;
					ret.elts.all = undefined;
				} else {
					ret = $.extend({}, this);
					ret._nmOpener = this;
				}
				ret.filters = [];
				ret.opener = undefined;
				ret._open = false;
				return ret;
			},
			
			// Indicate if an element can be stackable or not, regarding the nonStackable setting
			isStackable: function(elt) {
				return !elt.is(this.nonStackable);
			},

			// key handle function.
			// Will call 'keyHandle' callback filter
			keyHandle: function(e) {
				this.keyEvent = e;
				this._callFilters('keyHandle');
				this.keyEvent = undefined;
				delete(this.keyEvent);
			},

			// Get the internal object
			getInternal: function() {
				return _internal;
			},

			// Internal function for closing a nyroModal
			// Will call 'close' callback filter
			_close: function() {
				this.getInternal()._removeStack(this.opener);
				this._opened = false;
				this._open = false;
				this._callFilters('close');
			},
			// Public function for closing a nyroModal
			close: function() {
				this._close();
				this._callFilters('beforeClose');
				var self = this;
				this._unreposition();
				self._callAnim('hideCont', function() {
					self._callAnim('hideLoad', function() {
						self._callAnim('hideBg', function() {
							self._callFilters('afterClose');
							self.elts.cont.remove();
							self.elts.hidden.remove();
							self.elts.load.remove();
							self.elts.bg.remove();
							self.elts.all.remove();
							self.elts.cont = self.elts.hidden = self.elts.load = self.elts.bg = self.elts.all = undefined;
						});
					});
				});
			},

			// Init HTML elements
			_initElts: function() {
				if (!this.stack && this.getInternal().stack.length > 1)
					this.elts = this.getInternal().stack[this.getInternal().stack.length-2]['nmObj'].elts;
				if (!this.elts.all || this.elts.all.closest('body').length == 0)
					this.elts.all = this.elts.bg = this.elts.cont = this.elts.hidden = this.elts.load = undefined;
				if (!this.elts.all)
					this.elts.all = $('<div />').appendTo(this.getInternal()._container);
				if (!this.elts.bg)
					this.elts.bg = $('<div />').hide().appendTo(this.elts.all);
				if (!this.elts.cont)
					this.elts.cont = $('<div />').hide().appendTo(this.elts.all);
				if (!this.elts.hidden)
					this.elts.hidden = $('<div />').hide().appendTo(this.elts.all);
				this.elts.hidden.empty();
				if (!this.elts.load)
					this.elts.load = $('<div />').hide().appendTo(this.elts.all);
				this._callFilters('initElts');
			},

			// Trigger the error
			// Will call 'error' callback filter
			_error: function() {
				this._callFilters('error');
			},

			// Set the HTML content to show.
			// - html: HTML content
			// - selector: selector to filter the content
			// Will init the size and call the 'size' function.
			// Will call 'filledContent' callback filter
			_setCont: function(html, selector) {
				if (selector) {
					var tmp = [],
						i = 0;
					// Looking for script to store them
					html = html
						.replace(/\r\n/gi, 'nyroModalLN')
						.replace(/<script(.|\s)*?\/script>/gi, function(x) {
								tmp[i] = x;
								return '<pre class=nyroModalScript rel="'+(i++)+'"></pre>';
							});
					var cur = $('<div>'+html+'</div>').find(selector);
					if (cur.length) {
						html = cur.html()
							.replace(/<pre class="?nyroModalScript"? rel="?(.?)"?><\/pre>/gi, function(x, y, z) { return tmp[y]; })
							.replace(/nyroModalLN/gi, "\r\n");
					} else {
						// selector not found
						this._error();
						return;
					}
				}
				this.elts.hidden
					.append(this._filterScripts(html))
					.prepend(this.header)
					.append(this.footer)
					.wrapInner('<div class="nyroModal'+ucfirst(this.loadFilter)+'" />');

				// Store the size of the element
				this.sizes.initW = this.sizes.w = this.elts.hidden.width();
				this.sizes.initH = this.sizes.h = this.elts.hidden.height();
				var outer = this.getInternal()._getOuter(this.elts.cont);
				this.sizes.hMargin = outer.h.total;
				this.sizes.wMargin = outer.w.total;

				this.size();

				this.loading = false;
				this._callFilters('filledContent');
				this._contentLoading();
			},

			// Filter an html content to remove the script[src] and store them appropriately if needed
			// - data: Data to filter
			_filterScripts: function(data) {
				if (typeof data != 'string')
					return data;

				this._scripts = [];
				this._scriptsShown = [];
				var start = 0,
					stStart = '<script',
					stEnd = '</script>',
					endLn = stEnd.length,
					pos,
					pos2,
					tmp;
				while ((pos = data.indexOf(stStart, start)) > -1) {
					pos2 = data.indexOf(stEnd)+endLn;
					tmp = $(data.substring(pos, pos2));
					if (!tmp.attr('src') || tmp.attr('rel') == 'forceLoad') {
						if (tmp.attr('rev') == 'shown')
							this._scriptsShown.push(tmp.get(0));
						else
							this._scripts.push(tmp.get(0));
					}
					data = data.substring(0, pos)+data.substr(pos2);
					start = pos;
				}
				return data;
			},

			// Check if the nmObject has a specific filter
			// - filter: Filter name
			_hasFilter: function(filter) {
				var ret = false;
				$.each(this.filters, function(i, f) {
					ret = ret || f == filter;
				});
				return ret;
			},

			// Remove a specific filter
			// - filter: Filter name
			_delFilter: function(filter) {
				this.filters = $.map(this.filters, function(v) {
					if (v != filter)
						return v;
				});
			},

			// Call a function against all active filters
			// - fct: Function name
			// return an array of all return of callbacks; keys are filters name
			_callFilters: function(fct) {
				this.getInternal()._debug(fct);
				var ret = [],
					self = this;
				$.each(this.filters, function(i, f) {
					ret[f] = self._callFilter(f, fct);
				});
				if (this.callbacks[fct] && $.isFunction(this.callbacks[fct]))
					this.callbacks[fct](this);
				return ret;
			},

			// Call a filter function for a specific filter
			// - f: Filter name
			// - fct: Function name
			// return the return of the callback
			_callFilter: function(f, fct) {
				if (_filters[f] && _filters[f][fct] && $.isFunction(_filters[f][fct]))
					return _filters[f][fct](this);
				return undefined;
			},

			// Call animation callback.
			// Will also call beforeNNN and afterNNN filter callbacks
			// - fct: Animation function name
			// - clb: Callback once the animation is done
			_callAnim: function(fct, clb) {
				this.getInternal()._debug(fct);
				this._callFilters('before'+ucfirst(fct));
				if (!this._animated) {
					this._animated = true;
					if (!$.isFunction(clb)) clb = $.noop;
					var set = this.anim[fct] || this.anim.def || 'basic';
					if (!_animations[set] || !_animations[set][fct] || !$.isFunction(_animations[set][fct]))
						set = 'basic';
					_animations[set][fct](this, $.proxy(function() {
							this._animated = false;
							this._callFilters('after'+ucfirst(fct));
							clb();
						}, this));
				}
			},

			// Load the content
			// Will call the 'load' function of the filter specified in the loadFilter parameter
			_load: function() {
				this.getInternal()._debug('_load');
				if (!this.loading && this.loadFilter) {
					this.loading = true;
					this._callFilter(this.loadFilter, 'load');
				}
			},

			// Show the content or the loading according to the current state of the modal
			_contentLoading: function() {
				if (!this._animated && this._bgReady) {
					if (!this._transition && this.elts.cont.html().length > 0)
						this._transition = true;
					this._nbContentLoading++;
					if (!this.loading) {
						if (!this._opened) {
							this._opened = true;
							if (this._transition) {
								var fct = $.proxy(function() {
									this._writeContent();
									this._callFilters('beforeShowCont');
									this._callAnim('hideTrans', $.proxy(function() {
										this._transition = false;
										this._callFilters('afterShowCont');
										this.elts.cont.append(this._scriptsShown);
										this._reposition();
									}, this));
								}, this);
								if (this._nbContentLoading == 1) {
									this._unreposition();
									this._callAnim('showTrans', fct);
								} else {
									fct();
								}
							} else {
								this._callAnim('hideLoad', $.proxy(function() {
									this._writeContent();
									this._callAnim('showCont', $.proxy(function() {
										this.elts.cont.append(this._scriptsShown);
										this._reposition();
									}, this));
								}, this));
							}
						}
					} else if (this._nbContentLoading == 1) {
						var outer = this.getInternal()._getOuter(this.elts.load);
						this.elts.load
							.css({
								position: 'fixed',
								top: (this.getInternal().fullSize.viewH - this.elts.load.height() - outer.h.margin)/2,
								left: (this.getInternal().fullSize.viewW - this.elts.load.width() - outer.w.margin)/2
							});
						if (this._transition) {
							this._unreposition();
							this._callAnim('showTrans', $.proxy(function() {
								this._contentLoading();
							}, this));
						} else {
							this._callAnim('showLoad', $.proxy(function() {
								this._contentLoading();
							}, this));
						}
					}
				}
			},

			// Write the content in the modal.
			// Content comes from the hidden div, scripts and eventually close button.
			_writeContent: function() {
				this.elts.cont
					.empty()
					.append(this.elts.hidden.contents())
					.append(this._scripts)
					.append(this.showCloseButton ? this.closeButton : '')
					.css({
						position: 'fixed',
						width: this.sizes.w,
						height: this.sizes.h,
						top: (this.getInternal().fullSize.viewH - this.sizes.h - this.sizes.hMargin)/2,
						left: (this.getInternal().fullSize.viewW - this.sizes.w - this.sizes.wMargin)/2
					});
			},

			// Reposition elements with a class nmReposition
			_reposition: function() {
				var elts = this.elts.cont.find('.nmReposition');
				if (elts.length) {
					var space = this.getInternal()._getSpaceReposition();
					elts.each(function() {
						var me = $(this),
							offset = me.offset();
						me.css({
							position: 'fixed',
							top: offset.top - space.top,
							left: offset.left - space.left
						});
					});
					this.elts.cont.after(elts);
				}
				this.elts.cont.css('overflow', 'auto');
				this._callFilters('afterReposition');
			},

			// Unreposition elements with a class nmReposition
			// Exaclty the reverse of the _reposition function
			_unreposition: function() {
				this.elts.cont.css('overflow', '');
				var elts = this.elts.all.find('.nmReposition');
				if (elts.length)
					this.elts.cont.append(elts.removeAttr('style'));
				this._callFilters('afterUnreposition');
			}
		},
		_internal = {
			firstInit: true,
			debug: false,
			stack: [],
			fullSize: {
				w: 0,
				h: 0,
				wW: 0,
				wH: 0,
				viewW: 0,
				viewH: 0
			},
			nyroModal: function(opts, fullObj) {
				if (_internal.firstInit) {
					_internal._container = $('<div />').appendTo($b);
					$w.smartresize($.proxy(_internal._resize, _internal));
					$d.bind('keydown.nyroModal', $.proxy(_internal._keyHandler, _internal));
					_internal._calculateFullSize();
					_internal.firstInit = false;
				}
				return this.nmInit(opts, fullObj).each(function() {
					_internal._init($(this).data('nmObj'));
				});
			},
			nmInit: function(opts, fullObj) {
				return this.each(function() {
					var me = $(this);
					if (fullObj)
						me.data('nmObj', $.extend(true, {opener: me}, opts));
					else
						me.data('nmObj',
							me.data('nmObj')
								? $.extend(true, me.data('nmObj'), opts)
								: $.extend(true, {opener: me}, _nmObj, opts));
				});
			},
			nmCall: function() {
				return this.trigger('nyroModal');
			},

			nmManual: function(url, opts) {
				$('<a href="'+url+'"></a>').nyroModal(opts).trigger('nyroModal');
			},
			nmData: function(data, opts) {
				this.nmManual('#', $.extend({data: data}, opts));
			},
			nmObj: function(opts) {
				$.extend(true, _nmObj, opts);
			},
			nmInternal: function(opts) {
				$.extend(true, _internal, opts);
			},
			nmAnims: function(opts) {
				$.extend(true, _animations, opts);
			},
			nmFilters: function(opts) {
				$.extend(true, _filters, opts);
			},
			nmTop: function() {
				if (_internal.stack.length)
					return _internal.stack[_internal.stack.length-1]['nmObj'];
				return undefined;
			},

			_debug: function(msg) {
				if (this.debug && window.console && window.console.log)
					window.console.log(msg);
			},

			_container: undefined,

			_init: function(nm) {
				nm.filters = [];
				$.each(_filters, function(f, obj) {
					if (obj.is && $.isFunction(obj.is) && obj.is(nm)) {
						nm.filters.push(f);
					}
				});
				nm._callFilters('initFilters');
				nm._callFilters('init');
				nm.opener
					.unbind('nyroModal.nyroModal nmClose.nyroModal nmResize.nyroModal')
					.bind({
						'nyroModal.nyroModal': 	function(e) { nm.open(); return false;},
						'nmClose.nyroModal': 	function() { nm.close(); return false;},
						'nmResize.nyroModal': 	function() { nm.resize(); return false;}
					});
			},

			_scrollWidth: (function() {
				var scrollbarWidth;
				if ($.browser.msie) {
					var $textarea1 = $('<textarea cols="10" rows="2"></textarea>')
							.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo($b),
						$textarea2 = $('<textarea cols="10" rows="2" style="overflow: hidden;"></textarea>')
							.css({ position: 'absolute', top: -1000, left: -1000 }).appendTo($b);
					scrollbarWidth = $textarea1.width() - $textarea2.width();
					$textarea1.add($textarea2).remove();
				} else {
					var $div = $('<div />')
						.css({ width: 100, height: 100, overflow: 'auto', position: 'absolute', top: -1000, left: -1000 })
						.prependTo($b).append('<div />').find('div')
							.css({ width: '100%', height: 200 });
					scrollbarWidth = 100 - $div.width();
					$div.parent().remove();
				}
				return scrollbarWidth;
			})(),

			_selNyroModal: function(obj) {
				return $(obj).data('nmObj') ? true : false;
			},

			_selNyroModalOpen: function(obj) {
				var me = $(obj);
				return me.data('nmObj') ? me.data('nmObj')._open : false;
			},

			_keyHandler: function(e) {
				var nmTop = $.nmTop();
				if (nmTop && nmTop.useKeyHandler) {
					return nmTop.keyHandle(e);
				}
			},
			_pushStack: function(obj) {
				this.stack = $.map(this.stack, function(elA) {
					if (elA['nmOpener'] != obj.get(0))
						return elA;
				});
				this.stack.push({
					nmOpener: obj.get(0),
					nmObj: $(obj).data('nmObj')
				});
			},
			_removeStack: function(obj) {
				this.stack = $.map(this.stack, function(elA) {
					if (elA['nmOpener'] != obj.get(0))
						return elA;
				});
			},
			_resize: function() {
				var opens = $(':nmOpen').each(function() {
					$(this).data('nmObj')._unreposition();
				});
				this._calculateFullSize();
				opens.trigger('nmResize');
			},
			_calculateFullSize: function() {
				this.fullSize = {
					w: $d.width(),
					h: $d.height(),
					wW: $w.width(),
					wH: $w.height()
				};
				this.fullSize.viewW = Math.min(this.fullSize.w, this.fullSize.wW);
				this.fullSize.viewH = Math.min(this.fullSize.h, this.fullSize.wH);
			},
			_getCurCSS: function(elm, name) {
				var ret = parseInt($.curCSS(elm, name, true));
				return isNaN(ret) ? 0 : ret;
			},
			_getOuter: function(elm) {
				elm = elm.get(0);
				var ret = {
					h: {
						margin: this._getCurCSS(elm, 'marginTop') + this._getCurCSS(elm, 'marginBottom'),
						border: this._getCurCSS(elm, 'borderTopWidth') + this._getCurCSS(elm, 'borderBottomWidth'),
						padding: this._getCurCSS(elm, 'paddingTop') + this._getCurCSS(elm, 'paddingBottom')
					},
					w: {
						margin: this._getCurCSS(elm, 'marginLeft') + this._getCurCSS(elm, 'marginRight'),
						border: this._getCurCSS(elm, 'borderLeftWidth') + this._getCurCSS(elm, 'borderRightWidth'),
						padding: this._getCurCSS(elm, 'paddingLeft') + this._getCurCSS(elm, 'paddingRight')
					}
				};

				ret.h.outer = ret.h.margin + ret.h.border;
				ret.w.outer = ret.w.margin + ret.w.border;

				ret.h.inner = ret.h.padding + ret.h.border;
				ret.w.inner = ret.w.padding + ret.w.border;

				ret.h.total = ret.h.outer + ret.h.padding;
				ret.w.total = ret.w.outer + ret.w.padding;

				return ret;
			},
			_getSpaceReposition: function() {
				var	outer = this._getOuter($b),
					ie7 = $.browser.msie && $.browser.version < 8 && !(screen.height <= $w.height()+23);
				return {
					top: $w.scrollTop() - (!ie7 ? outer.h.border / 2 : 0),
					left: $w.scrollLeft() - (!ie7 ? outer.w.border / 2 : 0)
				};
			},

			_getHash: function(url) {
				if (typeof url == 'string') {
					var hashPos = url.indexOf('#');
					if (hashPos > -1)
						return url.substring(hashPos);
				}
				return '';
			},
			_extractUrl: function(url) {
				var ret = {
					url: undefined,
					sel: undefined
				};

				if (url) {
					var hash = this._getHash(url),
						hashLoc = this._getHash(window.location.href),
						curLoc = window.location.href.substring(0, window.location.href.length - hashLoc.length),
						req = url.substring(0, url.length - hash.length);
					ret.sel = hash;
					if (req != curLoc && req != baseHref)
						ret.url = req;
				}
				return ret;
			}
		},
		_animations = {
			basic: {
				showBg: function(nm, clb) {
					nm.elts.bg.css({opacity: 0.7}).show();
					clb();
				},
				hideBg: function(nm, clb) {
					nm.elts.bg.hide();
					clb();
				},
				showLoad: function(nm, clb) {
					nm.elts.load.show();
					clb();
				},
				hideLoad: function(nm, clb) {
					nm.elts.load.hide();
					clb();
				},
				showCont: function(nm, clb) {
					nm.elts.cont.show();
					clb();
				},
				hideCont: function(nm, clb) {
					nm.elts.cont.hide();
					clb();
				},
				showTrans: function(nm, clb) {
					nm.elts.cont.hide();
					nm.elts.load.show();
					clb();
				},
				hideTrans: function(nm, clb) {
					nm.elts.cont.show();
					nm.elts.load.hide();
					clb();
				},
				resize: function(nm, clb) {
					nm.elts.cont.css({
						width: nm.sizes.w,
						height: nm.sizes.h,
						top: (nm.getInternal().fullSize.viewH - nm.sizes.h - nm.sizes.hMargin)/2,
						left: (nm.getInternal().fullSize.viewW - nm.sizes.w - nm.sizes.wMargin)/2
					});
					clb();
				}
			}
		},
		_filters = {
			basic: {
				is: function(nm) {
					return true;
				},
				init: function(nm) {
					if (nm.opener.attr('rev') == 'modal')
						nm.modal = true;
					if (nm.modal)
						nm.closeOnEscape = nm.closeOnClick = nm.showCloseButton = false;
					if (nm.closeOnEscape)
						nm.useKeyHandler = true;
				},
				initElts: function(nm) {
					nm.elts.bg.addClass('nyroModalBg');
					if (nm.closeOnClick)
						nm.elts.bg.unbind('click.nyroModal').bind('click.nyroModal', function(e) {
							e.preventDefault();
							nm.close();
						});
					nm.elts.cont.addClass('nyroModalCont');
					nm.elts.hidden.addClass('nyroModalCont nyroModalHidden');
					nm.elts.load.addClass('nyroModalCont nyroModalLoad');
				},
				error: function(nm) {
					nm.elts.hidden.addClass('nyroModalError');
					nm.elts.cont.addClass('nyroModalError');
					nm._setCont(nm.errorMsg);
				},
				beforeShowCont: function(nm) {
					nm.elts.cont
						.find('.nyroModal').each(function() {
							var cur = $(this);
							cur.nyroModal(nm.getForNewLinks(cur), true);
						}).end()
						.find('.nyroModalClose').bind('click.nyroModal', function(e) {
							e.preventDefault();
							nm.close();
						});
				},
				keyHandle: function(nm) {
					// used for escape key
					if (nm.keyEvent.keyCode == 27 && nm.closeOnEscape) {
						nm.keyEvent.preventDefault();
						nm.close();
					}
				}
			},

			custom: {
				is: function(nm) {
					return true;
				}
			}
		};

	// Add jQuery call fucntions
	$.fn.extend({
		nm: _internal.nyroModal,
		nyroModal: _internal.nyroModal,
		nmInit: _internal.nmInit,
		nmCall: _internal.nmCall
	});

	// Add global jQuery functions
	$.extend({
		nmManual: _internal.nmManual,
		nmData: _internal.nmData,
		nmObj: _internal.nmObj,
		nmInternal: _internal.nmInternal,
		nmAnims: _internal.nmAnims,
		nmFilters: _internal.nmFilters,
		nmTop: _internal.nmTop
	});

	// Add jQuery selectors
	$.expr[':'].nyroModal = $.expr[':'].nm = _internal._selNyroModal;
	$.expr[':'].nmOpen = _internal._selNyroModalOpen;
});

// Smartresize plugin
(function($,sr){

  // debouncing function from John Hann
  // http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
  var debounce = function (func, threshold, execAsap) {
      var timeout;

      return function debounced () {
          var obj = this, args = arguments;
          function delayed () {
              if (!execAsap)
                  func.apply(obj, args);
              timeout = null;
          };

          if (timeout)
              clearTimeout(timeout);
          else if (execAsap)
              func.apply(obj, args);

          timeout = setTimeout(delayed, threshold || 100);
      };
  };
	// smartresize
	jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };

})(jQuery,'smartresize');
// ucFirst
function ucfirst(str) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Onno Marsman
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: ucfirst('kevin van zonneveld');
    // *     returns 1: 'Kevin van zonneveld'
    str += '';
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}
// ** ==================================================================== ** //
/*
 * nyroModal v2.0.0
 * 
 * Link filter
 * 
 * Depends:
 * 
 * Before: filters.gallery
 */
jQuery(function($, undefined) {
	$.nmFilters({
		link: {
			is: function(nm) {
				var ret = nm.opener.is('[href]');
				if (ret)
					nm.store.link = nm.getInternal()._extractUrl(nm.opener.attr('href'));
				return ret;
			},
			init: function(nm) {
				nm.loadFilter = 'link';
				nm.opener.unbind('click.nyroModal').bind('click.nyroModal', function(e) {
					e.preventDefault();
					nm.opener.trigger('nyroModal');
				});
			},
			load: function(nm) {
				$.ajax({
					url: nm.store.link.url,
					data: nm.store.link.sel ? [{name: nm.selIndicator, value: nm.store.link.sel.substring(1)}] : undefined,
					success: function(data) {
						nm._setCont(data, nm.store.link.sel);
					},
					error: function() {
						nm._error();
					}
				});
			}
		}
	});
});
// ** ==================================================================== ** //
/*
 * nyroModal v2.0.0
 * 
 * Iframe filter
 * 
 * Depends:
 * - filters.link
 * 
 * Before: filters.formFile
 */
jQuery(function($, undefined) {
	$.nmFilters({
		iframe: {
			is: function(nm) {
				var	target = nm.opener.attr('target') || '',
					rel = nm.opener.attr('rel') || '',
					opener = nm.opener.get(0);
				return !nm._hasFilter('image') && (target.toLowerCase() == '_blank'
					|| rel.toLowerCase().indexOf('external') > -1
					|| (opener.hostname && opener.hostname.replace(/:\d*$/,'') != window.location.hostname.replace(/:\d*$/,'')));
			},
			init: function(nm) {
				nm.loadFilter = 'iframe';
			},
			load: function(nm) {
				nm.store.iframe = $('<iframe src="javascript:\'\';" id="nyromodal-iframe-'+(new Date().getTime())+'" frameborder="0"></iframe>');
				nm._setCont(nm.store.iframe);
			},
			afterShowCont: function(nm) {
				nm.store.iframe.attr('src', nm.opener.attr('href'));
			},
			close: function(nm) {
				if (nm.store.iframe) {
					nm.store.iframe.remove();
					nm.store.iframe = undefined;
					delete(nm.store.iframe);
				}
			}
		}
	});
});
// ** ==================================================================== ** //
/*
 * nyroModal v2.0.0
 * 
 * Iframe form filter
 * 
 * Depends:
 * - filters.iframe
 * 
 * Before: filters.iframe
 */
jQuery(function($, undefined) {
	$.nmFilters({
		iframeForm: {
			is: function(nm) {
				var ret = nm._hasFilter('iframe') && nm.opener.is('form');
				if (ret) {
					nm._delFilter('iframe');
					nm._delFilter('form');
				}
				return ret;
			},
			init: function(nm) {
				nm.loadFilter = 'iframeForm';
				nm.store.iframeFormLoading = false;
				nm.store.iframeFormOrgTarget = nm.opener.attr('target');
				nm.opener.unbind('submit.nyroModal').bind('submit.nyroModal', function(e) {
					if (!nm.store.iframeFormIframe) {
						e.preventDefault();
						nm.opener.trigger('nyroModal');
					} else {
						nm.store.iframeFormLoading = true;
					}
				});
			},
			load: function(nm) {
				nm.store.iframeFormIframe = $('<iframe name="nyroModalIframeForm" src="javascript:\'\';" id="nyromodal-iframe-'+(new Date().getTime())+'"></iframe>');
				nm._setCont(nm.store.iframeFormIframe);
			},
			afterShowCont: function(nm) {
				nm.opener
					.attr('target', 'nyroModalIframeForm')
					.submit();
			},
			close: function(nm) {
				nm.store.iframeFormOrgTarget ? nm.opener.attr('target', nm.store.iframeFormOrgTarget) : nm.opener.removeAttr('target');
				delete(nm.store.formFileLoading);
				delete(nm.store.iframeFormOrgTarget);
				if (nm.store.iframeFormIframe) {
					nm.store.iframeFormIframe.remove();
					nm.store.iframeFormIframe = undefined;
					delete(nm.store.iframeFormIframe);
				}
			}
		}
	});
});
