// Setup variables
var currentMedia = null;
var slideshow = null;
var current_player = null;

// Callback for when the video player is created in the DOM
// Firefox will call this function once the player is shown(slide containing player is cycled to)
// IE6+7 call this function when the player is created in the DOM in descending order(player3,player2,player1)
function playerReady(obj) {}

// On player progress listener
function onPlayerProgress(obj) {
    // Get remaining time in video
    var timeRemaining = Math.round(obj.duration - obj.position);
    // If time remaning is equal to or less than 3 seconds
    if(timeRemaining <= 2) {
      // Tell slideshow to continue
      slideshow.cycle("resume");
      // Remove the player listener
      current_player.removeModelListener("TIME","onPlayerProgress");
    }  
}

$(function(){
  
  // Create video player function, pass an object with required attributes
  function createPlayer(obj) {
    // Instantiate our new SWFobject video player
    var player = new SWFObject('/media/swf/player.swf',obj.playerid,'700','450','9','000000');
    // Set parameters for video player
    player.addParam('allowscriptaccess','always');
    player.addParam('wmode','opaque');
    player.addParam('type','youtube');
    // Set variables to pass to video player
    player.addVariable('skin','/media/swf/perth2011.swf');
    player.addVariable('autostart','false');
    player.addVariable('volume','50');
    player.addVariable('image',obj.image);
    player.addVariable('file',obj.url);
    // Write the video player to DOM
    player.write(obj.container);
  }
  
  // Slideshow before changing slide
  function slideshowBefore(current,next,options) {
    // Get index for current slide
    var index = options.currSlide;
    // Set current media to null during transition
    currentMedia = null;
    // Check if current player is set
    if(current_player != null) {
      // Stop current player and remove model listeners
      current_player.sendEvent("stop");
      current_player.removeModelListener("TIME","onPlayerProgress");
      // Set current player to null
      current_player = null;
    }
    // Hide caption
    $("#header_article").find(".caption").fadeOut(250);
  }
  
  // Slideshow after changing slide
  function slideshowAfter(current,next,options) {
    // Get index for current slide
    var index = options.currSlide;
    // Get slideshow link associated with this slide and set as active
    $(".viewer a").removeClass("active").eq(index).addClass("active");
    // Set current media relative to new slide
    currentMedia = slideshow.children("div").eq(index).attr("class");
    // Perform actions based on current media being shown
    if(currentMedia == "video") {
      // Hide the header
      $("#header_article .picture_title").find("h2").fadeOut();
      // Pause the slideshow
      slideshow.cycle('pause');
      // Set current player variable to this current slide player
      // Check what browser we are dealing with
      if(jQuery.support.htmlSerialize) {
        // Not IE
        current_player = slideshow.children("div").eq(index).find("embed")[0];
      } else {
        // IE
        current_player = slideshow.children("div").eq(index).find("object")[0];
      }
      // Set a timeout to allow player instantiate
      setTimeout(function(){
        // Set player listener and play
        current_player.addModelListener("TIME","onPlayerProgress");
        // Automatically play the video
        current_player.sendEvent("play");
      },1000);
    } else {
      // Show the header
      $("#header_article .picture_title").find("h2").fadeIn();
      // Show caption if available
      var imageCaption = $("#header_article").find(".viewer li").eq(index).find("img:first").attr("alt");
      if(imageCaption != "") {
        $("#header_article").find(".caption").text(imageCaption);
        $("#header_article").find(".caption").fadeIn(250);
      }
    }
  }
  
  // Setup slideshow
  $(".viewer").each(function(){
    // Hide slideshow
    $(this).hide();    
    // Find all the available items
    var items = $(this).find("li");    
    // Only add functionality if there is more than one item
    if(items.length > 1) {
      // Remove existing picture
      var picture = $(this).find(".main_picture").remove();
      // Set parent variable
      var parent = $(this).parent("div#header_article").find(".picture_title");
      // Set slideshow variable
      slideshow = parent.append("<div class=\"slide\"></div>").find("div.slide");
      // Remove default paragraphs from parent
      parent.find("p").remove();
      // Cycle through the items
      items.each(function(i,v){
        // Set easy to use variables
        var link = $(v).find("a");
        var image = $(v).find("img");
        // Find out if the item is a video or iamge
        var type = link.attr("href").search(/youtube/i) == -1 ? "image" : "video";
        // Set class based on type of media
        slideshow.append("<div class=\""+type+"\"></div>");
        // Perform actions based on which type of media is being usd
        if(type == "image") {
          // Create image
          slideshow.find("div:last").html("<img />").find("img").attr({src: link.attr("href"), alt: link.find("img").attr("alt")});
          // Create caption
          parent.prepend("<div class=\"caption\"></div>");
        } else {
          // Create container div for video player
          slideshow.find("div:last").html("<div id=\"player"+i+"\"></div>");
          // Create the video player
          createPlayer({
            container: "player"+i,
            image: image.attr("src"),
            playerid: "video"+i,
            url: link.attr("href")            
          });
        }
        // Set actions for when user clicks link
        link.click(function(){
          var index = $(".viewer a").index(this);
          slideshow.cycle(index);
          return false;
        })
      })
      // Show slideshow again
      $(this).show();
      // Add a class to the list viewer item
      $(this).find("li").removeClass("last");
      $(this).find("li:last").addClass("last");
      // Start slideshow if viewer is setup correctly
      slideshow.cycle({ pause: true, fx: 'fade', speed: 500, before: slideshowBefore, after: slideshowAfter });
    }
  })
  
  // Pause/Resume slideshow on over/off
  $("#header_article").hover(function(){
    if(currentMedia != "video") slideshow.cycle('pause');
  },function(){
    if(currentMedia != "video") slideshow.cycle('resume');
  })
})
/*
// Global Variables
var player = null;
var slideshow = null;
var parent = null;
var videoVisible = null;
var current_player = null;
var playTimeout = null;
var stopTimeout = null;
  
function stopCurrentPlayer() {
  current_player.sendEvent("STOP");
  current_player.removeModelListener("TIME","onTimeChange");
}

function playCurrentPlayer() {
  current_player.sendEvent("PLAY");
  current_player.addModelListener("TIME","onTimeChange");
}

// onTimeChange
// Performed each time event fires from player
function onTimeChange(obj) {
  if(current_player != null) {
    var remaining = Math.round(obj.duration - obj.position);
    if(remaining <= 3) {    
      // Events at end of video
      current_player.removeModelListener("TIME","onTimeChange");
      current_player.sendEvent("STOP");
      slideshow.cycle('resume');
    }
  }
}

$(function(){  
  // createPlayer
  // Used to create the video player. Make sure to pass the image, url, container id and player id
  function createPlayer(obj) {
    // Make sure we have what we need to go ahead
    if(obj.image && obj.url && obj.container && obj.playerid) {
      // Create the video player
      var so = new SWFObject('/media/swf/player.swf',obj.playerid,'700','450','9','000000');
      so.addParam('allowscriptaccess','always');
      so.addParam('wmode','opaque');
      // If no type is given then default to youtube. Have this here on odd chance we might want to stream a local .flv file
      if(obj.type) {
        so.addParam('type',obj.type);
      } else {
        so.addParam('type','youtube');
      }
      so.addVariable('skin','/media/swf/perth2011.swf');
      so.addVariable('autostart','false');
      so.addVariable('volume','50');
      so.addVariable('image',obj.image);
      so.addVariable('file',obj.url);
      so.write(obj.container);
    }
  }
  
  function onBefore(curr,next,opts) {
    clearTimeout(playTimeout);
    var index = opts.currSlide;
    var embed = $("#header_article .slide > div").eq(index).find("embed");
    if(embed.length > 0) {
      current_player = $("#"+embed.attr("id"))[0];
      var stopTimeout = setTimeout("stopCurrentPlayer()",500);
      videoVisible = false;
    } else {
      current_player = null;
    }
    $(".picture_title .caption").fadeOut(250);
  }
  
  function onAfter(curr,next,opts) {
    clearTimeout(stopTimeout);
    currentType = $(next).hasClass("video") ? "video" : "image";
    var index = opts.currSlide;
    $(".viewer a").removeClass("active").eq(index).addClass("active");
    if(currentType == "video") {
      // Hide header
      slideshow.siblings("h2").fadeOut();
      // Pause slideshow
      slideshow.cycle('pause');
      // Set player variable
      videoVisible = true;
      var embed = $("#header_article .slide > div").eq(index).find("embed");
      if(embed.length > 0) {
        current_player = $("#"+embed.attr("id"))[0];
        var playTimeout = setTimeout("playCurrentPlayer()",500);
      } else {
        current_player = null;
      }
    } else {
      // Show header
      slideshow.siblings("h2").fadeIn();
  	  if($(".viewer li a img").eq(index).attr("alt") != "") {
  	    $(".picture_title .caption").text($(".viewer li a img").eq(index).attr("alt"));
  	    $(".picture_title .caption").fadeIn(250);
      }
    }
  }
  
  $(".viewer").each(function(){    
    // Debugging line
    $(this).hide();
    
    // Find all the available items
    var items = $(this).find("li");
    
    // Only add functionality if there is more than one item
    if(items.length > 1) {
      // Remove existing picture    
      var picture = $(this).find(".main_picture").remove();
      
      // Set parent variable of picture title container
      parent = $(this).parent("div#header_article").find(".picture_title");      
      slideshow = parent.append("<div class='slide'></div>").find('div.slide');
      parent.find("p").remove();
      items.each(function(i,v){
        var link = $(v).find("a");
        var image = $(v).find("img");
        var type = link.attr("href").search(/youtube/i) == -1 ? "image" : "video";
        slideshow.append('<div class="'+type+'"></div>');
        if(type == "image") {
          slideshow.find('div:last').html('<img />').find('img').attr({ src: link.attr('href'), alt: link.find('img').attr('alt') });
        } else {
          slideshow.find('div:last').html('<div id="player'+i+'"></div>');
          createPlayer({
            container: "player"+i,
            playerid: "video"+i,
            url: link.attr('href'),
            image: image.attr('src')
          });
        }
        link.click(function(){
          videoVisible = false;
          var index = $(".viewer a").index(this);
          slideshow.cycle(index);
          return false;
        })
      })
      
      slideshow.cycle({
        pause: true,
        fx: 'fade',
        speed: 500,
        before: onBefore,
        after: onAfter
      });
      
      parent.parent().hover(function(){
        if(!videoVisible) slideshow.cycle('pause');
      },function(){
        if(!videoVisible) slideshow.cycle('resume');
      })
      
      items.removeClass("last");
      $(this).find("li:last").addClass("last");
    	
    	$(this).show();
    }
  })
})
*/