/*
Bones Scripts File
Author: Eddie Machado

This file should contain any js scripts you want to add to the site.
Instead of calling it in the header or throwing it inside wp-head()
this file will be called automatically in the footer so as not to 
slow the page load.

*/

// Modernizr.load loading the right scripts only if you need them
Modernizr.load([
	{
    // Let's see if we need to load selectivizr
    test : Modernizr.borderradius,
    // Modernizr.load loads selectivizr for IE6-8
    nope : ['selectivizr-min.js']
	}
]);

/* imgsizer (flexible images for fluid sites) */
/*var imgSizer={Config:{imgCache:[],spacer:"/path/to/your/spacer.gif"},collate:function(aScope){var isOldIE=(document.all&&!window.opera&&!window.XDomainRequest)?1:0;if(isOldIE&&document.getElementsByTagName){var c=imgSizer;var imgCache=c.Config.imgCache;var images=(aScope&&aScope.length)?aScope:document.getElementsByTagName("img");for(var i=0;i<images.length;i++){images[i].origWidth=images[i].offsetWidth;images[i].origHeight=images[i].offsetHeight;imgCache.push(images[i]);c.ieAlpha(images[i]);images[i].style.width="100%";}
if(imgCache.length){c.resize(function(){for(var i=0;i<imgCache.length;i++){var ratio=(imgCache[i].offsetWidth/imgCache[i].origWidth);imgCache[i].style.height=(imgCache[i].origHeight*ratio)+"px";}});}}},ieAlpha:function(img){var c=imgSizer;if(img.oldSrc){img.src=img.oldSrc;}
var src=img.src;img.style.width=img.offsetWidth+"px";img.style.height=img.offsetHeight+"px";img.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='scale')"
img.oldSrc=src;img.src=c.Config.spacer;},resize:function(func){var oldonresize=window.onresize;if(typeof window.onresize!='function'){window.onresize=func;}else{window.onresize=function(){if(oldonresize){oldonresize();}
func();}}}}*/


// Meteor Slides variables
//var $j = jQuery.noConflict();
var $slidespeed = parseInt( meteorslidessettings.meteorslideshowspeed );
var $slidetimeout = parseInt( meteorslidessettings.meteorslideshowduration );
var $slideheight = parseInt( meteorslidessettings.meteorslideshowheight );
var $slidewidth = parseInt( meteorslidessettings.meteorslideshowwidth );
var $slidetransition = meteorslidessettings.meteorslideshowtransition;

