// global ajax options
$.ajaxSetup({
  type:"POST",
  dataType:"json"
});

function truncate(str,length,suffix) {
    if (str.length > length) str = str.substr(0, length)+suffix;
    return str;
}

function initBackgrounds() {
  // if (!$.browser.msie) {
    $("li.menu-item a.on")
      .before('<div class="background"></div>')
      .hover(showBackground, hideBackground)
      .removeClass('on');
  // };
}

function showBackground() {
  $(this).siblings(".background").stop(true, true).fadeIn(200, 'easeInQuad');
}

function hideBackground() {
  $(this).siblings(".background").stop(true, true).fadeOut(200, 'easeOutQuad');
}

function changePageClick(e) {
  e.preventDefault();
  
  if (!$(this).hasClass("off")) {
    var page = Number(this.href.match(/(\d+)$/).pop());
    changePage(page);
  }
}

function changePage(page) {
  page = Number(page); // sanitize
  var pages_array = $("#menu-nav").text().match(/(\d+) of (\d+)/);
  var curPage  = Number(pages_array[1]);
  var numPages = Number(pages_array[2]);
  
  // var curPage = Number($(".video-menu:visible").attr("id").match(/(\d+)$/).pop());
  // var numPages = Number($("#menu-nav").text().match(/\d+ of (\d+)/).pop());

  var dir = (page > curPage) ? "ltr" : "rtl";

  if ($("#menu-page-"+page).length == 0) {
    // make fake page
    var html = '<ul id="menu-page-'+page+'" class="video-menu clearfix">';
    for (var i=0; i<12; i++) {
      html += '<li class="menu-item grid_2';
      if (i % 6 == 0) html += ' alpha';
      if (i % 6 == 5) html += ' omega';
      html += '"><a href="#video" class="off"><img src="/img/video-thumbnail.png" alt="No Video Available" /><p>No Video</p></a></li>';
    }
    html += '</ul>';
    
    $("#slide-pane").append(html).children(":last").hide();
    
    // get page via AJAX
    var url = "/homepage/slide/"+(page-1);
    $.ajax({ 
      url:url,
      success:makePage
    });
  }
  
  var $elIn = $("#menu-page-"+page);
  var $elOut = $(".video-menu:visible");
  scrollPage($elIn, $elOut, dir);
  
  // update buttons
  $("#menu-nav li").each(function() {
    if ($(this).hasClass("prev")) {
      if (page > 1) {
        var url = $(this).children("a").attr("href").replace(/^(.*)(\d+)$/, "$1"+(page-1));
        $(this).children("a").attr("href", url).removeClass('off');
      } else {
        $(this).children("a").addClass('off');
      }
    } else if ($(this).hasClass("position")) {
      $(this).text(page+" of "+numPages);
    } else if ($(this).hasClass("next")) {
      if (page < numPages) {
        var url = $(this).children("a").attr("href").replace(/^(.*)(\d+)$/, "$1"+(page+1));
        $(this).children("a").attr("href", url).removeClass('off');
      } else {
        $(this).children("a").addClass('off');
      }
    }
  });
}

function makePage(data, success) {
  if (data.success == 1) {
    var page = Number(data.offset) + 1;
    $(data.data).each(function(i){
      $('#menu-page-'+page+' li:eq('+i+')')
        .attr("id", "thumbnail-"+this.id)
        .children("a")
          .attr("href", "#/"+this.id)
          .removeClass("off").addClass("on")
          .attr("title", "View "+this.title)
          .bind("click", changeVideo)
        .children("img")
          .attr("src", "/media/"+this.media+"/small")
          .attr("title", this.title)
        .next("p")
          .html(truncate(this.title, 25, ' &hellip;'));
          
        if ($("div.video:visible").attr("id").match(/\d+/).pop() == this.id) {
          $("#thumbnail-"+this.id+" a").addClass("selected");
        }
    });
    
    initBackgrounds();
  }
}

function changeVideo(e) {
  // e.preventDefault();
  
  if (!$(this).hasClass("off")) {
    var id = this.href.match(/(\d+)/).pop();
    loadVideo(id);
    
    // turn off next and prev buttons
    $("#video-nav a").addClass("off");
  } else {
    return false;
  }
}

