//FIXME - carousel doesnt hide all more infos when closing
( function( $ ) {
	$.fn.lazyLoad = function( options ) {
		return $( this ).each( function() {
			var $this = $( this );
			if( !$this.is( 'img' ) ) return;
			$this
				.attr( 'src', $this.attr( 'original-src' ) );
		} );
	},
	/* Simple Carousel */ 
	$.fn.multiModule = function( options ) {
		var $this = $( this );
		var out = $this;
		var cfg = {
			arrows: '<ul class="image_gallery_controls"> \
				<li class="next_button"><a href="#">Next Feature</a></li> \
				<li class="prev_button"><a href="#">Previous Feature</a></li> \
				</ul>',
			interval: '',
			fadeControls: true
		};
		$this.each( function() {
			var $container = $( this );
			
			// merge options with config
			var context = $container.data( 'multiModule-context' );
			if ( typeof context == "undefined" || context == null ) {
				context = $.extend( {}, cfg, options );
			} else {
				//update context
				context = $.extend( {}, context, options );
			}
			function init() {
				// add the dot nav and arrows
				$container
					.wrapAll( '<div class="gallery-wrapper"></div>' )
					.parent()
					.prepend( '<table border="0" cellspacing="0" cellpadding="0"><tr><td><div class="widthBullet"><div class="features-nav-wrapper"><div class="features-nav"></div></div></div></td></tr></table>' )
					.prepend( cfg.arrows )
				// make sure any moreInfo modules are closed up
					.end()
					.find( '.feature-more-info' )
					.hide();
				//do the cycle
				$container
					.cycle( {
						speed: 900,
						cleartype: true,
						timeout: 0,
						fx: 'scrollHorz',
						easeOut: 'swing',
						pager: $container.parent().find( '.features-nav' ),
						pagerAnchorBuilder: function ( idx, slide ) { 
							return '<div><a href="#">' + ( idx + 1 ) + '</a></div>'; 
						},
						prev: $container.parent().find( '.prev_button' ),
						next: $container.parent().find( '.next_button' )
					} );
				// move all but the first slide out of view
				$container
					.children( ':not( :first )' )
					.css( 'left', $container.width() + 'px' );
				// reposition the dots
				var $dots = $container
					.siblings( '.features-nav-wrapper' );
				$dots.css( 'left', 243 );
				// setup control fading -- this shouldn't be here...too specifc 
				if( context.fadeControls ) {
					$container
						.parent()
						.hoverIntent( {
							over: function() {
								$container
									.cycle( 'pause' )
									.parent()
									.find( '.image_gallery_controls li' )
									//.add( $container.parent().find( '.features-nav-wrapper' ) )
									.add( $container.find( '.feature-toggle-button' ) )
									.fadeIn( 'slow' );
							},
							out: function() {
								$container
									.cycle( 'resume' )
									.parent()
									.find( '.image_gallery_controls li' )
									//.add( $container.parent().find( '.features-nav-wrapper' ) )
									.add( $container.find( '.feature-toggle-button:visible' ) )
									.fadeOut( 'slow' );
								$container.find( '.feature-toggle-button:hidden' ).css( 'display', 'none' );
							}
						} );
					// hide all controls initially
					$container
						.find( '.image_gallery_controls li' )
						.add( '.features-nav-wrapper' )
						.hide();
				}
			}
			// run init
			init();
			// save context
			$container.data( 'multiModule-context', context );
		} );
		
		return out;
	};
	/* More info toggle */ 
	$.fn.moreInfo = function( options ) {
		var defaults = {
			expandHandler: function() {}, 
			collapseHandler: function() {},
			'$manager': null, // manager element - will pass all events to this if it's set rather than managing them itself
			'$button': null, // reference to the more/less info button
			'collapsed' : false,
			'button' : '<div class="feature-toggle-button">\
				<a href="#" /> \
				</div>', // template text
			'showText': 'Leer m\u00E1s',
			'hideText': 'Leer menos',
			//'buttonBottomOffset': 21.5,
			'hideInitially': true,
			'hideButton': true
		}
		var $this = $( this );
		var out = $this;
		$this.each( function() {
			var $this = $( this );
			// return if there's no info to show
			if( $this.children( '.feature-more-info' ).size() == 0 ) return;
			var context = $this.data( 'moreInfo-context' );
			if ( typeof context == "undefined" || context == null ) {
				context = $.extend( {}, defaults, options );
			} else {
				//update context
				context = $.extend( {}, context, options );
			}
			// unbind any past moreinfo events
			$this.unbind( '.moreInfo' );
			$this
				.bind( 'expand.moreInfo', function(){
					// run our bound handler - TODO make this make sense
					context.expandHandler.call( this );
					// now do the default actions
					var $this = $( this );
					$this
						.find( '.feature-more-info' )
						.css( { 'overflow': 'hidden', marginTop: 0, marginBottom: 0, paddingBottom: 0, paddingTop: 0 } )
						.animate( { height: 'show', paddingBottom: 8, paddingTop: 8 }, 400, 'swing', function() {
							$( this ).css( { paddingBottom: '', paddingTop: '', marginBottom: '', marginTop: '', overflow: '' } );
						} );
					// now update our button text
					$this
						.find( '.feature-toggle-button a' )
						.text( context.hideText );
					context.collapsed = false;
				} )
				.bind( 'collapse.moreInfo', function( e ) {
					// run our bound handler
					context.collapseHandler.call( this );
					var $this = $( this );
					if ( $this.find( '.feature-more-info' ).is( ':visible' ) ) {
						// if more info is currently visible, animate it out
						$this
							.find( '.feature-more-info' )
							.css( { 'overflow': 'hidden', marginTop: 0, marginBottom: 0 } )
							.animate( { height: 'hide', paddingBottom: 0, paddingTop: 0 }, 400, 'swing', function() {
								$( this ).css( {paddingBottom: '', paddingTop: '', marginBottom: '', marginTop: '', overflow: '' } );
							} );
					} else {
						// if it's not shown, just hide it
						$this
							.find( '.feature-more-info' )
							.hide();
					}
					// now update our button text
					$this
						.find( '.feature-toggle-button a' )
						.text( context.showText );
					context.collapsed = true;
				} );
				
			if( context.hideInitially ) {
				// hide the extra info
				$this
					.find( '.feature-more-info' )
					.hide();
				context.collapsed = true;
			}
			if( context.$button == null ) {
				addControl();
			} else {
				// update the position
				if(-14==$this.height() - context.buttonBottomOffset || 188==$this.height() - context.buttonBottomOffset || 190==$this.height() - context.buttonBottomOffset) {
					context.$button.css( 'top', 190 );
				}
			}
			
			// probably shouldn't be here... too specific
			if( context.hideButton ) {
				$this
					.hoverIntent( {
						over: function() {
							$this
								.find( '.feature-toggle-button' )
								.fadeIn( 'slow' );
						},
						out: function() {
							$this
								.find( '.feature-toggle-button' )
								.fadeOut( 'slow' );
							//$container.find( '.feature-toggle-button:hidden' ).css( 'display', 'none' );
						}
					} );
				$this
					.find( '.feature-toggle-button' )
						.hide();
			}
			function addControl()  {
				// add the more info button
				var $button = $( context.button )
					.find( 'a' )
					.text( context.showText )
					.bind( 'click.moreInfo', function() {
						var context = $( this ).parent().parent().data( 'moreInfo-context');
						if( context.$manager && context.$manager.not( $this ) ) {
							if( context.collapsed ) {
								context.$manager.triggerHandler( 'expand.multiMoreInfo' );
							} else {
								context.$manager.triggerHandler( 'collapse.multiMoreInfo' );
							}
						} else {
							if( context.collapsed ) {
								$this.triggerHandler( 'expand.moreInfo' );
							} else {
								$this.triggerHandler( 'collapse.moreInfo' );
							}
						}
						return false;
					} )
					.parent();
					//.css( 'top', $this.height() - context.buttonBottomOffset );
					
				$this
					.append( $button );
				context.$button = $button;
			}
			// save context 
			$this.data( 'moreInfo-context', context );
		} );
		
		return out;
	}
	// more Info manager - for managing moreInfo modules in a carousel
	$.fn.multiMoreInfo = function( options ) {
		var defaults = {
			$features: $(),
			$resizeParent: null,
			options: {
				fadeButtons: true,
				featuresSelector: '.feature',
				expandedHeight: null,
				collapsedHeight: null,
				resizeParent: true,
				featureOptions: {}
			}
		};
		var $this = $( this );		
		var out = $this;
		
		// add a feature to our managment 
		function addFeature( context, feature ) {
			// add the button to the feature
			context.$features = context.$features.add( 
				$( feature )
					.moreInfo( context.options.featureOptions )
					// unbind the mouseover/out handlers moreInfo sets so multiMoreInfo can manage it
					.unbind( "mouseover")
					.unbind( "mouseout" )
			);
		}
		// run this after all features are added
		function setResizeHeight( context ) {
			var $target = context.$resizeParent;
			context.options.collapsedHeight = context.options.expandedHeight = $target.height();
			context.$features.each( function() {
				// reset the managers expand height appropriately
				var $feature = $( this );
				var fDisplay = $feature.css( 'display' ),
					fmiDisplay = $feature.find( '.feature-more-info' ).css( 'display' )
					fmiPosition = $feature.find( '.feature-more-info' ).css( 'position' );
				var height = $feature
					.css( 'display', 'block' )
					.find( '.feature-more-info' )
					.css( { position: 'absolute',  display: 'block' } )
					.outerHeight();
				$feature
					.css( 'display', fDisplay )
					.find( '.feature-more-info' )
					.css( { position: fmiPosition,  display: fmiDisplay } );
				if( height + context.options.collapsedHeight > context.options.expandedHeight ) {
					context.options.expandedHeight = height + context.options.collapsedHeight;
				}
			} );
			
		}
		$this.each( function() {
			var $container = $( this );
			var context = $container.data( 'multiMoreInfo-context' );
			// merge options with config
			if ( typeof context == "undefined" || context == null ) {
				context = defaults;
				context.options = $.extend( {}, context.options, options );
				context.options.featureOptions['$manager'] = $container;
				if( typeof context.options.resizeParent == "object" ) {
					context.$resizeParent = context.options.resizeParent;
				} else if( context.options.resizeParent == defaults.options.resizeParent ) {
					context.$resizeParent = $container;
				}
				// set our initial heights unless they're already set
				context.options.collapsedHeight = context.options.collapsedHeight || $container.height();
				context.options.expandedHeight = context.options.collapsedHeight
				$container.data( 'multiMoreInfo-context', context );
			}
			if ( $container.find( context.options.featuresSelector ).size() == 0 ) {
				// if there's no features, what are you doing here? go, leave, get out of here
				return;
			}
			$container
				.find( context.options.featuresSelector )
				.each( function() {
					addFeature( context, $( this ) );
				} );
			// setup resize handlers
			setResizeHeight( context );
			$container
				.bind( 'collapse.multiMoreInfo', function() {
					var $this = $( this );
					var context = $container.data( 'multiMoreInfo-context' );
					context.$features.each(function() {
						$( this ).triggerHandler( 'collapse.moreInfo' );
					} );
					if( context.options.resizeParent ) {
						context.$resizeParent
							.animate( { height: 274 } );
						
					}
				} )
				.bind( 'expand.multiMoreInfo', function() {
					var $this = $( this );
					var context = $container.data( 'multiMoreInfo-context' );
					context.$features.each( function() {
						$( this ).triggerHandler( 'expand.moreInfo' );
					} );
					//expand this shit
					if( context.options.resizeParent ) {
						if( $.browser.name == "msie" ) {
							context.$features.height( context.options.expandedHeight );
						}
						context.$resizeParent
							//.children()
							// .parent()
							// .css( 'height', '' )
							// .end()
							.animate( { height: 342 } );
					}
				} );

		} );
		return out; 
	};
	
	/* Carousel with a fancy pager */
	$.fn.pampersCarousel = function( $$options ) {		
		var cfg = {
			arrows: '<ul class="image_gallery_controls"> \
				<li class="next_button_carousel"><a href="#">Next Feature</a></li> \
				<li class="prev_button_carousel"><a href="#">Previous Feature</a></li> \
				<li class="pause_button_carousel" id="pauseButton"><a href="#">Pause Feature</a></li> \
				</ul>',
			interval: '',
			fadeControls: true
		};
		
		function init( container ) {
			var $container = $( container ),
				context = {};
		
			var context = $container.data( 'pampersCarousel-context' );
			if ( typeof context == "undefined" || context == null ) {
				context = $.extend( {}, cfg, $$options );
			} else {
				//update context
				context = $.extend( {}, context, $$options );
			}

			addMarkup( $container );
			if( $container.children().size() <= 1 ) {
				// if there's only one element
				$container.parent().find( '.pampers-carousel-pager' ).remove();
				$container.parent().find( '.image_gallery_controls' ).remove();
				// if there's a feature we need to do a bit more
				$container.parent().addClass( 'pampers-carousel-single' );
				if( context.fadeControls ) {
					$container
						.parent()
						.hoverIntent( {
							over: function() {
								$container
									.cycle( 'pause' )
									.parent()
									// if there's a more info button, fade that shit in too
									.find( '.feature-toggle-button' )
									.fadeIn( 'slow' );
							},
							out: function() {
								$container
									.cycle( 'resume' )
									.parent()
									// if there's a more info button, fade that shit out too
									.find( '.feature-toggle-button' )
									.fadeOut( 'slow' );
							}
						} );
				}
				return;
			}
			context.$container = $container;
			context.$pager = $container.parent().find( '.pampers-carousel-pager' );
			
			$container.cycle( {
				//autostop: true,
				speed: 900,
				cleartype: 0,
				pager: context.$pager,
				updateActivePagerLink: function( pager, currSlide, activePagerClass ) {
					context.$pager.children( "." + activePagerClass ).removeClass( activePagerClass )
					var $curPager = context.$pager.children().eq( currSlide ).addClass( activePagerClass );
					if( ! $curPager.is( '.pampers-carousel-pager-item-open' ) ) {
						// find the open one and close it
						context.$pager.find( '.pampers-carousel-pager-item-open' )
							.trigger( 'closeUp' );
						// open this one
						$curPager.trigger( 'openUp' );
					}
				},
				pagerAnchorBuilder: function ( idx, slide ) { 
					return '<div class="pampers-carousel-pager-item">' +
						$( slide )
							.find( '.pampers-carousel-more-info' )
							.html() + 
						'</div>';
				},
				before: function( ) {
					
				},
				timeout: 4000,
				prev: $container.parent().find( '.prev_button_carousel' ),
				next: $container.parent().find( '.next_button_carousel' ),
				pause: true
			} );
			//remeasure things
			$container.height( '274px' );
			// setup control fading
			if( context.fadeControls ) {
				$container
					.parent()
					.hoverIntent( {
						over: function() {
							$container
								//.cycle( 'pause' )
								.parent()
								.find( '.image_gallery_controls li' )
								.fadeIn( 'slow' )
								.end()
								// if there's a more info button, fade that shit in too
								.find( '.feature-toggle-button' )
								.fadeIn( 'slow' );
						},
						out: function() {
							$container
								//.cycle( 'resume' )
								.parent()
								.find( '.image_gallery_controls li' )
								.fadeOut( 'slow' )
								// if there's a more info button, fade that shit out too
								.end()
								.find( '.feature-toggle-button' )
								.fadeOut( 'slow' );
								// if there are any more info buttons which are hidden, make sure THEY THEMSELVES are hidden, not just their parents
							$container
								.find( '.feature-toggle-button:hidden' )
								.css( 'display', 'none' );
						}
					} )
					.parent()
					.find( '.image_gallery_controls li' )
					.hide();
				}
			initPager( context );
		}
		function addMarkup( $container ) {
			// add the dot nav and arrows
			$container
				.wrapAll( '<div class="pampers-carousel-wrapper"></div>' )
				.parent()
				.prepend( cfg.arrows )
				.append( '<div class="pampers-carousel-pager"></div>' );
		}
		function initPager( context ) {
			var pagerCount = context.$pager.children().size();
			/*if ( pagerCount <= 3 ) {
				// center em
				var leftPadding = ( context.$container.width() - context.$pager.width() ) / 2 ;
				context.$pager
					.css( 'float', 'left' )
					.css( 'paddingLeft', (  leftPadding + 'px' ) )
					.css( 'float', 'none' );
					context.$pager
						.width( context.$container.width() - leftPadding  );
			} else {*/
				context.$pager.children().each( function() {
					$( this )
					.bind( 'closeUp.pampers-carousel', function ( e ) {
						e.stopPropagation();
						var $this = $( this );
						if( ! $this.data( 'pampersCarousel' ).collapsed ) {
							$this.data( 'pampersCarousel' ).collapsed = true;
							$this
								.removeClass( 'pampers-carousel-pager-item-open' )
								.find( 'a' )
								.stop()
								.animate( { width: 50 }, 400 );
						}
					} )
					.bind( 'openUp.pampers-carousel', function( e ) {
						e.stopPropagation();
						var $this = $( this );
						$this.data( 'pampersCarousel' ).collapsed = false;
						$this
							.addClass( 'pampers-carousel-pager-item-open' )
							.find( 'a' )
							.stop()
							.animate( { width: 250 }, 400 );
					} )
					.hoverIntent( {
						'over': function() {
							var $this = $( this );
							if( ! $this.is( '.pampers-carousel-pager-item-open' ) ) {
								// find the open one and close it
								context.$pager.find( '.pampers-carousel-pager-item-open' )
									.trigger( 'closeUp' );
								// open this one
								$this.trigger( 'openUp' );
							}
						},
						'out': function() {}
					} )
					.data( 'pampersCarousel', { 'collapsed': true, 'animating': false } )
					.find( 'a' )
					.width( '50px' );
				} )
				.filter( ':first' )
				.data( 'pampersCarousel', { 'collapsed': false } )
				.addClass( 'pampers-carousel-pager-item-open' )
				.find( 'a' )
				.width( '250px' );
				
				// center em
				var leftPadding = ( context.$container.width() - context.$pager.width() ) / 2 ;
				context.$pager
					.css( 'float', 'left' )
					.css( 'paddingLeft', (  leftPadding + 'px' ) )
					.css( 'float', 'none' );
					context.$pager
						.width( context.$container.width() - leftPadding  );
			//}
		}
		return $( this ).each( function() {
			init( this );
		} );
	};
	// initilizations 
	$( document ).ready( function () {
		$( '.feature ' )
			.moreInfo( { 'hideButton': $.browser.name != "msie" } );
		$( '.multiFeature' )
			.multiModule( { 'fadeControls': $.browser.name != "msie" })
			.multiMoreInfo( {
				featureOptions: {
					'hideButton': $.browser.name != "msie"
				}
		} );
		// only run it if the user doesn't have the correct version of flash installed
		if( swfobject.hasFlashPlayerVersion( '45.0.18' ) ) {
			// load the flash 

			// get rid of the markup
		} else {
				$( 'img[original-src]' ).lazyLoad();
				$( '.pampers-carousel' )
					.pampersCarousel( { fadeControls: $.browser.name != "msie" } ).each( function() {
						$( this )
							.multiMoreInfo( {
								resizeParent: $( this ).closest( '.pampers-carousel-wrapper' ).add( $( this ).closest( '.pampers-carousel' ) ),
								featureOptions: {
									'hideButton': $.browser.name != "msie",
									'buttonBottomOffset': 14
								}
						} )
					} );
		}
		$('#pauseButton').click(function() {
			var curControl = document.getElementById('pauseButton').className;
			if(curControl=='pause_button_carousel') {
				document.getElementById('pauseButton').className='play_button_carousel';
				$( '.pampers-carousel' ).each( function() {
					$( this ).cycle('pause');
				});
			} else {
				document.getElementById('pauseButton').className='pause_button_carousel';
				$( '.pampers-carousel' ).each( function() {
					$( this ).cycle('resume');
				});
			}
		});
	} ); //document ready
} )( jQuery );
