function Swf(){
  var mode = null
  
  var that = {
    init:function(){
      var attributes = {};
  		var flashvars = {};
  		var params = {};
      attributes.id = 'cyoa'
  		params.scale =  "noscale";
  		params.bgcolor = "#000000";
  		params.allowScriptAccess = "sameDomain";
      swfobject.embedSWF("cyoa.swf", "cyoa", "100%", "60", "9.0.0","", flashvars, params, attributes);
    },
    navigate:function(e){
      var path = ['cyoa']
      if (e.value != '/') path = e.value.slice(1).split("/")
      var newMode = path[0]
      if (newMode=='_') newMode = 'cyoa'

      var dt = 1000
      var newHeight
      var newPos = 'fixed'
      var newTitle = null
      if (newMode=='anim'){
        newHeight = 660
        newTitle = "cyoa · animations"
        newPos = 'absolute'
      }else if (newMode=='zork'){
        newHeight = 800
        newTitle = "cyoa · zork"
        newPos = 'absolute'
      }else if (newMode=='gallery'){
        newHeight = 106
      }else if (newMode=='cyoa' || newMode=='branches'){
        newHeight = 40
      }else{
        return
      }
      mode = newMode

      $("#cyoa").delay(dt, function(){
        if (newPos=='absolute') $.scrollTo(0, {axis:'y'})
        $("#cyoa").css('position',newPos)
        $("#cyoa").stop(true).height(newHeight)
        if (newTitle) $.address.title(newTitle)
      })
    }
  }

  that.init()
  $.address.change(that.navigate)
  return that
}

