/* Seta a flag que verifica se o usuário consegue acessar o youtube */
var acessaYoutube;
var apple;
var suportaHTML5;
function initVideo() {
	var Apple = {};  
	Apple.UA = navigator.userAgent;  
	Apple.Device = false;  
	Apple.Types = ["iPhone", "iPod", "iPad"];  
	for (var d = 0; d < Apple.Types.length; d++) {  
	    var t = Apple.Types[d];  
	    Apple[t] = !!Apple.UA.match(new RegExp(t, "i"));  
	    Apple.Device = Apple.Device || Apple[t];  
	}
	
	apple = Apple.Device;
	
	var testeHTML5 = document.createElement("canvas");
	suportaHTML5 = ( testeHTML5.getContext ) ? true : false;
	
	youtubeVerify();
}

/* define function that adds another function as a DOM event listener */ 
function myAddListener(obj, evt, handler, captures) { 
	if ( document.addEventListener ) 
	   obj.addEventListener(evt, handler, captures); 
	else 
	   // IE 
	   obj.attachEvent('on' + evt, handler); 
} 

/* define functions that register each listener */ 
function RegisterListener(eventName, objID, embedID, listenerFcn) { 

    var obj = document.getElementById(objID); 

    if ( !obj ) 
        obj = document.getElementById(embedID); 
    if ( obj ) 
        myAddListener(obj, eventName, listenerFcn, false); 
} 




//2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 3. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.


var player;

// 5. The API calls this function when the player's state changes.
//    The function indicates that when playing a video (state=1),
//    the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
	if (event.data == YT.PlayerState.PLAYING) {
		controlBanner('PLAY');
	}
	if (event.data == YT.PlayerState.PAUSED) {
		controlBanner('PAUSE');
	}
	if (event.data == YT.PlayerState.ENDED) {
		controlBanner('ENDED');
	}
}
function stopVideo() {
  player.stopVideo();
}

/* Verifica se o browser do cliente consegue acessar o youtube */
function youtubeVerify() {
	jQuery.ajax({
		url: 'http://gdata.youtube.com/feeds/api/users/nissanoficial/subscriptions?max-results=1&alt=json&callback=?',
		dataType: 'json',
		success: function() {loadVideos(true); },
		error: function() {loadVideos(false); },
		timeout: 3000
	});
}

function loadVideos(youtube) {
	acessaYoutube = youtube;
//	acessaYoutube = false;
	
	$('.midia').each(function(idx, ctx){
		var youtubeId = $(ctx).attr('youtube');
		var videoServer = $(ctx).attr('server');
		var width = $(ctx).attr('width');
		var height = $(ctx).attr('height');
		var autoplay = $(ctx).attr('auto_play');
		
		$(ctx).attr("id","m"+idx);
		
		if(autoplay == undefined){
			autoplay = 0;
		}
		
		var html = '';
		
		//alert('apple: ' + apple + ' acessaYT: ' +acessaYoutube + ' suportaHTML5: ' + suportaHTML5)
		if(apple && (!acessaYoutube || !suportaHTML5)) {
			html = QT_GenerateOBJECTText_XHTML(videoServer, width, height,'',
					'autoplay', (autoplay==1?true:false),
					'postdomevents', 'True',
					'obj#id', "m"+idx);
			$(ctx).html(html);
			RegisterListener('qt_ended', "m"+idx, 'qtmovie_embed', function(event) {controlBanner('ENDED');});
			RegisterListener('qt_play', "m"+idx, 'qtmovie_embed', function(event) {controlBanner('PLAY');});

		} else if(acessaYoutube) {
//			html =  '<iframe width="' + width + '" height="' + height + '" frameborder="0" src="http://www.youtube.com/embed/'+youtubeId+'?hl=en&fs=1&rel=0&showinfo=0&autoplay='+autoplay+'"></iframe>';
			player = new YT.Player("m"+idx, { 
				
			    height: height,
			    width: width,
			    videoId: youtubeId,
			    playerVars : {autoplay:autoplay},
			    events: {
			      'onStateChange': onPlayerStateChange
			    }
			  });
		} else {
			jwplayer("m"+idx).setup({
				 flashplayer: 'player/mediaplayer.swf',
				 file: videoServer,
				 height: height,
				 width: width,
				
				 events: {
					 onPlay: function(event) {controlBanner('PLAY');},
					 onPause: function(event) {controlBanner('PAUSE');},
					 onENDED: function(event) {controlBanner('ENDED');}
				 	}
			 });
		} 
//		
	});
}
///////////////////////////////////////////////////////////////////////////////
/////// banner rotativo ///////////////////////////////////////////////////////
var timer_banner;
var intervalo = 5000;
var b_length = 0;
var b_nav_pos = 0;

function controlBanner(state){
	if(state == "PLAY"){
		clearInterval(timer_banner);
	}
	if(state == "PAUSE"){
		clearInterval(timer_banner);
	}
	if(state == "ENDED"){
		clearInterval(timer_banner);
		timer_banner = setInterval( bannerControlChange, intervalo);
	}
//	alert(state);
}

function initBannerRotativo() {

	clearInterval(timer_banner);
	
	b_length = $("td",$(".banner-rotativo-scroll")).length;
	
	b_nav_pos = 0;
	
	
	var nav = "";
	
	for(var i = 0 ; i < b_length ; i++){
		
		nav += '<td class="banner-rotativo-nav-btn" trgt="'+i+'" style="background-position:'+(-i*27)+'px 25px;"></td>'
		
	}
	
	$("tr",$(".banner-rotativo-nav")).html(nav);
	
	
	$(".banner-rotativo-nav-btn").click(function(){
		
		b_nav_pos = Number($(this).attr("trgt"));
		
		setBannerSelecionado(b_nav_pos);
		
		if(b_length > 1){
			clearInterval(timer_banner);
			
			timer_banner = setInterval( bannerControlChange, intervalo);
		}
		
	});
	
	setBannerSelecionado(b_nav_pos);
	
	if(b_length > 1){
		timer_banner = setInterval( bannerControlChange, intervalo);
	}
	
	
	
	//$(".banner-rotativo-scroll").hover(function(){
	//	clearInterval(timer_banner);
	//},function(){
	//	timer_banner = setInterval( bannerControlChange, intervalo);
	//});

}

function bannerControlChange(){
	if(b_nav_pos == b_length-1){
		setBannerSelecionado(0);
		b_nav_pos = 0;
	} else {
		setBannerSelecionado(++b_nav_pos);
	}		
}

function setBannerSelecionado(pos){

	$(".banner-rotativo-nav-btn").each(function(i){
		
		if(i != pos){
			
			$(this).stop().animate({
				opacity:0
			  }, 500, 'swing', function() {
			  });
			
		} else {
			
			$(".banner-rotativo-scroll").stop().animate({scrollLeft: $(".banner-rotativo-scroll").width()*pos}, '500');
			
			$(this).stop().animate({
				opacity:1
			  }, 500, 'swing', function() {
			  });
		}
		
	});

}
