$(document).ready(function(){
  
  // HACK: Hide news scroller so it does not conflict with the lighbox video player
  // jquery li scroller seems to conflict with video.js
  // Only when lightbox opens the video player.
  if (VideoJS.isIE() && ($(".video-link").size() > 0)) {
    $("ul#news_scroller").hide(); 
  }
  
  // Initialize the scroller
/*  if ($("ul#news_scroller:visible").size() > 0) {
    $("ul#news_scroller").liScroll({travelocity: 0.03});  
  }
  */
  // Team profile pop up
  $("#team-profiles li").click(function(){
    
    $(this).siblings().find('div.profile-info').fadeOut();
    $(this).siblings().removeClass('selected');
    if ($(this).hasClass('selected')){
      $(this).removeClass('selected');
      $(this).find('div.profile-info').fadeOut();
    } else {
      $(this).addClass('selected');
      $(this).find('div.profile-info').fadeIn();
    }
    
    // center if position is more than 50% screen width
    
    if ( should_be_centered($(this))){
      var offset = Math.round(relative_offset($(this)));
      $("#slider").slider("value", offset);
      //console.log("should be centred");
      //console.log(offset);
    }
    
  });
  add_keypress_slide("#team-profiles");
  add_scrollbar("#team-profiles", true);
  move_slideable("#team-profiles", 0, true);
  var MIN_IMAGES_TO_REORG = 16;  
  //reorganise_images_and_add_scrollbar("ul.image-listing", MIN_IMAGES_TO_REORG);
  
  //$(".lightbox .images a").fancybox({cyclic: true, overlayOpacity: 0.6, overlayColor: '#000'});
  //$(".lightbox .audio .audio-link").fancybox({showCloseButton: false, overlayOpacity: 0.6, overlayColor: '#000'});
    
  //$('.audio .audio-player').each(function() {
    
    // Audio path found in the link within the .audio_player container
   // var audio_path = $(this).find("a").attr("href");
    
   // $(this).flash({ src: '/javascripts/player_mp3_maxi.swf', height: 20, width: 200, 
   //     flashvars: {movie: "player_mp3_maxi.swf", mp3: audio_path} });
    
 // });
  
  
  
  //Fancyplayer - flowplayer and fancybox integeration
  var videoclip;
	var player;
	var vidid;
	var captions;
	var capShow;
	var ccbutShow;
	var audioclip;
	var filetype;
	var cover;
	var isiPad = navigator.userAgent.match(/iPad/i) != null;
	$(".video_link").hover(function(){
		vidid = $(".video_link").index(this);
		videoclip = $(".video_link").eq(vidid).attr("name");
		cover = $(".video_link").eq(vidid).attr("href");
		videoclip = videoclip.replace(/ /g,"%20");
		videoclip = videoclip.replace("&","%26");
		filetype = videoclip.toString().substr(-3);
		if(filetype=="mp3") {
			rtmp="mp3:vod/aww.addictionww";
		} else {
			rtmp="mp4:vod/aww.addictionww";
		}
		audioclip = $(".video_link").eq(vidid).attr("href");
		
		if ($(".video_link").eq(vidid).hasClass('captions')) {
		captions = $(".video_link").eq(vidid).attr("name")+'.srt';
		capShow = true;
		ccbutShow = { width: 20, height: 15, right: 5, bottom: 32, label: 'SUBS' };
		} else { 
		captions = '/images/empty.srt';
		capShow = false;
		ccbutShow = null;
		}
	});
	
	$(".video_link").fancybox({
		'hideOnContentClick':false,
		'overlayOpacity' :.6,
		'zoomSpeedIn'    :400,
		'zoomSpeedOut'   :400,
		'easingIn'		 : 'easeOutBack',
		'easingOut'		 : 'easeInBack',
		
		'onComplete' :function(){
			
			if (videoclip == 'image') {				
				
				//$("#fancybox-right, #fancybox-left").css({height:$("#fancybox-inner").height(), bottom: '0'});
				
				} else {
					if(filetype=="mp3") {
						$("#fancybox-wrap").css({width:854,height:55});
						$("#fancybox-inner").css({width:834,height:35});
					} else {
						$("#fancybox-wrap").css({width:854,height:490});
						$("#fancybox-inner").css({width:834,height:470});
				}
				$.fancybox.center();
				if(!isiPad) {
				player = $f("fancybox-inner",{src: swfplayer, wmode: 'opaque'},{
							
				play:{opacity:0},
			  	key: '#@8efd2f533373bd7a07b',
				
				plugins: {
					
				
				/*captions: { 
					url: swfcaptions, 					 
					// pointer to a content plugin (see below) 
					captionTarget: 'content',
					showCaptions: capShow,
					button: ccbutShow
				},*/ 
				audio: {
					url:swfaudio
				},
				/* 
					configure a content plugin so that it  
					looks good for showing subtitles 
				*/ 
				content: { 
					url:swfcontent, 
					bottom: 25, 
					height:40, 
					backgroundColor: 'transparent', 
					backgroundGradient: 'none', 
					border: 0, 
					textDecoration: 'outline', 
					style: {  
						body: {  
							fontSize: 16,  
							fontFamily: 'Arial', 
							textAlign: 'center', 
							color: '#ffffff' 
						}  
					}  
				},
				
				controls:  {
				url: 'http://www.addictionworldwide.com/javascripts/flowplayer/flowplayer.controls-3.2.3.swf',
				backgroundColor: 'transparent',
				progressColor: 'transparent',
				bufferColor: 'transparent',
				all:false,
                                //fullscreen:true,
				scrubber:true,
				volume:true,
				mute:true,
				play:true,
				height:30,
				autoHide: 'always'		

				},
				
				rtmp: {
					url:swfrtmp,
					netConnectionUrl:'rtmp://r.aww.addictionww.netdna-cdn.com/play'
				}

				},
				canvas: {
					backgroundColor:'#000000',
					backgroundGradient: 'none'
				},
				clip:{
					autoPlay:true,
					autoBuffering:true,
					url:rtmp+videoclip+'',
					//captionUrl: videopath+captions+'', 
					urlEncoding: true,
					scaling: "fit",
					provider: "rtmp",
					onFinish:function(){
						$('#fancybox-close').trigger('click');
					}
				}
			});
				
			player.load();
			$('#fancybox-title').css('width','');
				}  else {
					/*$f("fancybox-inner",{src:swfplayer},{
						key: '#@a2ebb3896b2624c1bd7',
					clip:{
						url:videpath+videoclip+'',
						autoPlay:true,
						autoBuffering:true}}).ipad();
						/*player.ipad();*/
				}
		}
			
			$('#fancybox-right, #fancybox-right-ico').click(function(){
				vidid++;
				videoclip = $(".video_link").eq(vidid).attr("name");
				if ($(".video_link").eq(vidid).hasClass('captions')) {
				captions = $(".video_link").eq(vidid).attr("name")+'.srt';
				capShow = true;
				ccbutShow = { width: 20, height: 15, right: 5, bottom: 32, label: 'CC' };
				} else {
				captions = 'videos/empty.srt';
				capShow = false;
				ccbutShow = null;
				}
				//var itemHeight=$("#fancybox-inner").height();
				//$("#fancybox-right, #fancybox-left").css({height:itemHeight, bottom: '0'});
			});
			
			$('#fancybox-left, #fancybox-left-ico').click(function(){
				vidid--;
				videoclip = $(".video_link").eq(vidid).attr("name");
				if ($(".video_link").eq(vidid).hasClass('captions')) {
				captions = $(".video_link").eq(vidid).attr("name")+'.srt';
				capShow = true;
				ccbutShow = { width: 20, height: 15, right: 5, bottom: 32, label: 'SUBS' };
				} else {
				captions = 'videos/empty.srt';
				capShow = false;
				ccbutShow = null;
				}
				//$("#fancybox-right, #fancybox-left").css({height:$("#fancybox-inner").height(), bottom: '0'});
			});
		},
		'callbackOnClose':function(){
			$("#fancybox-content-api").remove();
		}
	});
  //Fancyplayer - end
  // Custom vertical scrollbars
  $("#content .floating-box .body-inner").jScrollPane({scrollbarWidth: 6, scrollbarMargin: 20});
  
  var linkLoc;
  $("body").css("display","none");
  $("body").fadeIn(100);
  
  $("#header ul li a").click(function(event){
	  event.preventDefault();
	  linkLoc=this.href;
	  $("body").fadeOut(100,redirectPage);
  });
  
  $("a.animated").click(function(event){
	  event.preventDefault();
	  linkLoc=this.href;
	  $("body").fadeOut(100,redirectPage);
  });
  
  function redirectPage(){
	  window.location=linkLoc;
  }
});