function Gallery(){
  var mode = null
  var info = null
  var current = null
  
  var that = {
    init:function(){
      $.getJSON("static/metadata.json",function(data){
        data.sort(function(a,b){
          if (a.year == b.year) return 0
          return (a.year < b.year) ? -1 : 1
        })
        info = data
        that.updateGallery()
      })

      // prevent clicks on the flash-requiring nav items from working
      // if flash isn't loaded. display a warning if so
      $("#nav > a[href='']").click(function(e){
        return false
      }).hover(function(e){
        // show warning
        $("#nav .warning").stop(true).show().animate({opacity:1}, 'slow')
      },function(e){
        // hide warning
        $("#nav .warning").stop(true).show().animate({opacity:0}, 'slow',
        function(){
          $(this).hide()
        })
      })
            
      // add the scroller-links to the js-based nav
      $("#gallery-nav .subnav > a").live('click', function(e){
        that.scrollto($(this).text())
        return false
      })

      $("#gallery-nav .controls > a").live('click', function(e){
        var incr = ($(this).text()=='prev') ? -1 : 1
        var next = current + incr
        next = Math.max(next, 0)
        next = Math.min(next, info.length-1)
        // console.log(info[next].file.slug)
        $.address.value('gallery/'+info[next].slug)
        // $.address.value('gallery/'+(next+1))
        return false
      })
    },
    scrollto:function(section){
      var elts = {'paths':'.arcs',
                  'data':'.cover',
                  'endings':'.tree',
                  'walkthrough':'.map'}
      var target = elts[section]
      if(!target) return
      
      var jumpSize = Math.abs($(window).scrollTop() - ($(target).position().top-20))
      $.scrollTo($(target), {duration:jumpSize, axis:'y', offset:{top:-110}})
    },
    updateGallery:function(){
      path = $.address.pathNames()
      var idx = 0
      if (path[1]!=undefined && path[1]!=''){
        for (var i in info) if (info[i].slug==path[1]) idx = Number(i)
      }
      if (info){
        if (mode=='gallery'){
          $.address.title("cyoa · "+info[idx].title.toLowerCase())
        }else{
          return
        }
        if (idx == current) return
        current = idx
        
        // scan of the book cover
        $(".cover").stop(true).animate({opacity:0}, 'slow', function(){

          // update the html nav title if flash didn't load
          $("#gallery-nav .title").html(info[idx].title+" by "+info[idx].author)

          // load then fade in the cover img
          var newCover = "<img><br>"+info[idx].serial+" <a target='book_details' href='"+info[idx].details+"' class='attrib'> view details</a></div>"
          $(".cover").html(newCover)          
          $('.cover img').attr('src', 'http://s3.amazonaws.com/cyoa/img/covers/'+info[idx].id+".jpg").load(function() {  
            $(".cover").show().animate({opacity:1}, 'slow')
          })
        })


        // the All The Paths view
        $(".arcs").stop(true).animate({opacity:0}, 'slow', function(){
          var basename = info[idx].slug
          var newArcs = "<img><br>ALL THE PATHS <a title='Paths to Catastrophic Endings' rel='"+basename+"' href='http://s3.amazonaws.com/cyoa/img/endings/"+basename+"-f.jpg' class='attrib'> readings broken down by ending</a></div>"
          var endings = {"d":"Paths to Disappointing Endings",
                         "c":"Paths to Mediocre Endings",
                         "b":"Paths to Favorable Endings",
                         "a":"Paths to Great Endings"}
          for (var grade in endings){
            newArcs += "<a title='"+endings[grade]+"' href='http://s3.amazonaws.com/cyoa/img/endings/"+basename+"-"+grade+".jpg' rel='"+basename+"' class='attrib'></a>"
          }
          
          $(".arcs").html(newArcs)
          $('.arcs img').attr('src', "http://s3.amazonaws.com/cyoa/img/arcs/"+basename+".png").load(function() {  
            $(".arcs").show().animate({opacity:1}, 'slow')
            $(".arcs > a").fancybox({hideOnContentClick:false})
          })
        })

        // the .cy-file listing of page transitions
        $(".pages").stop(true).show().animate({opacity:0}, 'slow', function(){
          var basename = info[idx].slug
          
          var newPages = "<img><br>ORIGINAL DATA <a target='_blank' href='"+info[idx].pagesLink+"' class='attrib'> "+info[idx].pages+"</a>"
          $(".pages").html(newPages)
          $('.pages img').attr('src', "http://s3.amazonaws.com/cyoa/img/pages/"+basename+".png").load(function() {  
            $(".pages").show().animate({opacity:1}, 'slow')
          })
        })

        // the force-directed graphs
        $(".tree").stop(true).show().animate({opacity:0}, 'slow', function(){
          var newTree = "<img><br>GAME TREE <a href='http://s3.amazonaws.com/cyoa/img/trees/_legend.png' class='attrib'> view legend</a>"
          $(".tree").html(newTree)
          $('.tree img').attr('src', "http://s3.amazonaws.com/cyoa/img/trees/"+info[idx].id+".png").load(function() {  
            $(".tree").show().animate({opacity:1}, 'slow')
            $(".tree a").fancybox()
          })
        })

        // the david sky drawing (if applicable)
        if (info[idx].hasOwnProperty('map')){
          $(".map").stop(true).animate({opacity:0}, 'slow', function(){
            var basename = info[idx].file.slug
              var newPages = "<img><br>WALKTHROUGH <a target='map' href='"+info[idx].mapLink+"' class='attrib'>"+info[idx].map+"</a>"
              $(".map").html(newPages)
              $('.map img').attr('src', "http://s3.amazonaws.com/cyoa/img/maps/"+info[idx].id+".jpg").load(function() {  
                $(".map").show().animate({opacity:1}, 'slow')
              })
          })
          
          // update the html nav if flash didn't load
          $("#gallery-nav .subnav a").eq(3).show()
        }else{
          $(".map").stop(true).animate({opacity:0}, 'slow', function(){
            $(".map").hide()
            $(".map").html("")
            $("#gallery-nav .subnav a").eq(3).hide()
          })
        }
      }
    },
    
    
    navigate:function(e){
      // console.log(e.value)
      var path = ['cyoa']
      if (e.value != '/') path = e.value.slice(1).split("/")
      var newMode = path[0]
      if (newMode=='_') newMode = 'cyoa'
      
      if (newMode == 'gallery'){
        var dt = (mode==null) ? 0 : 1000
        if (newMode != mode){
          $("#gallery").delay(dt, function(){
            $.scrollTo(0, {axis:'y'})
            $("#fader").show()
            $("#gallery").stop(true).show().animate({opacity:1}, 'slow')
          })
        }
        $("#gallery-nav").stop(true).show().animate({opacity:1}, 'slow')
        mode = newMode
        that.updateGallery()
        
      }else{
        mode = newMode
        $("#gallery-nav").stop(true).animate({opacity:0}, 'slow', function(){
          $(this).hide()
        })
        $("#gallery").stop(true).animate({opacity:0}, 'slow', function(){
          $('#gallery').hide()
          $('#fader').hide()
        })
      }
      

      
    }
  }

  $('#nav a').eq(2).attr('href','#/gallery')
  
  $.address.change(that.navigate)
  that.init()
  return that
}

