(function($){
		  
    $.LoadModalFlv = function(el, options){
		
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;
        
        // Access to jQuery and DOM versions of element
        base.$el = $(el); // jQuery
        base.el = el;     // Dom
        
        // Add a reverse reference to the DOM object
        base.$el.data("LoadModalFlv", base);
        
        base.init = function(){
			//pass in options
            base.options = $.extend({},$.LoadModalFlv.defaultOptions, options);
			
			// look in the metadata for a width and height
			data = base.$el.metadata();
			
			if(data.target_id == null){
				alert('Please provide a unique "target_id" e.g class="show-vid data{target_id:\'media3\'}"');
			}else{
	          	// bind the media to the base element
				// adds a new div to the child of the parent which contains a wrapper
				// which is then rendered JWplayer by Media plugin
				// make sure to pass in the results of the initialisation, in this case imgStatus
				// pass to both bind and its associated function call
				base.$el.bind('toggleContent', function(e, imgStatus){ base.loadMedia(imgStatus); });
				
				switch(base.options.event){
					case "onClick":
						// do nothing on click event to base jQuery object
						base.$el.click(function(){ base.initResource(); return false;});
					break;
					case "onLoad":				
						// normally a.view-vid
						//then make a call to initialise the resoures being used e.g. vid background image
						base.initResource();
					break;
				}		
			}
        };   
		
		// Method call initDropdown
		base.initResource = function(){
			//check that bg img exists
			//base.resourceCheck();
			base.initDropdown('success');
			return false;
		}
		
		// Method call initDropdown
		base.initDropdown = function(imgStatus){
			//fire event handler toggleContent object	
			base.$el.trigger('toggleContent', [imgStatus]);
			
			return false;
		}
		
		// Method call resourceCheck
		base.resourceCheck = function(){
			
			//get img path			
			imgSnapshotPath = base.$el.attr('title');
			
			//check if snapshot img exists
			if(imgSnapshotPath){	
				
				if(imgSnapshotPath!=null){
						
						//preload inage into page
						//use ajax call to PHP script which checks for existance of file on server	
						$.ajax({
						    type: "GET",
							url: '/check_resource.php',
							data: 'p_resource='+imgSnapshotPath,
						  	success: function(responseXML, textStatus, XMLHttpRequest){
								var message = $('status', responseXML).text(); //assign XML message node to variable
								base.initDropdown(message);
							},
						  	error: function(XMLHttpRequest, textStatus){
								base.initDropdown(textStatus);
							}
						});
				}
			}
			
		}
		
		// Method call loadMedia
		// accepts argument passed in by base.resourceCheck
		base.loadMedia = function(imgStatus){
			
			//note must use $var inorder for IE to recognise var as object
			//initialise local vars
			href = null;
			flash_extension = null;
			$target = base.$el;	

			//grab href attribute	
			href = base.$el.attr('href');	

			//get link path to flv if it exists
			flash_extension = base.$el.attr('href').substring(base.$el.attr('href').lastIndexOf(".")+1,base.$el.attr('href').length); //grab file extension attribute 

			
			//set background image based on imgStatus
			switch(imgStatus){
				case "success":
					base.options.imgDefaultSrc = base.$el.attr('title');
				break;
			}
			
			//hide target
			$target.css({'display':'none'});


			if($target.siblings('div.video').length > 0){
				$target.siblings('div.video').remove();
			}
			
			switch(flash_extension){
				case "mp4":
				case "ogv":
					if(jwplayer){
						
						// look in the metadata for a width and height
						data = $target.metadata();
						
						
						if (data.width && data.width > 0 && data.height && data.height > 0){
							if (base.options.width == null && base.options.height == null){
								base.options.width = data.width;
								base.options.height = data.height;
							}
						}
						
						if (data.target_id != null){
							base.options.targetId = data.target_id;
						}
						
						// initialise
						isIphone = false;
				
						// iphone and ipad go straight to roundabout
						if (Modernizr.video && Modernizr.video.h264){
							
				        	// preload h264 assets
				        	//if(Modernizr.video.h264){
				        	if((navigator.userAgent.match(/iPhone/i)) ||  (navigator.userAgent.match(/iPad/i))) {
				        		isIphone = true;
				        	}
				   		}
				   		
				   		// none video browsers go straight to roundabout
				   		if (!Modernizr.video){
				   			isIphone = false;
				   		}
						
						//if($target.siblings('.video').length == 0){
						
							//background:url(\''+base.options.imgDefaultSrc+'\') center no-repeat;
							$('<div class="video" style="width:'+base.options.width+'px;height:'+base.options.height+'px;"><video id="'+base.options.targetId+'" class="player" poster="'+base.options.imgDefaultSrc+'" width="'+base.options.width+'" height="'+base.options.height+'" controls="true"><source src="'+href+'" type=\'video/mp4; codecs="avc1.42E01E, mp4a.40.2"\'><div class="non-flash-content">no flash</div></video></div>').insertAfter($target);							
							
					   		
							if (isIphone == false) {
								
								// init jwplayer
								if(typeof(base.options.targetId) != null){
								
								    jwplayer(base.options.targetId).setup({
													    width: base.options.width,
													    height: base.options.height,
													    file: href,
													    image: base.options.imgDefaultSrc,
													    skin:'/js/libs/jwplayer/skins/glow/'+base.options.skin+'.xml',
													    stretching:'uniform',
													    players: [
														            { type: "html5" },
														            { type: "flash", src: base.options.swfDefaultDir }
														        ]
													  });
					    
					    			if(base.options.event == "onClick"){
					    				jwplayer(base.options.targetId).onReady(jwplayer(base.options.targetId).play()); // autoplay
					    			}
							    
								    // append the wmode para to the flash object if rendered
								    if(document.getElementById(base.options.targetId)){
										var wmode = document.createElement("param");
										wmode.name = "wmode";
										wmode.value = "transparent";
										document.getElementById(base.options.targetId).appendChild(wmode);
									}
								}
								
								//enforce dimensions on player
								$(base.options.targetId).bind('set_dimensions',function(){
									$(this).css({'width': base.options.width,'height': base.options.height});
								});
								
								$(base.options.targetId).trigger('set_dimensions');
							}
						/*}else{
							
							$target.siblings('.video').show();
							// the video already exists on the page, so just show it
							if(base.options.event == "onClick"){
								log(jwplayer(base.options.targetId));
			    				jwplayer(base.options.targetId).play(); // autoplay
			    			}		    			
								
							//enforce dimensions on player
							$(base.options.targetId).bind('set_dimensions',function(){
								$(this).css({'width': base.options.width,'height': base.options.height});
							});
							
							$(base.options.targetId).trigger('set_dimensions');
						}*/
							
					}else{
						alert('You need to have the jwplayer installed.');
					}
				break;
			}
			
			if(base.options.event == "onClick"){
				//add on closer div
				$target.siblings('.video').append('<div class="closer"><p>close [X]</p></div>');
				
				if(isIphone == true){
					$target.siblings('.video').children('div.closer').css({'display':'none'});
				}
				
				//apply media closing action
				$target.siblings('.video').children('div.closer').bind('click',function(){ 
					// stop the vid
					jwplayer(base.options.targetId).stop();
					//remove movie wrapper
					$('div.video').hide();
					$('div.closer').remove();
					// show target
					$target.css({'display':'block'});
				});
			}
		}
		
        
        // Run initializer
        base.init();
    };
    
    $.LoadModalFlv.defaultOptions = {
		imgExtension: ["jpg"],
		imgDefaultSrc: null,
		width: null,
		height: null,
		swfDefaultDir:'/movies/player.swf',
		event:'onLoad',
		targetId: null,
		skin : 'glow'
    };
    
    $.fn.loadModalFlv = function(options){
        return this.each(function(){
            (new $.LoadModalFlv(this, options));
        });
    };
    
    // This function breaks the chain, but returns
    // the LoadModalFlv if it has been attached to the object.
    $.fn.getLoadModalFlv = function(){
        this.data("LoadModalFlv");
    };
    
})(jQuery);