/* FUNCTIONS */ 

// Clean up - remove active, original area and overlay. Then show original
function reset_splash() {
  $("#splash .active").remove();
  $("#splash .original-area").remove();
  $("#splash-overlay").remove();

  $("#splash .original").removeClass("original").show();  
}

function reorganise_images_and_add_scrollbar(li_container_selector, min_images_to_reorg) {
  var num_portfolio_items = $(li_container_selector + " li").size();

  if (num_portfolio_items >= min_images_to_reorg) {  
    add_scrollbar(li_container_selector, false);
    readjust_li_container_width(li_container_selector);    
  }
}

// Add scrollbar if li container exists.
// NOTE: doesn't work properly when there is more than 1 li container that exists, which is not
// required at the moment.
//
// add_hover_nav boolean whether to show side hover navigation or not
function add_scrollbar(li_container_selector, add_hover_nav) {
  if ($(li_container_selector).size() > 0) {
    $("body").addClass("has_hori_scollbar");
    
    // Set width
    $(li_container_selector).width(function(){
      var items = $(this).find('li');
      return items.first().outerWidth(true) * items.size();
    });    
    
    // Add slider markup
    $(li_container_selector).after("<div id='slider-container'><div id='slider'></div></div>");
    
    
    // NOTE: slide/change includes keypress
    $("#slider").slider({
      slide: function(event, ui) {
        move_slideable(li_container_selector, ui.value, false);
      },
      change: function(event, ui) { 
        move_slideable(li_container_selector, ui.value, true);
      }
    });

    // mouswheel navigation  
    /* In order not to interfer with normal browser navigation, I'm disabling up/down scroll and only supporting horizontal scroll if user supports it.*/ 
    $('#team-profiles, #slider').live('mousewheel', function(event, delta, deltaX, deltaY){
      // Only use deltaY
      var selected = $('#team-profiles li.selected').eq(0);
      console.log(deltaX);
      if (deltaX < -5) previous_slide(li_container_selector, selected);
      else if(deltaX > 5 ) next_slide(li_container_selector, selected);
    });
    
    // Mouse hover navigations
    if (add_hover_nav) {
      var MAX_TIME_TO_ANIMATE = 8000;
      var li_container = $(li_container_selector);
      li_container.after("<div class='slider-hover-previous-wrapper'><a class='slider-hover-previous' href=''>Previous</a></div>");
      li_container.after("<div class='slider-hover-next-wrapper'><a class='slider-hover-next' href=''>Next</a></div>");

      $(".slider-hover-previous, .slider-hover-next").click(function() {
        return false;
      });
      $(".slider-hover-previous").hover(
        function() {
          // Faster if closer to the end (ie, the front of the list) - make it a consistent speed no matter where it is
          var time_to_move = (get_slideable_percent_moved(li_container_selector) / 100) * MAX_TIME_TO_ANIMATE;

          li_container.animate({left: 0}, time_to_move);
        },
        function() {
          li_container.stop();
          move_slider_to_container_proportion(li_container_selector);
        }
      );    
      $(".slider-hover-next").hover(
        function() {
          var total_width = get_slideable_total_width(li_container_selector);
          var left_value = -total_width;

          // Faster if closer to the end (ie, the end of the list) - make it a consistent speed no matter where it is
          var time_to_move = ((100 - get_slideable_percent_moved(li_container_selector)) / 100) * MAX_TIME_TO_ANIMATE;        
          li_container.animate({left: left_value}, time_to_move);                                 
        },
        function() {
          li_container.stop();
          move_slider_to_container_proportion(li_container_selector);
        }
      );
      $("img.bg").hover(function() {
        // Cancel scroll move if hovering on the background
        li_container.stop();
        move_slider_to_container_proportion(li_container_selector);
      });      
    }
  }
}