function loadVideo(id) {
  var url = "/homepage/main/"+id;
  
  $.ajax({
    url:url,
    success:videoSuccess,
    error:videoError
  });
}

function videoSuccess(data, status) {
  if (data.success == 1) {
    
    // date time
    var date_time = data.data.disp_date.replace(/[^\d]*/g, '');
    
    // create new image object
    var html = '<div id="video-'+data.data.id+'" class="video '+date_time+'">';
    html += '<img src="/media/'+data.data.media+'/medium" alt="'+data.data.title+'" />';
    html += '</div>';
    
    $("#video-player").append(html);
    $("#play-video a").attr("href", '#/video/'+data.data.video);
    
    if ($("#loading").length > 0) {
      // fade out loading
      $("#loading").fadeOut(200, function() {
        // slide down then fade in
        $("#video-player").slideDown(300, function() {
          $("#video-"+data.data.id).hide().fadeIn(200);
          
          // find thumbnail
          setSelected(data.data.id);
        });
      }).remove();

    } else {
      var elOut = $("#video-player div.video:first");
      var elIn = $("#video-"+data.data.id);
      var dir = (date_time < elOut.attr("class").match(/\d+/).pop()) ? 'ltr' : 'rtl';

      // swap out old movie
      elOut.children('object').remove();
      
      // if there are any other divs, remove them
      $("#video-player>div.video").each(function() {
        if (this != elOut[0] && this != elIn[0]) {
          $(this).remove();
        }
      });
      
      // scroll and fade
      scrollVideo(elIn, elOut, dir);
    }
    
    // fade out the content
    $("#video-info").stop(true, true).fadeOut(300, function() {
      // set title, subtitle and body text
      $("#video-info h3").html(data.data.title);
      $("#video-info h4").html(data.data.subtitle);
      $("#body").html(data.data.body);
    }).fadeIn(300);
    
    // update next and last
    var prev = $("#video-nav li.prev a");
    if (data.prev) { 
      prev.attr("href", "#/"+data.prev.id)
        .attr("title", data.prev.title)
        .removeClass("off");
    
      preloadImage(data.prev.id);
    } else { 
      prev.attr("href", "#")
        .attr("title", "")
        .addClass("off");
    }
    
    var next = $("#video-nav li.next a");
    if (data.next) { 
      next.attr("href", "#/"+data.next.id)
        .attr("title", data.next.title)
        .removeClass("off");

      preloadImage(data.next.id);
    } else { 
      next.attr("href", "#")
        .attr("title", "")
        .addClass("off");
    }
    
    // Google Analytics
    pageTracker._trackPageview("/"+data.data.id);
  } else {
    videoError();
  }
}

function videoError() {
  if ($("#loading").length > 0) {
    $("#loading").fadeOut(300).remove();
  } else {
    $("#video-player").fadeOut(300);
    $("#video-info").fadeOut(300);
  }
  
  var error = '<div class="error hide">';
  error += '<p>The URL you supplied is invalid, please check you have not mis-typed the URL.</p>';
  error += '</div>';
  
  $("#main").append(error).find(".error").fadeIn(300);
}

function preloadImage(id) {
  var url = "/homepage/main/"+id;
  
  $.ajax({
    url:url,
    success:function(data, success) {
      if (data.success == 1) {
        var imgPre = new Image;
        imgPre.src = '/media/'+data.data.media+'/medium';
      }
    }
  });
}

function showVideo(e) {
  e.preventDefault();
  
  var vid = this.href.match(/\d+/).pop();
  var swf = "http://vimeo.com/moogaloop.swf?clip_id="+vid+"&server=vimeo.com&show_title=0&show_byline=0&show_portrait=0&fullscreen=1&autoplay=1&color=12a2b2";
  
  if ($.hasFlashPlayer) {
    $("div.video:visible").flash({
      swf: swf,
      width: 400,
      height: 224
    });
  } else {
    var html = '<div class="video-error">';
    html += '<h2>This content requires Flash</h2>';
    html += '<p>To view this content you need the latest version of the Adobe Flash Player.</p>';
    html += '<p class="caption"><a href="/go/getflashplayer">Download the free Flash Player now!</a></p>';
    html += '<a href="http://www.adobe.com/go/getflashplayer" class="noHover"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash Player" border="0" /></a></div>';
    
    $("div.video:visible").html(html);
  }
  
  // hide play button
  $(this).parent().hide();
}

