var repoTemplate = '<li class="repo"><h3><a href="${html_url}" title="${name}">${name}</a></h3>' 
					+ '<ul class="horizontal metadata"><li>${language}</li></ul>'
					+ '<p>${description}</p></li>',
	flickrResponse = null;
$( document ).ready( function( ) { 
	getPhotos( 7, 1 );
	$( '.slideshow' ).nivoSlider( { effect: 'boxRain' } );
	$( '#photostream li' ).bind( 'mouseenter mouseleave', function( e ) { 
		if( e.type === 'mouseenter' ) {
			$( e.currentTarget ).find( ' > .caption' ).fadeIn( 500 );
		} else {
			$( e.currentTarget ).find( ' > .caption' ).fadeOut( 500 );
		}
	} );
	$( '#photostream a.navigation' ).bind( 'click', function( e ) { 
		var obj = $( e.currentTarget ),
			goto = obj.data( 'current-page' ) + ( obj.is( '[rel=next]' ) ? 1 : -1 );
			e.preventDefault( ); 
			getPhotos( 7, goto ); 
			$( '#photostream a.navigation' ).data( 'current-page', goto );
	} );
	$.ajax( { 
		url: 'https://api.github.com/users/jyeung001/repos',
		type: 'GET',
		dataType: 'jsonp',
		success: function( response ) {
			var repos = response.data,
				container = $( '#repos ul' );
			for( var i = 0, repo; repo = repos[ i ]; i++ ) {
				container.append( $.tmpl( repoTemplate, repo ) );
			}
		}
	} );
} );

function jsonFlickrApi( response ) {
	flickrResponse = response;
};

function buildPhotoStream( collection ) {
	var imgTmpl = '<img src="http://farm${farm}.static.flickr.com/${server}/${id}_${secret}${size}.jpg" title="${title}" /><div class="caption">${title}</div>';
	$( '#photostream li:not(.container)' ).each( function( i ) { 
		var container = $( this ),
			photo = collection.photo[ i ];
		photo[ 'size' ] = container.is( '.c2, .c3' ) ? '_b' : '';
		$( this ).html( $.tmpl( imgTmpl, photo ) );
	} );
	if( collection.page === 1 ) {
		$( '#photostream a[rel=prev]' ).hide( );
		$( '#photostream a[rel=next]' ).show( );
	} else if( collection.page === collection.pages ) {
		$( '#photostream a[rel=prev]' ).show( );
		$( '#photostream a[rel=next]' ).hide( );
	} else {
		$( '#photostream a[rel=next]' ).show( );
		$( '#photostream a[rel=prev]' ).show( );
	}
};

function getPhotos( perPage, page ) {
	$.ajax( { 
		url: 'http://api.flickr.com/services/rest/',
		data: { method: 'flickr.people.getPublicPhotos',
				api_key: '97951d20ba537103a0a07e02b68e432c',
				user_id: '63666302@N00',
				per_page: perPage || 7, page: page || 1, format: 'json' },
		type: 'GET',
		dataType: 'jsonp',
		complete: function( e ) {
			if( flickrResponse.stat !== 'ok' ) {
				$( '#photostream' ).hide( );
			} else {
				buildPhotoStream( flickrResponse.photos );
			}
		}
	} );
};
