var g_width = 900 ;
var book ;
var img_path = "/assets/portfolio/gallery/";
// This will be the URL of the video you want to load
var videoUrl;
// This is the oEmbed endpoint for Vimeo (we're using JSON)
var endpoint = 'http://www.vimeo.com/api/oembed.json';
// Tell Vimeo what function to call
var callback = 'embedVideo';
// The URL will be put together
var vid_url;

// This function loads the data from Vimeo
function initVideoEmbed() {
    var js = document.createElement('script');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('src', vid_url);
    document.getElementsByTagName('head').item(0).appendChild(js);
}

// This function puts the video on the page
function embedVideo(video) {
    document.getElementById('video').innerHTML = unescape(video.html);
}

function InitSlideshow(){
    //load the first section
    $.getJSON('includes/'+book+'.php', startSlideshow);

    function startSlideshow(slides){
      /* server returns an array of slides which looks like this:
      {"images":
            [
                {"path":"BOOKNAME/1.jpg","width":"IMG WIDTH","height":"IMG HEIGHT","title":"IMG TITLE","caption":"IMG CAPTION"},
                {"path":"BOOKNAME/2.jpg","width":"IMG WIDTH","height":"IMG HEIGHT","title":"IMG TITLE","caption":"IMG CAPTION"},
                {"path":"BOOKNAME/3.jpg","width":"IMG WIDTH","height":"IMG HEIGHT","title":"IMG TITLE","caption":"IMG CAPTION"},
                ...
          ]
        }*/

        //display the total number of images and reset the current image
    var totalSlideCount = slides.images.length;
    $('div.book_count span.total').text(totalSlideCount);
    $('div.book_count span.curr').text('1');

    //clear out the slideshow and load the first image
    var firstSlide = slides.images.shift();
    var firstSlideNum = firstSlide['path'].split('/').pop().split('.');
    $('.slideshow_container').html('<div class="slideshow"><img src="'+img_path+firstSlide['path']+'" width="'+firstSlide['width']+'" height="'+firstSlide['height']+'" alt="'+firstSlideNum[0]+'" rel="'+firstSlide['caption']+'" /></div><!-- /#slideshow --><p id="caption"></p>');

    var $slideshow = $('.slideshow');

    // markup now contains only a single slide; before starting the slideshow we append one slide and prepend one slide (to account for prev/next behavior)
    var preSlide = slides.images.pop();
    var appSlide = slides.images.shift();
    var preSlideNum = preSlide['path'].split('/').pop().split('.');
    var appSlideNum = appSlide['path'].split('/').pop().split('.');

    $slideshow.prepend('<img src="'+img_path+preSlide['path']+'" width="'+preSlide['width']+'" height="'+preSlide['height']+'" alt="'+preSlideNum[0]+'" rel="'+preSlide['caption']+'" />');
    $slideshow.append('<img src="'+img_path+appSlide['path']+'" width="'+appSlide['width']+'" height="'+appSlide['height']+'" alt="'+appSlideNum[0]+'" rel="'+appSlide['caption']+'" />');

    // start slideshow
    $('.slideshow').cycle({
      fx: 'fade',
      startingSlide: 1, //start on the slide that was in the markup
      timeout:  0,
      speed:    500,
      after: UpdateCurr,
      prev:    '.prev',
      next:    '.next',
      before:   onBefore
    });

    function onBefore(curr, next, opts, fwd){
      // on Before arguments:
      //  curr == DOM element for the slide that is currently being displayed
      //  next == DOM element for the slide that is about to be displayed
      //  opts == slideshow options
      //  fwd  == true if cycling forward, false if cycling backward

      // on the first pass, addSlide is undefined (plugin hasn't yet created the fn yet)
      if (!opts.addSlide)
          return;

      // have we added all our slides?
      if (opts.slideCount == totalSlideCount)
          return;

      // shift or pop from our slide array
      var nextSlideSrc = fwd ? slides.images.shift() : slides.images.pop();
      var nextSlideNum = nextSlideSrc['path'].split('/').pop().split('.');

      // add our next slide
      opts.addSlide('<img src="'+img_path+nextSlideSrc['path']+'" width="'+nextSlideSrc['width']+'" height="'+nextSlideSrc['height']+'" alt="'+nextSlideNum[0]+'" rel="'+nextSlideSrc['caption']+'" />', fwd == false);
    };
  };
}

