(function($) {

$.fn.ajaxMedia = function(options) {
	var defaults = {
		overlayPrepend:'body',
		overlayOpacity:'0.8',
		OSSInit:'.overlaySlideShow',
		OVInit:'.overlayVideo',
		OQTInit:'.overlayQuicktime',
		IAInit:'.inlineAudio',
		IIAInit:'.instantInlineAudio',
		ISWFInit:'.inlineSWF',
		IISWFInit:'.instantInlineSWF',
		OSWFInit:'.overlaySWF',
		close:'.close',
		next:'.next',
		previous:'.previous',
		archiveSelect:'.archiveSelect',
		rootPath:'http://www.du.edu',
		rootPathShort:'http://www.du.edu',
		expressInstallPath:'/WebSite/display/swf/expressInstall.swf',
		playerPath:'/WebSite/display/swf/video/player.swf',
		skinPath:'/WebSite/display/swf/video/modieus.swf',
		slideshowUL:'.overlay-slideshow',
		overlayWrapper:'.overlay-wrapper',
		slideCount:'.overlay-slideCount',
		slideNavBox:'.overlaySlideNav',
		mediaInfo:'.mediaInfo',
		resizePadding: '6px',
		altContentContainer:'altContent_'/*var for swf object NOT jquery. must be an id, without '#'. will tack on asset id*/
	}
	var options = $.extend(defaults, options);

	var overlay = $("<div id='overlay'><div id='loading'>&nbsp;</div></div>");
	var addMedia = $("<div id='addMedia'>&nbsp;</div>");
	
	if(options.rootPathShort == options.rootPath){
		options.playerPath=options.playerPath.replace(/\/WebSite\//gi, "/");
		options.playerPath=options.playerPath.replace(/\/WebAssets\//gi, "/");
		options.skinPath=options.skinPath.replace(/\/WebSite\//gi, "/");
		options.skinPath=options.skinPath.replace(/\/WebAssets\//gi, "/");
		options.expressInstallPath=options.expressInstallPath.replace(/\/WebSite\//gi, "/");
		options.expressInstallPath=options.expressInstallPath.replace(/\/WebAssets\//gi, "/");
	}
	
	$(options.overlayPrepend).prepend(overlay);
	$('#overlay').css('opacity', options.overlayOpacity);
	$('body').append(addMedia);
	
	// Slideshow hover
	var slide = 1;
	var slideTotal=0;
	var callers = new Array();
	var scrollPos = $(window).scrollTop() + 50;

	if($.browser.msie && $.browser.version < 7.0) {
		$('#overlay').css('position', 'absolute');
		$("body","html").css({"height": "100%"});
		var windowHeight = $(document).height();
		var windowWidth = $(document).width();
		var marginLeft = (-(windowWidth-960)/2);
		if(windowWidth > 960){$('html').css('overflow-x','hidden')};
		$('#overlay').css({'height': windowHeight, 'width': windowWidth, 'margin-left':'0', 'margin-top':'0'});
	}
	
	
	
	
	$(options.OSSInit).click(function(){
        $jqObj=$(this);
		obj=this;
        init('OSS', $jqObj, obj);
        return false;
    });
	
	$(options.OVInit).click(function(){
        $jqObj=$(this);
		obj=this;
        init('OV', $jqObj, obj);
        return false;
    });
	
	$(options.OQTInit).click(function(){
        $jqObj=$(this);
		obj=this;
        init('OQT', $jqObj, obj);
        return false;
    });
	
	$(options.IAInit).click(function(){
        $jqObj=$(this);
		obj=this;
        init('IA', $jqObj, obj);
        return false;
    });
	
	$(options.IIAInit).each(function(i){
        $jqObj=$(this);
		obj=this;
        init('IA', $jqObj, obj);
        return false;
    });
	
	$(options.OSWFInit).click(function(){
        $jqObj=$(this);
		obj=this;
        init('OSWF', $jqObj, obj);
        return false;
    });
	
	$(options.ISWFInit).click(function(){
        $jqObj=$(this);
		obj=this;
        init('ISWF', $jqObj, obj);
        return false;
    });
	
	$(options.IISWFInit).each(function(i){
        $jqObj=$(this);
		obj=this;
        init('ISWF', $jqObj, obj);
        return false;
    });
    
	function init(type, $tempJqObj, tempObj){
        var clicked = tempObj;
        var check = false;
        var classy = $tempJqObj.attr('class');
        var href = $tempJqObj.attr('href');
        var arrayPos = 0;
        $.each(callers, function(i,n){
            if(callers[i][2]==href){
                check=true;
                arrayPos=i;
            }
        })
        if(check==true){
			switch(type){
				case 'OSS':
				overlaySlideshow(true, $tempJqObj, arrayPos);
				break;
				case 'OV':
				overlayVideo(true, $tempJqObj, arrayPos);
				break;
				case 'OQT':
				overlayQT(true, $tempJqObj, arrayPos);
				break;
				case 'OSWF':
				overlaySWF(true, $tempJqObj, arrayPos);
				break;
				default:
			}
        }else{
            arrayPos=callers.length;
            callers[arrayPos] = new Array();
            callers[arrayPos][0] = clicked;
            callers[arrayPos][1] = classy;
            callers[arrayPos][2] = href;
			
			switch(type){
				case 'OSS':
				overlaySlideshow(false, $tempJqObj, arrayPos);
				break;
				case 'OV':
				overlayVideo(false, $tempJqObj, arrayPos);
				break;
				case 'OQT':
				overlayQT(false, $tempJqObj, arrayPos);
				break;				
				case 'IA':
				inlineAudio($tempJqObj, arrayPos);
				break;
				case 'OSWF':
				overlaySWF(false, $tempJqObj, arrayPos);
				break;
				case 'ISWF':
				inlineSWF($tempJqObj, arrayPos);
				break;
				default: 
			}
        }
        return false;
    }

	function overlaySlideshow(loaded, $jqObj, index){
		var divId = ("overlaySlideshow-"+index);
		$("#overlay").fadeIn('fast');
		var slideNum = 1;
		
		if(loaded == true){
			reopen();
		}else{
			var wrapper = $('<div id="'+divId+'">&nbsp;</div>');
			$('#addMedia').append(wrapper);
			showLoading(true, $jqObj);
			$('#'+divId).load(callers[index][0].href + ' '+options.overlayWrapper, function(){
				initOSS();
			});
		};
		
		function initOSS(){
			hideLoading(true, $jqObj);
			slideNum = 1;
			mediaPath=$("#"+divId+" .mediaPath").html();
			if(options.rootPathShort == options.rootPath){
				newMediaPath=mediaPath.replace(/\/WebSite\//gi, "/");
			}else{newMediaPath=mediaPath};
			if(options.rootPathShort == options.rootPath){
				$("#"+divId+" "+options.slideshowUL+" li img").each(function(i){
					var regexp = /(\w|[-.])+$/;
					fname = regexp.exec($(this).attr('src'));
					$(this).attr('src', (newMediaPath + 'images/' + fname[0] ));
				});
			}
			slideTotal=$("#"+divId+" "+options.slideshowUL+" li").siblings().length;
			$("#"+divId+" "+options.overlayWrapper).fadeIn('slow');
			$("#"+divId+" "+options.slideshowUL+" li:first").addClass('currentSlide').slideDown('slow');
			control();
			close(divId, 'OSS', index);
		}
		
		function reopen(){
			$('#'+divId+' '+options.overlayWrapper).fadeIn('fast');
			$('#'+divId+' '+options.overlayWrapper+' li.currentSlide').slideDown('slow');
		}
		
		function control(){
			indexSlides(divId);
			
			$("#"+divId+" "+options.next).click(function(e){
				var currentSlide = $("#"+divId+" "+options.slideshowUL+" li.currentSlide");
				e.preventDefault();
				if(slideNum<slideTotal){
					$(currentSlide).removeClass('currentSlide').fadeOut('medium', function(){
					$(currentSlide).next("#"+divId+" "+options.slideshowUL+" li").addClass('currentSlide').fadeIn('medium');});
					slideNum++;
					indexSlides(divId);
				}else{
					$(currentSlide).removeClass('currentSlide').fadeOut('medium', function(){
					$("#"+divId+" "+options.slideshowUL+" li:first").addClass('currentSlide').fadeIn('medium');});
					slideNum = 1;
					indexSlides(divId);
				}
			});
			
			$("#"+divId+" "+options.previous).click(function(e){
				var currentSlide = $("#"+divId+" "+options.slideshowUL+" li.currentSlide");
				e.preventDefault();
				if(slideNum>1){
					$(currentSlide).removeClass('currentSlide').fadeOut('medium', function(){
					$(currentSlide).prev("#"+divId+" "+options.slideshowUL+" li").addClass('currentSlide').fadeIn('medium');});
					slideNum--;
					indexSlides(divId);
				}else{
					$(currentSlide).removeClass('currentSlide').fadeOut('medium', function(){
					$("#"+divId+" "+options.slideshowUL+" li:last").addClass('currentSlide').fadeIn('medium');});
					slideNum=slideTotal;
					indexSlides(divId);
				}
			});
			
			function indexSlides(id){
				if (slideTotal == 0){
					$(options.slideNavBox).css('display','none');
					$(options.mediaInfo).css('margin-top','-20px');
				}else{
				$("#"+id+" "+options.slideCount).html(slideNum + ' of ' + slideTotal);
				}
			}
		};
		return false;
	}
	
	function overlayVideo(loaded, $jqObj, index){
		var divId = ("overlayVideo-"+index);
		$("#overlay").fadeIn('fast');
		if(loaded == true){
			$('#'+divId+' '+options.overlayWrapper).fadeIn('fast');
		}else{
			var wrapper = $('<div id="'+divId+'">&nbsp;</div>');
			$('#addMedia').append(wrapper);
			showLoading(true, $jqObj);
			$('#'+divId).load(callers[index][0].href + ' '+options.overlayWrapper, function(){
				hideLoading(true, $jqObj);
				$('#'+divId+' '+options.overlayWrapper).fadeIn('fast');
				
				var vidPathTmp = $('#'+divId+' .path').html();
				var vidWidth = $('#'+divId+' .width').html();
				var vidHeight = $('#'+divId+' .height').html();
				var vidTitle = $('#'+divId+' .title').html();
				var vidAssetId = $('#'+divId+' .assetid').html();
				var vidServer = $('#'+divId+' .server').html();
				var vidFilePath = $('#'+divId+' .videoPath').html();
				var vidFilename = $('#'+divId+' .filename').html();
				var vidImage = $('#'+divId+' .img').html();
				var altContentId = (options.altContentContainer+vidAssetId);
				var vidID = ("video_"+vidAssetId);
				var vidRTMP = 'rtmp://'+vidServer+'/'+vidFilePath;
				var vidImgSrc = $(vidImage).attr("src");
				
				var params={	allowfullscreen: "true", allownetworking: "all", allowscriptaccess: "always" };
				var flashvars={ author: "University of Denver", file: vidFilename, title: vidTitle, type: "rtmp", height: vidHeight, skin: options.rootPath+options.skinPath, width: vidWidth, bufferlength: "10", stretching: "fill", id: vidID, plugins: "googlytics-1", streamer: vidRTMP }
				var attributes={id: vidID};
				swfobject.embedSWF((options.rootPath+options.playerPath), altContentId, vidWidth, vidHeight, "10", (options.rootPath+options.expressInstallPath), flashvars, params, attributes);
				
				close(divId, 'OV', vidID);
			});
		};
	}
	
	function inlineAudio($jqObj, index){
		var divId = ("inlineAudio-"+index);
		var audFlashWarning = '*To listen to audio clips, please <a href="http://www.adobe.com/go/getflashplayer">download the free Adobe Flash Player</a>.';
		var wrapper = $('<span class="inlineAudioWrapper"><span id="'+divId+'"></span></span>');
		$jqObj.after(wrapper);
		showLoading(false, $jqObj);
		if(swfobject.hasFlashPlayerVersion("9.0.0")){
			$('#'+divId).load(callers[index][0].href + ' .vars', function(){
				$jqObj.slideUp();
				hideLoading(false, $jqObj);
				var audPathTmp = ($('#'+divId+' .path').html());
				if(options.rootPathShort == options.rootPath){
					cleanAudPath=audPathTmp.replace(/\/WebSite\//gi, "/");
				}else{cleanAudPath=audPathTmp};
				
				var audWidth = $('#'+divId+' .width').html();
				var audTitle = $('#'+divId+' .title').html();
				var audAssetId = $('#'+divId+' .assetid').html();
				var autoStartVar = "false";
				if(('.'+callers[index][1]) == options.IAInit){autoStartVar="true"};
				
				var params={	allowfullscreen: "false", allownetworking: "all", allowscriptaccess: "always" };
				var flashvars={ author: "University of Denver", file: cleanAudPath, title: audTitle, type: "sound", height: "30", skin: options.rootPath+options.skinPath, width: audWidth, bufferlength: "10", stretching: "fill", id: divId, plugins: "googlytics-1", autostart:autoStartVar }
				swfobject.embedSWF((options.rootPath+options.playerPath), divId, audWidth, "30", "10", (options.rootPath+options.expressInstallPath), flashvars, params);
			});
		}else{$('#'+divId).append(audFlashWarning);}
	}	
	
	function overlayQT(loaded, $jqObj, index){
		var divId = ("overlayQT-"+index);
		$("#overlay").fadeIn('fast');
		if(loaded == true){
			$('#'+divId+' '+options.overlayWrapper).fadeIn('fast');
		}else{
			var wrapper = $('<div id="'+divId+'">&nbsp;</div>');
			$('#addMedia').append(wrapper);
			showLoading(true, $jqObj);
			$('#'+divId).load(callers[index][0].href + ' '+options.overlayWrapper, function(){
				var src=$('#'+divId+' embed').attr('src');
				if(options.rootPathShort == options.rootPath){
					newSrc=src.replace(/\/WebSite\//gi, "/");
				}else{newSrc=src};
				if(newSrc!=src){$('#'+divId+' embed').attr('src',(newSrc));}
				hideLoading(true, $jqObj);
				$('#'+divId+' '+options.overlayWrapper).fadeIn('fast');
				close(divId, 'OQT', index);
			});
		};
	}
	
	function overlaySWF(loaded, $jqObj, index){
		var divId = ("overlaySWF-"+index);
		$("#overlay").fadeIn('fast');
		if(loaded == true){
			$('#'+divId+' '+options.overlayWrapper).fadeIn('fast');
		}else{
			var wrapper = $('<div id="'+divId+'">&nbsp;</div>');
			$('#addMedia').append(wrapper);
			showLoading(true, $jqObj);
			$('#'+divId).load(callers[index][0].href + ' '+options.overlayWrapper, function(){
				
				var swfPathTmp = ($('#'+divId+' .path').html());
				if(options.rootPathShort == options.rootPath){
					cleanSWFPath=swfPathTmp.replace(/\/WebSite\//gi, "/");
				}else{cleanSWFPath=swfPathTmp};
				
				var swfWidth = $('#'+divId+' .width').html();
				var swfHeight = $('#'+divId+' .height').html();
				var swfTitle = $('#'+divId+' .title').html();
				var swfCaption = $('#'+divId+' .caption').html();
				if(swfTitle == ""){$('#'+divId+' '+options.overlayWrapper).addClass('plain'); }
				if(swfCaption == ""){$('#'+divId+' '+options.overlayWrapper).addClass('noCaption'); resizeOverlay(swfWidth, divId); }
				var swfAssetId = $('#'+divId+' .assetid').html();
				var swfId=(options.altContentContainer+swfAssetId);
				var attributes={id: "swf_"+swfAssetId};
				
				hideLoading(true, $jqObj);
				swfobject.embedSWF(cleanSWFPath, swfId, swfWidth, swfHeight, "9.0.0", (options.rootPathShort+options.expressInstallPath), false, false, attributes, reveal);
				function reveal(){$('#'+divId+' '+options.overlayWrapper).fadeIn('fast');}
				close(divId, 'OSWF', index);
			});
		};
	}
	
	function inlineSWF($jqObj, index){
		var divId = ("inlineAudio-"+index);
		var swfFlashWarning = 'Please <a href="http://www.adobe.com/go/getflashplayer">download the free Adobe Flash Player</a> to view dynamic content.';
		var wrapper = $('<span class="inlineAudioWrapper"><span id="'+divId+'"></span></span>');
		$jqObj.after(wrapper);
		showLoading(false, $jqObj);
		if(swfobject.hasFlashPlayerVersion("6.0.65")){
			$('#'+divId).load(callers[index][0].href + ' .vars', function(){
				$jqObj.slideUp();
				hideLoading(false, $jqObj);
				var swfPathTmp = ($('#'+divId+' .path').html());
				if(options.rootPathShort == options.rootPath){
					cleanSWFPath=swfPathTmp.replace(/\/WebSite\//gi, "/");
				}else{cleanSWFPath=swfPathTmp};
				
				var swfWidth = $('#'+divId+' .width').html();
				var swfHeight = $('#'+divId+' .height').html();
				var swfTitle = $('#'+divId+' .title').html();
				
				swfobject.embedSWF(cleanSWFPath, divId, swfWidth, swfHeight, "9.0.0", (options.rootPathShort+options.expressInstallPath));
			});
		}else{$('#'+divId).append(swfFlashWarning);}
	}
	
	/*GLOBALS*/
	function showLoading(overlay, $jqObj){
		if(overlay==true){
		$('#loading').fadeIn('fast');
		}else{ $jqObj.addClass('loading'); }
	}
	function hideLoading(overlay, $jqObj){
		if(overlay==true){
		$('#loading').fadeOut('fast');
		}else{ $jqObj.removeClass('loading');
		}
	}
	function resizeOverlay(width, id){
		intWidth=parseInt(width)+parseInt(options.resizePadding);
		$('#'+id+' '+options.overlayWrapper).css({'width': intWidth, 'margin-left': -(intWidth/2)});
	}
	function close (id, type, playerID){
		$('#overlay, '+"#"+id+" "+options.close).click(function(){
			if(swfobject.hasFlashPlayerVersion("9.0.0") && type=== "OV"){
				player=document.getElementById(playerID);
				player.sendEvent('PLAY', 'false');
			}
			$('#'+id+' '+options.overlayWrapper).fadeOut('fast');
			$('#'+id+'.currentSlide').slideUp('slow');
			$('#overlay').fadeOut('fast');
			type="";
			return false;
		});
	}
			
	return false;
};
})(jQuery);