/**
* Bumpslide Portfolio Site
* 
* Requires jquery, jquery.cycle, jquery.masonry, jquery.onfontresize
* @author David Knape, http://bumpslide.com/
*/    
function BumpslideWork() {

    // constants
    var PORTFOLIO_DATA_URL = 'portfoliodata.json';
    var IMAGE_PATH_PREFIX = '/work/slir/w602-c16:9/work/';
    var THUMBNAIL_PATH_PATH = '/work/slir/w140-c16:9/work/';
    var DEFAULT_LINK_TITLE = 'Visit Site';
    
    var MONTHS = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    // project data
    var projects = [];
        
    var delayInt = -1;
    
    init();
    
    /**
     * Start
     */
    function init() 
    {    
        // wire up the "show more" links
        $('.showmore').click( toggleSectionContent ); 
                
        // attempt to avoid spam
         populateEmailLinks('.email_link', 'david', 'bumpslide.com');
         
         //console.log('loading portfolio data', PORTFOLIO_DATA_URL);
         // load portfolio data
        $.getJSON(PORTFOLIO_DATA_URL, handlePortfolioDataLoaded).error( handleAjaxError );
        
         //$(document).bind("fontresize", function (event, data) {
         	//masonify( 2 );
         //});
         
         
    }
        
    /**
    * populate email links dynamically
    */
    function populateEmailLinks(selector, alias, host) 
    {
        var eml=alias+'@'+host;
        var tmp="<a href='mailto:eml'>eml</a>";
        $(selector).append(tmp.replace(/eml/g, eml));  
        
    }
    
    function handleAjaxError(xhr) {
        console.log('Failed to load JSON. ' + xhr.statusText);
    }
    
    /**
     * Handle project data AJAX result
     */
    function handlePortfolioDataLoaded(data, status, jqXHR) 
    {
        //console.log('loaded');
        var project_list = data['projects'];
        
        // sort projects by date
        project_list.sort( 
            function(a,b){ 
                return (Number(a.created) > Number(b.created)) ? -1 : 1;
            }
        );
                
        // Clean up the project data and store in lookup table (this.projects)
        for(var n=0; n<project_list.length; n++) {        
            
            var p = project_list[n];            
            
            // convert line breaks to paragraphs in project description    
            p.description = p.description.replace(/(\n)/g, '</p><p>'); 
            
            // add thumbnail to screenshot slideshow
            p.screenshots.unshift( p.thumbnail );
                       
            // prepend base paths to thumbnail and screenshots
            p.thumbnail = THUMBNAIL_PATH_PATH + p.thumbnail;

            for( var i=0; i<p.screenshots.length; i++) {
                p.screenshots[i] = IMAGE_PATH_PREFIX + p.screenshots[i];
            }           
            
            if(p.link!=null && !p.link.title) {
                p.link.title = DEFAULT_LINK_TITLE;
            }
            
            // create a "formattedDate" property for display purposes
            var d = p.created.split('.');
            p.formattedDate = MONTHS[ Number(d[1]) ] + " " + d[0]; 
            
            // save to projects lookup table
            projects[ p.pid ] = p;
        }
        
        // hide loading indicator        
        $('#gallery .content').removeClass('loading');
        
        // create projects from the 'thumbTemplate'
        $('#thumbTemplate').tmpl( project_list ).appendTo( '#gallery .content');
        
        // reveal the projects
        n=0;
        $('.project').each( function() {
            $(this).delay( 75 * (n++) ).fadeIn( 250 );
            masonify(2); 
        } );
        
        
       setTimeout( postProcessProjects, 10 );
        
    }
    
    
    function postProcessProjects() {
        // assign click event handler for project thumbnails
        $('.project .thumb_link').click( openProject );
        
        // orangy image link highlights
        $('a img').parent().addClass('imageLink');
        $('a img').wrap('<div class="imageLinkBackground" />').wrap('<div class="imageLinkWrapper" />');

        
        
                
        var path_parts = document.location.href.split('#').shift().split('/work/');
        if(path_parts.length==2) {
            gotoProject( path_parts.pop().replace('/', '') );
        }
        
        // click to advance slideshow
        $('.slide').click( function() {
            $(this).parent().cycle('next');
        } );
        
        //doMasonify();
         
    }
        
    function gotoProject( name ) {
        //alert('goto project ' + name );
        for( var id in projects ) {
            //console.log( projects[id] );
            if(projects[id].path==name) {
                //console.log(' found ' + id );
                $('#project_'+id+' .thumb').each( openProject );
                return;
            }
        }
    }
       
    /**
     * Hide/show hidden content
     */
    function toggleSectionContent( event ) 
    {    
        // close any open projects when interacting with another section
        closeProjects();
        
        var section = $(this).data('section');
        
        // toggle the hidden content
        $('#content_'+section).toggle(300);
    }
    
    /**
     * Hide all open sections
     */
    function closeSectionContent() {
        $('div[id^="content_"]').hide();
    }
    
    /**
     * Close any open projects
     */
    function closeProjects( onComplete ) 
    {
        
        var projects = $('.open_project').length;
        
        
        
        var proj = $('.open_project')[0];
        
        
        
        var scope = this;
        
        if( proj==undefined ) {
            if(onComplete) return onComplete.call( scope );
            else return;
        }
        
        $('.project_data').clearQueue();
        
        clearInterval(delayInt);
        
        // back to first slide
        //$('.slideshow', proj).cycle(0);
        $('.slideshow', proj).cycle('destroy');
        
        // restore thumb src
        $('.thumb', proj).attr('src', $('.thumb', proj).data('src') );
        
        // hide  the project data
        $('.project_data', proj).slideUp(250, function () {
        
            // hide slideshow and restore thumbnail
            $('.slideshow', proj).hide();
             
            $('.thumb_link', proj).show();
            
            // trigger CSS transition
            delayInt = setTimeout( function() {
                
                $('.thumb').removeClass('expanded');
                
                clearInterval( delayInt );
                delayInt = setTimeout( function() {
                    //$(proj).css('float', 'left');
                    doMasonify();
                    if(onComplete) return onComplete.call( scope );
                    else return;
                }, 500);
                
            }, 10 );
            
                      
            
            
            
        });
    
        $(proj).removeClass('open_project');    
    }
    
    function openProject() {
        // hide page scrollbar while transitioning
        $('body').css('overflow', 'hidden');
        $('#gallery .content').css('overflow', 'hidden');
        // close any open sections
        closeSectionContent();
        
        var pid = $( this ).data('pid');
        // close other projects
        closeProjects( function() {
            doExpandProject( pid );
        });
    }
    
    
    
    function doExpandProject( project_id ) {
        
        var data = projects[ project_id ];
        var project_div = $('#project_'+project_id)[0];
        var project = $('#project_'+project_id);
        
        // set the open_project class for reference and CSS use
        project.addClass('open_project');
        
        var pos = project.position().left / $(document).width();
        
        project.css('float', pos > .5 ? 'right' : 'left' );
        
        // do css3 transition on thumb after setting src to that of first slide
        var th = $('.thumb', project_div);
        th.data('src', th.attr('src'));
        th.attr('src', $('.slide:first', project_div).data('src') );
        th.addClass('expanded'); 
        
        clearInterval( delayInt );
        
        // wait for css transition to finish
        delayInt = setTimeout( function() 
        {           
            // show the project data and slideshow
            $('.project_data', project_div).slideDown(400, function()
            {
            
                // restore scrollbar
                $('body').css('overflow', 'auto');  
                
                delayInt = setTimeout( function() {
            
                    // scroll to top of project
                    var top = project.offset().top - 14;            
                    $('html, body').animate({scrollTop: top},250); 
                    
                }, 250 );

                
                //doMasonify();
            }); 
            
            initSlideShow( project_div );
            
            
            //$('.closeButton').click( closeProjects );   
            //
                            
        }, 500 );
        
        masonify( 6 );
        //doMasonify();
                      
        
    }
    
    var masonInt = -1;
    var masonFrames = 0;
    
    function masonify( frames ) {
        clearInterval( masonInt );        
        masonFrames = frames;        
        masonInt = setInterval( doMasonify, 250 );
        //$('.project').css('float', 'auto');
    }
    
    function doMasonify() {
        //return;
        $('.thumb').removeAttr('style');
        $( '#gallery .content').masonry( { resizeable: false, animate: true, animationOptions: {
            duration: 250,
            queue: false
          }} );
        if(--masonFrames==0) {
            clearInterval( masonInt );
        }
        
    }
    
    function initSlideShow( project_div ) 
    {        
        // load images by populating slide src from data-src
        $('.slide', project_div ).each( function(index) {
            if( $(this).data('src')=='' ) {
                // remove empty images
                $(this).remove();
            } else {
                $(this).attr('src', $(this).data('src'));
            }
        } );        
           
        var slideshow_options = {
            speed: 500,
            timeout: 6000,
            fx: 'fade'
        };
               
        $('.slideshow', project_div).cycle(slideshow_options);
        $('.thumb_link', project_div).hide();
        $('.slideshow', project_div).show();     
        
        
//        $('.slideshow', project_div).touchwipe({
//                wipeLeft: function() {
//                    $('.slideshow', project_div).cycle("next");
//                },
//                wipeRight: function() {
//                    $('.slideshow', project_div).cycle("prev");
//                }
//            });       
    }



}
    
$( function(){ new BumpslideWork(); } );


/**
 * jQuery Plugin to obtain touch gestures from iPhone, iPod Touch and iPad, should also work with Android mobile phones (not tested yet!)
 * Common usage: wipe images (left and right to show the previous or next image)
 * 
 * @author Andreas Waltl, netCU Internetagentur (http://www.netcu.de)
 * @version 1.0 (15th July 2010)
 */
//(function($){$.fn.touchwipe=function(settings){var config={min_move_x:20,wipeLeft:function(){alert("left");},wipeRight:function(){alert("right");},preventDefaultEvents:true};if(settings)$.extend(config,settings);this.each(function(){var startX;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 dx=startX-x;if(Math.abs(dx)>=config.min_move_x){cancelTouch();if(dx>0){config.wipeLeft();}else{config.wipeRight();}}}}function onTouchStart(e){if(e.touches.length==1){startX=e.touches[0].pageX;isMoving=true;this.addEventListener('touchmove',onTouchMove,false);}}this.addEventListener('touchstart',onTouchStart,false);});return this;};})(jQuery);