function UpdateCurr(){
    //update current image number
    var curr = $('.slideshow img:visible').attr('alt');
    curr = (curr < 10)?curr.replace('0',''):curr;
    $('div.book_count span.curr').text(curr);
    var rel = $('.slideshow img:visible').attr('rel');
    $('p#caption').text(rel);
    //resize navigation buttons
    var imgHeight = $('.slideshow img:visible').height();
    var imgTop = -1 * imgHeight + "px";
    var capTop = imgHeight + "px";
    $('p#caption').css('top',capTop);
    $('.slideshow_control .prev, .slideshow_control .next').height(imgHeight).css('top',imgTop)
}

$(document).ready(function(){

    //find the first book to load
    book = $('ul.nav ul li:first a').attr('rel');

    InitSlideshow();

    //change book in a section
    $('ul.nav ul li a').click(function(){
        $('ul.nav ul li a').removeClass('current');
        $(this).addClass('current');

        if($(this).hasClass('video')){
            if($('div#video').length == 0){
                //was somewhere else
                $('div.book_count, div.inner_image_container, div.slideshow_control, div#flight_path_videos').hide();
                $('div#flight_path_videos').after('<div id="video"></div>');
            }

            videoUrl = 'http://www.vimeo.com/' + $(this).attr('rel');
            vid_url = endpoint + '?url=' + encodeURIComponent(videoUrl) + '&callback=' + callback + '&width=900';
            initVideoEmbed();
        } else if($(this).attr('rel')){
            book = $(this).attr('rel');
            $('div.book_count, div.inner_image_container, div.slideshow_control').show();
            $('div#flight_path_videos').hide();
            $('div#video').remove();
            InitSlideshow();
            return false ;
        } else if($(this).hasClass('flightpath')){
            $('div.book_count, div.inner_image_container, div.slideshow_control').hide();
            $('div#video').remove();
            $('div#flight_path_videos').show();
            $('div#flight_path_videos div.intro_container').show();
            $('div#flight_path_videos div.video_nav').hide();
            $('div#flight_path_videos div.video_container').load('videos.html');
        }
        return false;
    });

    $('div#flight_path_videos a.show_videos').click(function(){
        $('div#flight_path_videos div.video_nav').hide();
        $('div#flight_path_videos div.intro_container').hide();
        $('div#flight_path_videos div.video_nav').show();
        return false;
    });

    $('div#flight_path_videos div.single_vid a.backlink').live('click', function(){
        $('div#flight_path_videos div.video_nav').show();
        $('div#flight_path_videos div.video_container').hide();
        return false;
    });

    $('div#flight_path_videos div.video_thumb a').click(function(){
        var rel = $(this).attr('rel');
        $('div#flight_path_videos div.video_nav').hide();
        $('div#flight_path_videos div.video_container div.single_vid').hide();
        $('div#flight_path_videos div.video_container div.'+rel).show();
        return false;
    });

    //show the new work section
    $('ul.nav li a.cat').click(function(){

        if($(this).hasClass('current')){
            return false;
        } else {
            $('ul.nav li a.cat').removeClass('current');
            $(this).addClass('current');

            $('ul.nav ul').animate({
                opacity: "hide",
                left: -100
            },{
                duration: 1100,
                easing: "easeOutElastic"
            });
            $(this).parent().find('ul').animate({
                opacity: "show",
                left: 27
            },{
                duration: 900,
                easing: "easeOutElastic"
            });
        }

        //$(this).parent().find('ul li:first a').addClass('current');

        return false ;
    });

    //open new work by default
    $('li.newwork ul').animate({
        opacity: "show",
        left: 27
    },{
        duration: 900,
        easing: "easeOutElastic"
    });

});
