// JavaScript Document


$(document).ready(function(){
	
	
	function videoProcess(){
		
		
		//1) raise videodetect event
		var videoDetect = $.Event("videoDetect");
		
		
		videoDetect.options = {
			IsMp4:false,
			IsFlash:false			
		};
		
		$("body").trigger(videoDetect);
		
       	
		//2) set up videoEvents
		videoSettings();
		
		//3) no video detection
		if (!videoDetect.options.IsMp4){
			
			videoCleanUp();
		}
		else
		{
			return;
		}
		
		//4) return if no flash
		if (!videoDetect.options.IsFlash){
		
			return;
		}
		
		//5) flash fallback	
		$("body").trigger("videoFlash");
		
	}
	
	
	function videoCleanUp(){
		
		$("video").each(function(){
			
			var target = $(this);

			target.find("a[data-video-player]").each(function(){
				
				var anchor = $(this);
			
				anchor.closest("video").replaceWith(anchor); 
			});
			
			
		});
	}
	
	function videoSettings(){
		
		$("video:not([data-ready])").each(function(){
			
			var video = $(this);
			
			//bind the ended event
			video.bind("ended",function(){
			
				var redirect  = $(this).attr("data-video-redirect");

				if (redirect != undefined){
														
					window.location.href = 	redirect;
				}
				
			});
			
			//set data-ready
			video.attr("data-ready","true");
		});
		
		
		
	}
	
	
	
	$(window).bind("load",function(){
		
		videoProcess();
	});
    
    $("body").ajaxComplete(function(){
       
	   
	   
        videoProcess();
    });
	
	
	
});
