var CI = {
  slider: undefined,
  videos: [],
  add: function(item) {
    CI.videos.push(item);
    item.addEventListener('onStateChange', "onStateChange_listener");
  },
  play: function(index) {
    CI.videos[index].play();
  },
  stop: function() {
    for (var i=0; i < CI.videos.length; i++) {
      try { 
        CI.videos[i].stopVideo();
      } catch (e) {
        throw new Error(e);
      }
    };
  }
}

function onStateChange_listener(e) {
  if (e == 1) {
    CI.slider.stop();
  } 
  
  if (e == 0) {
    CI.slider.play();
  }
}

function onYouTubePlayerReady(playerId) {
 var video = document.getElementById(playerId); 
 CI.add(video);
}

$(document).ready(function() { 
    
  /*	video
	------------------------------------*/
	
	function setupFlash( el ) {
	  var video = $(el).text();
    var id =    $(el).attr('id');
    var params = { allowScriptAccess: "always", wmode: "opaque" };
    
    var unique_id = "player_" + id;
    var atts = { id: unique_id };
    
    swfobject.embedSWF("http://www.youtube.com/e/" + video + "?enablejsapi=1&version=3&rel=0&hd=1&wmode=opaque&showinfo=0&playerapiid=" + unique_id, id, "320", "240", "8", null, null, params, atts);
	}
	
	function setupHTML5( el ) {
	  $(el).html('<iframe width="320" height="240" src="http://www.youtube.com/embed/' + $(el).text() + '?rel=0&amp;hd=1&amp;wmode=opaque&showinfo=0&html5=1" frameborder="0" allowfullscreen></iframe>');
	}
  
  function setupVideo( el ) {
  
  	//console.log('setupVideo', el);
  
  	var id = el.attr('id') + String( Math.random() * 100 ).replace('.', '_');
		el.attr('id', id);
  
    if ( navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i) ) {
      setupHTML5( el );
    } else {
      setupFlash( el );
    }
  }
	
	/*	slider
	------------------------------------*/
	
	
	// initialize scrollable and return the programming API
	var api = $("#scroll").not('.no-scroll').scrollable({
		items: '#slides',
		circular: true,
		speed: 300,
		onBeforeSeek: function(){
		  var that = this;
		  $('#slides').fadeTo(100, 0);		  
		},
		onSeek: function(){
		  
		  var item = this.getItems()[this.getIndex()];
		  // console.log(item);
		  
		  if ( $(item).find('.youtube-video').length > 0 ) {
		    
		    var el = $(item).find('.youtube-video');
		    setupVideo(el);
		    
		  } else if ( $(item).find('.media').length == 0 ) {
		    CI.stop();
		  }
		  
		  $('#slides').fadeTo(200, 1);
		},
		easing: 'easeInOutExpo'
	})
	.autoscroll({ 
		autoplay: true,
		interval: 10000,
		autopause: true
	})	
	.navigator();
	
	CI.slider = api.data("scrollable");
	
	
	
	
	
	
	
	(function(){
        
        var Shifter = {
           nav: $('.navi'),
           thumbs: $('#thumbs'),
           index: 0
        };
        
        Shifter.navWidth = 0;
        
        Shifter.nav.find('li').each(function(){
            Shifter.navWidth += $(this).width();
        });
        
        Shifter.total = $('.navi li').length;
        
        Shifter.next = function() {
            
            var visible_width = 0;
            
            $('.navi li').each(function(i){
                if (i >= Shifter.index) {
                    visible_width += $(this).width();
                }
            });
            
            var margin = 0;
            
            $('.navi li').each(function(i){
                if (i <= Shifter.index) {
                    margin -= $(this).width();
                }
            });
            
            if (Shifter.thumbs.width() < visible_width) {
                this.nav.animate({
                    marginLeft: margin
                  }, 100, function() {
                      Shifter.index++;
                  });
            }
            
        }
        
        Shifter.prev = function() {
    
            var margin = 0;
            
            $('.navi li').each(function(i){
                if (i < Shifter.index-1) {
                    margin += $(this).width();
                }
            });
            
            if (Shifter.index > 0) {
                this.nav.animate({
                    marginLeft: -margin
                  }, 100, function() {
                      Shifter.index--;
                  });
            }
            
        };
        
        if ( Shifter.navWidth > Shifter.thumbs.width()) {
            $('<a id="t_prev" class="control">prev</a>')
    	        .insertBefore('#thumbs')
    	        .click(function(e){
    	            Shifter.prev();
    	        })
    
            $('<a id="t_next" class="control">next</a>')
    	        .insertAfter('#thumbs')
    	        .click(function(e){
    	            Shifter.next();
    	        })
        }	    
        
    })();
    
	
	
	
	
	
	
	
		// IF NO SLIDER PRESENT, BUT VIDEO IS:
	if ($('.slide').length == 1) {
		var el = $('#slides').find('.youtube-video');
		if (el.length > 0) {
			setupVideo(el);
		}
	}
	
	
	
	// provide scrollable API for the action buttons
	if(api) api = api.data("scrollable");

	function sliderColours(){
		if(api){
			var	currentSlide = $("#slides .slide:eq(" + (api.getIndex() + 1) + ")");
		}
		else {
			var	currentSlide = $(".no-scroll .slide");
		}
		if(currentSlide.length > 0){
			if(currentSlide.hasClass('red')){
				$('#hero_fg, #hero_bg').removeClass().addClass('red');
				$('.nav-arrow.current').removeClass('yellow blue green grey').addClass('red');
			}
			else if(currentSlide.hasClass('green')){
				$('#hero_fg, #hero_bg').removeClass().addClass('green');		
				$('.nav-arrow.current').removeClass('yellow blue red grey').addClass('green');
			}
			else if(currentSlide.hasClass('yellow')){
				$('#hero_fg, #hero_bg').removeClass().addClass('yellow');		
				$('.nav-arrow.current').removeClass('red blue green grey').addClass('yellow');
			}
			else if(currentSlide.hasClass('grey')){
				$('#hero_fg, #hero_bg').removeClass().addClass('grey');		
				$('.nav-arrow.current').removeClass('red blue green yellow').addClass('grey');
			}
			else {
				$('#hero_fg, #hero_bg').removeClass().addClass('blue');		
				$('.nav-arrow.current').removeClass('red blue green grey').addClass('blue')
			}		
		}			
	}
	
	window.sliderColours = sliderColours;
	sliderColours();
	
	if(api) api.onSeek(sliderColours);

	$('#stop').toggle(
		function(){
			api.pause();
			$(this).addClass('button_on');
	  },
	  function(){
	  	api.play();
	    $(this).removeClass('button_on');      
		}
	);	

		
	/*	accordion
	------------------------------------*/
	var accordion = $(".accordion")
		.tabs(".accordion > div.pane", {
			tabs: 'h2', 
			effect: 'slide', 
			onClick: function(){
			  var that = this;
			  // console.log(accordion);
			},
			initialIndex: null
		}
	);
	
	$(".accordion").each(function(){
		$(this).find('h2:last').addClass('last-child');
	})
						
}); 

