/**
 * FlowPlayer Integration
 * @ Author : Eddie Spradley
 * @ Date: November 18th, 2011.
 * @ Comments: I really, really, really dislike IE browsers...
 */
(function( $ ){

	
	//Function declaration.  
	$.fn.levVideo = function( options ) {
		
		//Extends the  default options.  Allowing us to overwrite or use the default values in each object.
		var opts = $.extend({}, $.fn.levVideo.defaults, options);	

       	//Loop through each item of each selector and the script will do what it does.	
		return this.each(function(){
	    	
			
			var $this = $(this);
			
			
			//Checks if the browser has meta data enabled...it's cleaner.  If not, use default
			var o = $.meta ? $.extend({}, opts, $this.data()) : opts;	

			//Video specific variable declaration.  This allows us to use the tags in the dom element.
			var vid_path = (o.url != '') ? o.url : (typeof $(this).attr('href') !== 'undefined') ? $this.attr('href') : '',
				vid_height = ($this.attr('v_height') != null) ? $this.attr('v_height') : o.height,
				vid_width = ($this.attr('v_width') != null) ? $this.attr('v_width') : o.width,
				vid_title = (o.title != '') ? o.title : (typeof $(this).attr('v_title') !== 'undefined') ? $this.attr('v_title') : '';
				
			o.autoPlay = (typeof $this.attr('v_autoPlay') !== 'undefined') ? true : o.autoPlay;
				
    		
			//The acutally processing occurs here.  If it's a modal, we do something very different than if it's embedded.
			if(o.modal){    			
    			
				//We need to attach a click event listener to this element, but only if it's modal.
				$this.click(function(e){

					//Stop the link from going to the movie file.
    				e.preventDefault();
    				
    				//Stops all playing video's.  That way we don't have more than one video playing at once.  
    		        $f('*').each(function() {
    		        	this.stop();
    		        });
    				
    				//Grab the modal HTLM text and then load it in the dom structure.  Only done for modals.
    		        $('body').append(fnGenModalDiv(vid_title));
    		        
    		        //Generate the video dom structure so we can think about loading the movie.  Sends the name of float, which is converted to vid_float.
    	    		$('.video-window').append(fnGenVideoDiv(vid_path, vid_width, vid_height, 'float'));
    	    	
    	    		//Sends in the target and the optoins for this element and converts the link placeholder into a flowplayer video.
    	    		fnConvertVideo(o, 'vid_float');
    	    		
    	    		//Part of a bug fix in flow player, see fnGenVideoDiv for more...
    	    		$f('vid_float').load();
    	    		
    			})
    			
    		}
    		else{
    			//If this is embedded, we don't need all that garbage above.  We simply generate the video text and append it to this element.
    			//It's important to have an ID in this case, so we can identify which dom element to append.  
    			//If I had more time, I'd fix make it so no id is required.
    			$this.append(fnGenVideoDiv(vid_path, vid_width, vid_height, $this.attr('id')));
    			
    			//This converts the link placeholder to the video.
    			fnConvertVideo(o, 'vid_'+$this.attr('id'));
    		}
	    });
	};

	//Generates video dom structure.
	fnGenVideoDiv = function(url, width, height, nameElement){
		
		//Instantiate the var
		var defaultText = "";
		
		//Interesting thig going on here.  If name element isn't passed, then we want to name the element vid_modal.
		var elementID = (typeof nameElement !== 'undefined') ? " id='vid_"+nameElement+"' " : "";
		
		/*
		 * Hack fix for Flowplayer isseus with IE.  We have to unload a video before we can remove it from dom, or IE
		 * as usual complains about it.  Flowplayer doesn't help this because the unload call only works if there is
		 * default content.  The problem enters when we have embeded vids.  If we had default text, then when we ran the 
		 * stop all command above, the div would convert to the default text.  If it's blank, then it doesn't do anything
		 * when we stop it.  So, for ebedded, we leave it blank, for modal we set it since it dissapears off dom anyways.
		 */
		if(elementID == "vid_float"){
			defaultText = "Click here if the video doesn't play automatically";
		}
		
    	videoDiv = '<div class="video">';
        videoDiv += '<a href="' + url + '" style="display:block; width:' + width + 'px; height:' + height + 'px;"'+elementID+'>'+defaultText+'</a>';   // adjust width, height, and video
        videoDiv += '</div>';       // video
        return videoDiv;
	
	}
	
    //Generate Modal Div
    fnGenModalDiv = function(title){
    	
        var modalDiv = '';    	
    	modalDiv = '<div class="floating-div">'; //Overlay
		modalDiv +=	'<div class="video-window">'; //Interior Div
		modalDiv += '<a class="close-btn" href="#">close</a>';
        if (title != '') {
            modalDiv += '<h1>' + title + '</h1>';
        }
		modalDiv += '</div>';
		modalDiv += '</div>';
		return modalDiv;
    }
    
    /*
     * Omniture: SiteCatalyst Video Tracking
     */
    
    //Call on video load.
    fnStartMovie = function(params){
    	s.Media.open(params.name, params.length, params.playerName);
    	fnPlayMovie(params);
    }
    
    //Slider release or unpause
    fnPlayMovie = function(params){
    	s.Media.play(params.name, params.offset);
    }
    
    //Pause and slider grab
    fnStopMovie = function(params){
    	s.Media.stop(params.name,params.offset);
    }
    
    //End of video
    fnEndMovie = function(params){
    	fnStopMovie(params);
    	s.Media.close(params.name);
    }
    
    fnConvertVideo = function(o, target){

        //Convert the target id to a flow player instance.
    	flowplayer(target, {src:'/flowplayer/flowplayer.commercial-3.2.5.swf', wmode:(o.modal ? 'opaque' : 'transparent')}, {
    		onLoad: function(){ 
    			var params = { event : 'load' };
			},
    		onError: function(err, msg){ 
    			var params = { event : 'error', err : err, msg : msg };
			},
    		onVolume: function(level){ 
    			var params = { event : 'volume', level : level };
			},
    		onFullScreen: function(){ 
    			var params = { event : 'fullscreen' };
			},
    		onFullScreenExit: function(){ 
    			var params = { event : 'fullscreenexit' };
			},
    		key: o.key,
	        clip:  {
	    		onPause: function(clip){ 	
	    			var params = { name : clip.completeUrl, offset : parseInt(this.getTime()) };
	    			fnStopMovie(params);
				},
	    		onResume: function(clip){ 
	    			var params = { name : clip.completeUrl, offset : parseInt(this.getTime()) };
	    			fnPlayMovie(params);
				},
	    		onStart: function(clip){ 
	    			var params = { name : clip.completeUrl, length : parseInt(clip.fullDuration), playerName : 'FlowPlayer', offset : parseInt(this.getTime()) };
	    			fnStartMovie(params);
				},
	    		onStop: function(clip){ 
	    			var params = { name : clip.completeUrl, offset : parseInt(this.getTime()) };
	    			fnStopMovie(params);
				},
	    		onFinish: function(clip){ 
	    			var params = { name : clip.completeUrl, offset : parseInt(this.getTime()) };
	    			fnEndMovie(params);
				},
				onSeek: function(clip){					
					var params = { name : clip.completeUrl, offset : parseInt(this.getTime()) };
					fnStartMovie(params);
				},
	        	autoPlay: o.autoPlay,
	        	autoBuffering: o.autoBuffering
	        },
	        plugins: {
	            controls: {
	                timeColor: o.timeColor,
	                progressGradient: o.progressGradient,
	                backgroundColor: o.backgroundColor,
	                timeBgColor: o.timeBgColor,
	                sliderColor: o.sliderColor,
	                tooltipColor: o.tooltipColor,
	                bufferGradient: o.bufferGradient,
	                borderRadius: o.borderRadius,
	                sliderBorder: o.sliderBorder,
	                buttonColor: o.buttonColor,
	                buttonOverColor: o.buttonOverColor,
	                volumeSliderGradient: o.volumeSliderGradient,
	                volumeBorder: o.volumeBorder,
	                volumeSliderColor: o.volumeSliderColor,
	                sliderGradient: o.sliderGradient,
	                timeSeparator: o.timeSeparator,
	                autoHide: o.autoHide,
	                backgroundGradient: o.backgroundGradient,
	                progressColor: o.progressColor,
	                bufferColor: o.bufferColor,
	                volumeColor: o.volumeColor,
	                durationColor: o.durationColor,
	                timeBorder: o.timeBorder,
	                tooltipTextColor: o.tooltipTextColor,
	                theight: o.theight,
	                opacity: o.opacity,
	                play: o.play,
	                volume: o.volume,
	                mute: o.mute,
	                time: o.time,
	                stop: o.stop,
	                playlist: o.playlist,
	                fullscreen: o.fullscreen
	            }
   
            }});
    	return false;
    };
	
	
	//Default variable declaration.  These can be overrident by passing in values like this $(element).levVideo({ autoPlay: false, title : '123' })
	$.fn.levVideo.defaults = {
        url:        '',
        width:      510,
        height:     285,
        modal:      false,
        title:      '',
		key: ['#@f01543d564cec67757b', '#@706f244e744a3ee7a64', '#$86133b48294dd73af2b'],
		autoPlay: false,
		autoBuffering: true,
        timeColor: '#ffffff',
        progressGradient: 'none',
        backgroundColor: 'rgb(0, 0, 0, 0.7)',
        timeBgColor: 'rgb(0, 0, 0, 0)',
        sliderColor: '#000000',
        tooltipColor: '#000000',
        bufferGradient: 'none',
        borderRadius: '0px',
        sliderBorder: '0px solid rgba(128, 128, 128, 0.7)',
        buttonColor: '#ffffff',
        buttonOverColor: '#ffffff',
        volumeSliderGradient: 'none',
        volumeBorder: '0px solid rgba(128, 128, 128, 0.7)',
        volumeSliderColor: '#000000',
        sliderGradient: 'none',
        timeSeparator: ' ',
        autoHide: 'true',
        backgroundGradient: 'none',
        progressColor: '#5798d6',
        bufferColor: '#2e5580',
        volumeColor: '#5798d6',
        durationColor: '#5798d6',
        timeBorder: '0px solid rgba(0, 0, 0, 0.3)',
        tooltipTextColor: '#ffffff',
        theight: 24,
        opacity: 1.0,
        play: true,
        volume: true,
        mute: true,
        time: true,
        stop: false,
        playlist: false,
        fullscreen: false
	}; 
	
	
	//We use this to bind a few events.  Should be rewritten if we have time.
	$(document).ready(function(){
		
		//I always use delegate vs live click since it has less over head due to less bubbling.  You should too!  
		//Ulimately this closes the modal window.
		$('body').delegate('.close-btn', 'click', function(e){
			e.preventDefault();
			
			/*
			 * Part of the IE/Flowplayer bug.
			 * First, we have to unload the vid_float Flowplayer instance for the float.  This means we stop all connectivity to the server.
			 * Then, we have to hide it...since IE doesn't like you to remove dom elements...sure, it's a xhtml standards thing, but what other browser follows them?
			 * Then we can actually remove it without causing IE to give null = null error.  
			 */
			$f('vid_float').unload();			
			$('.floating-div').hide();
			$('.floating-div').remove();
		});
		
		//Prevents the browser from following the placeholder link we create.
		$('body').delegate('.lev_video_float', 'click', function(e){
			e.preventDefault();
		});
		
		//Automatically converts floats and embeds if they use our specified class structure below.
		//This prevents the user from having to make any calls to this function.  All they must do is include it :)
		$('.lev_video_float').levVideo({ modal : true });
		$('.lev_video_embed').levVideo();
	});
	
	

	  
})( jQuery );