// as the page loads, call these scripts
$(document).ready(function() {

	// Meteor Slides
	$('.meteor-slides').cycle({
		height: $slideheight,
		width: $slidewidth,
		fit: 1,
		fx: $slidetransition,
		speed: $slidespeed,
		timeout: $slidetimeout,
		pause: 1,
		prev: '#meteor-prev',
		next: '#meteor-next',
		pager: '#meteor-buttons',
		pagerEvent: 'click',
		cleartypeNoBg: 'true',
		slideExpr: '.mslide'
	});

	// Dynamic loading for models archive page
	/*var contentHeight = $( '#content' ).height();
	$( '.page-navigation a' ).live( 'click', function( e ) {
		e.preventDefault();
		var link = $( this ).attr( 'href' );
		$( '#content' ).height( contentHeight );
		$( '#main-wrapper' ).fadeOut( 100 ).load( link + ' #main', function() {
			$( '#main-wrapper' ).fadeIn( 100 );
		});
	});*/
	
	/* New accordion - adds classes automatically */
	var isTitle = true;
	jQuery( '.accordion' ).children().each( function() {
		jQuery( this ).css('height', jQuery( this ).height() );
		if ( isTitle ) jQuery( this ).addClass( "accordionButton" );
		else jQuery( this ).addClass( "accordionContent" );
		isTitle = !isTitle;
	});
	jQuery( '.accordion .accordionButton' ).click( function() {
		jQuery( '.accordion .accordionButton' ).removeClass( 'on' );
		jQuery( '.accordion .accordionContent' ).slideUp( 'normal' );
		if( jQuery( this ).next().is( ':hidden' ) == true ) {
			jQuery( this ).addClass( 'on' );
			jQuery( this ).next().slideDown( 'normal' );
		}
	});
	jQuery( '.accordion .accordionContent' ).hide();
	
	/* Show age in taxonomy filter */
	jQuery( 'ul#term-list-birth_year_cat li a' ).each( function( index ) {
		//alert( index + ': ' + $( this ).text() );
		var year = jQuery( this ).text();
		var todays_date = new Date();
		var current_year = todays_date.getFullYear();
		var approx_age = ( current_year - year );
		jQuery( this ).prepend( approx_age + " (" ).append( ")" );
	});
	// Change 'Year Of Birth' to 'Age'
	jQuery( "ul.taxonomy-drilldown-lists li a" ).contents().each( function() {
	    if( this.nodeType == 3 )
	        this.nodeValue = this.nodeValue.replace( "Year Of Birth", "Age" );
	});
		
	// Remove title attribute from images
	jQuery( 'img[title]' ).each( function() { jQuery( this ).removeAttr( 'title' ); });
	
	// Fancybox for the gallery
	jQuery("a.gallery-zoom").fancybox({
		'padding': 5,
		'titleShow': false
	});
	
	// Thumbnail fades for gallery
	$('.ngg-thumbnail img, .ngg-gallery-thumbnail img').opacityrollover({
		mouseOutOpacity:   1.0,
		mouseOverOpacity:  0.75,
		fadeSpeed:         'fast',
		exemptionSelector: '.selected'		
	});
	
	// Thumbnail fades for models
	$('.fade-image img').opacityrollover({
		mouseOutOpacity:   1.0,
		mouseOverOpacity:  0.75,
		fadeSpeed:         'fast',
		exemptionSelector: '.selected'	
	});
	
	// We only want these styles applied when javascript is enabled
	$('div.gallery-navigation').css({'width' : '270px', 'float' : 'right'});
	$('div.gallery-content').css('display', 'block');

	// Initially set opacity on thumbs and add
	// additional styling for hover effect on thumbs
	var onMouseOutOpacity = 0.75;
	$('#thumbs ul.thumbs li').opacityrollover({
		mouseOutOpacity:   onMouseOutOpacity,
		mouseOverOpacity:  1.0,
		fadeSpeed:         'fast',
		exemptionSelector: '.selected'
	});
	
	// Initialize Advanced Galleriffic Gallery
	var gallery = $('#thumbs').galleriffic({
		delay:                     2500,
		numThumbs:                 6,
		preloadAhead:              10,
		enableTopPager:            false,
		enableBottomPager:         true,
		maxPagesToShow:            8,
		imageContainerSel:         '#slideshow',
		controlsContainerSel:      '#controls',
		captionContainerSel:       '#caption',
		loadingContainerSel:       '#loading',
		renderSSControls:          false,
		renderNavControls:         false,
		playLinkText:              'Play Slideshow',
		pauseLinkText:             'Pause Slideshow',
		prevLinkText:              '&larr; Previous Photo',
		nextLinkText:              'Next Photo &rarr;',
		nextPageLinkText:          '&nbsp;',
		prevPageLinkText:          '&nbsp;',
		enableHistory:             false,
		autoStart:                 false,
		syncTransitions:           true,
		defaultTransitionDuration: 900,
		onSlideChange:             function(prevIndex, nextIndex) {
			// 'this' refers to the gallery, which is an extension of $('#thumbs')
			this.find('ul.thumbs').children()
				.eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
				.eq(nextIndex).fadeTo('fast', 1.0);
		},
		onPageTransitionOut:       function(callback) {
			this.fadeTo('fast', 0.0, callback);
		},
		onPageTransitionIn:        function() {
			this.fadeTo('fast', 1.0);
		},
		onTransitionIn:            function () {
			$("a.zoom").fancybox({
				'titleShow' : false,
				'padding' : 5,
				'overlayOpacity' : 0.6,
				'overlayColor' : '#000',
				'speedIn' : 500
			});
			$("span.image-wrapper").fadeTo('slow', 1.0);
		}
	});
	
	// VideoJS Fancybox integration
	$("a.fancyvideo").click(function () {
	
		var url = $(this).attr('name');

        $.fancybox({
            'padding': 0,
            'overlayOpacity': 0.6,
            'autoDimensions': false,
            'width': 640,
            'height': 480,
            'scrolling': 'no',
            'content': '<div class="video-js-box vim-css hu-css">' + 
        					'<video id="video_1" class="video-js" width="640" height="480" controls="controls" autoplay="autoplay" preload="auto" poster="/wp-content/themes/kidslondon/library/images/video-poster.png">' + 
        						'<source src="' + url + '" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\' />' + 
        						//'<source src="' + url + '" type=\'video/webm; codecs="vp8, vorbis"\' >' + 
        						//'<source src="' + url + '" type=\'video/ogg; codecs="theora, vorbis"\' />' + 
								/*'<!-- Flash Fallback. Make sure to keep the vjs-flash-fallback class. -->' +
								'<object id="flash_fallback_1" class="vjs-flash-fallback" width="640" height="480" type="application/x-shockwave-flash" data="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf">' + 
									'<param name="movie" value="http://releases.flowplayer.org/swf/flowplayer-3.2.1.swf" />' + 
									'<param name="allowfullscreen" value="true" />' + 
									'<param name="flashvars" value=\'config={"playlist":["/wp-content/themes/kidslondon/library/images/video-poster.png", {"url": "' + url + '","autoPlay":true,"autoBuffering":true}]}\' />' + 
									'<!-- Image Fallback. Typically the same as the poster image. -->' + 
									'<img src="/wp-content/themes/kidslondon/library/images/video-poster.png" width="640" height="480" alt="Poster Image" title="No video playback capabilities." />' + 
								'</object>' + */
        					'</video>' + 
        				'</div>',
            'onComplete': function () { $( "#fancybox-inner" ).css({ 'overflow': 'hidden' }); VideoJS.setupAllWhenReady(); },
            'onClosed': function () { $( "#fancybox-inner" ).empty(); }
        });
        
        return false;
        
    });
    
    // YouTube Fancybox Integration
    $("a.fancyvideo-youtube").click(function () {
    
    	var url = $(this).attr('href');
    	
    	$.fancybox({
			'titleShow' : false,
			'padding': 5,
			'overlayOpacity': 0.6,
			'autoDimensions': false,
			'href' : this.href.replace(new RegExp("watch\\?v=", "i"), 'v/'),
			'type' : 'swf',
			'swf' : {'wmode':'transparent','allowfullscreen':'true'}
		});
		
		return false;
		
	});
	
	/* Don't put any other scripts below here - they won't work... */
	
});

/* end of as page load scripts */

$(window).load(function () {

	// Fade stuff
	$( '#logo' ).fadeIn( 500 );
	$( '#billboard' ).fadeIn( 1000 );
	
	// Taxonomy drill-down menu
	$( '.taxonomy-drilldown-lists' ).fadeIn( 250 ).initMenu();
	
	// Remove stuff
	$( '*' ).removeClass( 'loading' );

});