function Doc(){
  var mode = null
  var hangline = 0 // remember where people were in the doc so we can return to it
  
  var that = {
    navigate:function(e){
      var path = ['cyoa']
      if (e.value != '/') path = e.value.slice(1).split("/")
      var newMode = path[0]
      if (newMode=='_') newMode = 'cyoa'
      if (newMode == mode) return
      
      if (newMode == 'cyoa'){
        $.address.title("cyoa")
        var dt = (mode==null) ? 0 : 1000
        $("#intro").delay(dt, function(){
          $("#intro").stop(true).show()
          $.scrollTo(hangline, {axis:'y'})
          $("#intro").animate({opacity:1}, 'slow')
        })
      }else{
        if (mode=='cyoa'){
          hangline = $(window).scrollTop()
        } 
        $("#intro").stop(true).animate({opacity:0}, 'slow', function(){
          $('#intro').hide()
        })
      }
      mode = newMode
      
    },    
    wink:function(){
      $("#intro > p > code").css('color','#bbb').delay(200, function(){
        $("#intro > p > code").css('color','#fff').delay(200, function(){
          $("#intro > p > code").css('color','#bbb').delay(200, function(){
            $("#intro > p > code").css('color','#fff')  
          })
        })
      })
    }
  }


  // init
  blinkenTimer = setInterval(that.wink, 30*1000)

  $(".colophon").fancybox({hideOnContentClick:false, 
    frameWidth:490,
    frameHeight:520,
    callbackOnStart:function(){$('body').css('overflow','hidden')},
    callbackOnClose:function(){$('body').css('overflow','scroll')}
  })      
  $("#intro").find('a[href^=http]').click(function(){
    window.open($(this).attr('href'))
    return false
  })
  $(".fn-popup a").live('click',function(){
    window.open($(this).attr('href'))
    return false
  })
  
  $(".zoomable").fancybox({hideOnContentClick:true, 
    callbackOnStart:function(){$('body').css('overflow','hidden')},
    callbackOnClose:function(){$('body').css('overflow','scroll')}
  })
  $(".footnote").fancybox({hideOnContentClick:false, 
    callbackOnStart:function(){$('body').css('overflow','hidden')},
    callbackOnClose:function(){$('body').css('overflow','scroll')}
  })

  $("#nav").stop(true).show().animate({opacity:1}, 'slow')
  $.address.change(that.navigate)
  return that
}

// Delay Plugin for jQuery
// - http://www.evanbot.com
// - © 2008 Evan Byrne
jQuery.fn.delay = function(time,func){
	this.each(function(){
		setTimeout(func,time);
	});
	
	return this;
};

$(document).ready(function(){
  swf = Swf()
  gal = Gallery()
  doc = Doc()
  // var branches = Branches()
  // branches.init()
})


/*function Branches(){
  var mode = null
  var init = false
  
  var that = {
    init:function(){
      if (init) return
      init = true
//      console.log('INIT')
      var attributes = {};
  		var flashvars = {};
  		var params = {};
      attributes.id = 'branches'
  		params.scale =  "noscale";
  		//params.bgcolor = "#a09f92";
      // params.wmode = "transparent";
      params.bgcolor = "#000000";
  		params.allowScriptAccess = "sameDomain";
      swfobject.embedSWF("branches.swf", "branches", "80%", "80%", "9.0.0","", flashvars, params, attributes);
    },
    navigate:function(e){
      var path = ['cyoa']
      if (e.value != '/') path = e.value.slice(1).split("/")
      var newMode = path[0]

      if (newMode == 'branches'){
        var dt = (mode==null) ? 0 : 1000
        that.init()
        $("#branches").delay(dt, function(){
          $("#branches").stop(true).show().animate({opacity:1}, 'slow')
        })
      }else{
        $("#branches").stop(true).animate({opacity:0}, 'slow', function(){
          $('#branches').hide()
        })
      }
      
      mode = newMode

    }
  }
  
  $.address.change(that.navigate)
  return that  
}
*/