function move_slider_to_container_proportion(li_container_selector) {
  var current_left = Math.abs($(li_container_selector).position().left);

  var total_width = get_slideable_total_width(li_container_selector);
  // Proportion of current left value over total width (as a percentage out of 100)
  var left_proportion = (current_left / total_width) * 100;
  
  // Move scroll bar to the same proportion as the left proportion
  $("#slider").slider("value", left_proportion);  
}

// Readjust the li container so that there are only 3 rows (floating the li's makes it flow correctly)
function readjust_li_container_width(li_container_selector) {
  var num_portfolio_items = $(li_container_selector + " > li").size();
  
  // Find width of an li
  var li_width = $(li_container_selector + " > li").outerWidth(true);

  // If odd, take the last 3 items to put on the last row, otherwise, take the last 4
  var num_items_in_last_row = (num_portfolio_items % 2) ? 3 : 4;
  // Split the remainder into the top 2 rows, to find out the number of columns
  var num_cols = (num_portfolio_items - num_items_in_last_row) / 2;
      
  // Find out how wide the container has to be
  var container_width = li_width * num_cols;
  
  // Set width of container
  // console.log("li container width = " + container_width);
  $(li_container_selector).width(container_width);  
}

// Reorganise image listing to show with only 3 rows, if there are more images than min_images_to_reorg
function reorganise_image_listing(li_container_selector) {  
  var num_portfolio_items = $(li_container_selector + " > li").size();
  // console.log(num_portfolio_items);
  // If odd, take the last 3 items to put on the last row, otherwise, take the last 4
  var num_items_in_last_row = (num_portfolio_items % 2) ? 3 : 4;
  
  // Split the remainder into the top 2 rows, to find out the number of columns
  var num_cols = (num_portfolio_items - num_items_in_last_row) / 2;
  
  // console.log(num_cols);
  for (var i = 1; i <= num_cols; i = i + 1) { // NOTE: starts from 1
    // Move 2nd row li item to the 1st row li
    var first_row_item_sel = li_container_selector + " > li:nth-child(" + i + ")";
    var second_row_item_sel = li_container_selector + " > li:nth-child(" + (i + num_cols) + ")";
    $(first_row_item_sel).append($(second_row_item_sel).children());
    $(second_row_item_sel).addClass("to-remove"); // Flag it to be removed later
  
    // Add last row for all the columns with a last row
    if ((i >= 1) && (i <= num_items_in_last_row)) {
      var third_row_item_sel = li_container_selector + " > li:nth-child(" + (i + (num_cols * 2)) + ")";
      $(first_row_item_sel).append($(third_row_item_sel).children());
      $(third_row_item_sel).addClass("to-remove"); // Flag it to be removed later
    }
    //console.log(i + "/" + num_cols + ", " + $("ul.image-listing li:nth-child(" + i + ")").text());       
  }     
  // Clean up - remove all li's flagged to be removed
  $(li_container_selector + " li.to-remove").remove();
}