function scrollPage($elIn, $elOut, dir) {
  var leftOut = (dir == "ltr") ? -200 : 200;
  var leftIn = (dir == "ltr") ? 200 : -200;
  
  var attrOut = new Object();
  attrOut.left = leftOut;
  if (!$.browser.msie) attrOut.opacity = 0;
  
  var attrIn = new Object();
  attrIn.left = 0;
  if (!$.browser.msie) attrIn.opacity = 1;
  
  $elOut.stop(true, true).animate(
    attrOut,
    600,
    'easeOutQuad',
    function() { $(this).hide(); }
  );
  
  $elIn.stop(true, true).show()
  .css({ "left": leftIn })
  .animate(
    attrIn,
    600,
    'easeOutQuad',
    function() {
      var vid_id = $("div.video:visible").attr("id").match(/\d+/).pop();
      if ($("#thumbnail-"+vid_id+":visible").length) {
        $("#thumbnail-"+vid_id+" a").addClass("selected");
      }
    }
  );
}

function scrollVideo($elIn, $elOut, dir) {
  var leftOut = (dir == "ltr") ? -50 : 50;
  var leftIn = (dir == "ltr") ? 50 : -50;
  
  $elOut.removeClass('selected').stop(true).animate(
    { left: leftOut, opacity: 0 },
    200,
    'easeOutQuad',
    function() { $(this).hide(); }
  );
  
  $elIn.addClass('selected').show()
  .css({ "left": leftIn })
  .animate(
    { left: 10, opacity: 1},
    200,
    'easeOutQuad',
    function() {
      $elOut.remove();
      
      var vid_id = this.id.match(/(\d+)$/).pop();
      setSelected(vid_id);
    }
  );
}

function showPlay(e) {
  if ($(".video:visible object").length == 0) {
    $("#play-video").fadeIn(200);
  }
}

function hidePlay(e) {
  $("#play-video").fadeOut(200);
}

function initVideo() {
  var id;

  if (window.location.hash.match(/\d+/) != null) {
    id = window.location.hash.match(/\d+/).pop();
  } else if (window.location.hash.length == 0) {
    id = $(".video-menu li:first").attr("id").match(/\d+/).pop();
  } else {
    videoError();
    return false;
  }
  
  loadVideo(id);
}

function setSelected (id) {
  // set selected in thumbnails
  $(".menu-item a").removeClass("selected");

  if ($("#thumbnail-"+id+":visible").length) {
    $("#thumbnail-"+id+" a").addClass("selected");
  } else if ($("#thumbnail-"+id).length) {
    // find thumbnail in existing page
    var page = $("#thumbnail-"+id).parent().attr("id").match(/(\d+)$/).pop();
    changePage(page);
  } else {
    // load new pages till find id
    findThumb(id, 1); // Number(maxPage)+1);
  }
}

function findThumb(id, page) {
  page = Number(page); // sanitize
  var numPages = Number($("#menu-nav").text().match(/\d+ of (\d+)/).pop());
  
  if (page <= numPages) {
    var url = "/homepage/slide/"+(page-1);
    $.ajax({ 
      url:url,
      success:function(data, status) {
        var found = false;
      
        $(data.data).each(function(){
          if (this.id == id) {
            changePage(page);
            found = true;
            return true;
          };
        });
    
        if (!found) {
          // recursive find
          findThumb(id, page+1);
        }
      }
    });
  }
}

$(document).ready(function() {
  $("#menu-nav a").bind('click', changePageClick);
  $("#video-nav a").bind('click', changeVideo);
  $("#video-player a").bind('click', showVideo);
  $(".video-menu a").bind('click', changeVideo);
  $("#video-player").hover(showPlay, hidePlay);
  initBackgrounds();
  initVideo();
  
  // ie png fix
  $(document).pngFix();
});