function add_keypress_slide(li_container_selector) {
  if ($(li_container_selector).size() > 0) {
    
    $(document).keydown(function(e) {
      var selected = $(li_container_selector + ' li.selected').eq(0);
      var ret = true;
      switch(e.keyCode){
        case 37: // left
        case 38: // up
          ret = previous_slide(li_container_selector, selected);
          break;
        case 39: // right
        case 40: // down
          ret = next_slide(li_container_selector, selected);
          break;
      }
      return ret; // returns true or false. true if we're at the last slide or first slide.
    });
  }
}

function previous_slide(li_container_selector, element){
  if(element.size() == 0){
    $(li_container_selector + ' li').eq(0).click();
  }else if(element.prev().size() > 0){
    element.prev().click();
  } else{
    return true;
  }
  return false;
}

function next_slide(li_container_selector, element){
  if(element.size() == 0){
    $(li_container_selector + ' li').eq(0).click();
  }
  else if(element.next().size() > 0){
    element.next().click();
  } else{
    return true;
  }
  return false;
}


function should_be_centered(element){
  var offset = element.offset().left;
  return offset > $(window).width()/2 || offset < 10;
}
function relative_offset(element){
  //console.log(element.index() + " - total: " + element.siblings().size());
  return (element.index() * 100 / element.siblings().size());
  // return element.position().left * 100 / element.offsetParent().width();
}

// Returns a percentage as a number eg, 10 = 10%
function get_slideable_percent_moved(li_container_selector) {
  var container = $(li_container_selector);
  var total_width = get_slideable_total_width(li_container_selector);
  var current_container_position = Math.abs(container.position().left);

  return (current_container_position / total_width) * 100;
}
function get_slideable_total_width(li_container_selector) {
  var container = $(li_container_selector);
  var total_width = (container.width() - ($(window).width()/2 + container.find('li').first().outerWidth()/2));

  return total_width;
}
function move_slideable(li_container_selector, value, animate) {
  var container = $(li_container_selector);

  var x = (
      container.width() - 
      ($(window).width()/2 + container.find('li').first().outerWidth()/2) 
      ) * value/100;
  x = Math.round(-x);

  if (animate) {
    $(li_container_selector).animate({left: x}, 500); 
  } else {
    $(li_container_selector).css('left', x);    
  }
  
}

