var movie_viewer = new MovieViewer();

function MovieViewer()
{
	// Our elements.
	this.BACKGROUND_DIV 	= "overlayblackout";
	this.FOREGROUND_DIV 	= "popin";
	this.FLASH_DIV			= "popmovie";
	
	// Transitions go here.
	this.EFFECTS_IN = 0.05;
	this.EFFECTS_OUT = 0.15;

	var ourbody, pbackground;
	var movie_width, movie_height, window_min_width;

	this.Launch = function(title, movie, width, height, min_width, swfpath)
	{
		// Get our values for repetitive use.
		window_min_width = min_width;
		if ((InnerDimensionsInfo()[0]) / width * height > (InnerDimensionsInfo()[1]-23)){
			movie_width = Round((InnerDimensionsInfo()[1]-23) / height * width);
			movie_height = InnerDimensionsInfo()[1]-23;
		}else{
			movie_width = InnerDimensionsInfo()[0];
			movie_height = Round((InnerDimensionsInfo()[0]) / width * height);
		}

		// Insert our movie
		var flash_writer = new FlashWriter(movie, movie_width-20, movie_height-20, swfpath);
		flash_writer.SetScriptAccess("never");
		
		GetElement(movie_viewer.FLASH_DIV).innerHTML = flash_writer.ToString();

		// Set up our background and append it to the body.
		ourbody = document.getElementsByTagName("body").item(0);
		pbackground = document.createElement("div");

		if(!(IsFirefoxMac()))
		{
			pbackground.setAttribute("id", movie_viewer.BACKGROUND_DIV);
		}
		else
		{
			// Mac Firefox can't handle opacity stuff, so let's do a workaround.
			movie_viewer.BACKGROUND_DIV = "overlayblackout_ffmac";
			pbackground.setAttribute("id", movie_viewer.BACKGROUND_DIV);
			pbackground.style.backgroundImage = "url(blackbox.png)";
			pbackground.style.backgroundRepeat = "repeat";
		}

		pbackground.style.display = 'none';
		ourbody.appendChild(pbackground);

		// Position stuff before we start displaying things
		this.CalibrateMoviePos();

		// Add an event handler for when the user resizes/scrolls the page
		SetEventHandler("resize", this.CalibrateMoviePos);
		SetEventHandler("scroll", this.CalibrateMoviePos);

		ToggleSelects("hidden");
		GetElement(movie_viewer.BACKGROUND_DIV).style.display = "block";

		// Set the title text.
		GetElement("popmovietitle").innerHTML = "<span class=\"shortpres\">NK Flash:</span> " + title;

//		if(!(IsFirefoxMac()))
//		{
//			new Effect.Appear(GetPopup());
//		}
//		else
//		{
			// Firefox/Mac can't handle fading in Flash
			GetPopup().style.display = "block";
//		}
	}

	this.CalibrateMoviePos = function()
	{
		// Let's set up the positioning of the background and the container,
		// prior to doing anything else.
		var popup_element = GetPopup();
		popup_element.style.width = (Math.max(movie_width, window_min_width) + 20) + "px";

		// This needs to be set, for centering purposes.
		GetElement(movie_viewer.FLASH_DIV).style.width = movie_width + "px";

		var background_element = GetElement(movie_viewer.BACKGROUND_DIV);
		background_element.style.top = 0 + "px";
		background_element.style.left = 0 + "px";
		background_element.style.width = ScrollDimensionsInfo()[0] + "px";
		background_element.style.height = ScrollDimensionsInfo()[1] + "px";
		background_element.style.zIndex = 20;

		var popup_height;
		var popup_width;
		
		// Little trick to get the dimensions of a possibly hidden element
		var element_hidden = (popup_element.style.display == "none");

		popup_element.style.visibility = "hidden";
		popup_element.style.display = "block";
		popup_height = popup_element.clientHeight;
		popup_width = popup_element.clientWidth;

		if(element_hidden)
		{
			popup_element.style.display = "none";
		}
		popup_element.style.visibility = "visible";

		// Now calculate our location based on scrolling and window size
		var top = Round((InnerDimensionsInfo()[1] - popup_height) / 2);
		if(top < 0)
		{
			top = 0;
		}
		top += GetPageScrolledPosition()[1];

		var left = Round((InnerDimensionsInfo()[0] - popup_width) / 2);
		if(left < 0)
		{
			left = 0;
		}
		left += GetPageScrolledPosition()[0];

		popup_element.style.top = top + "px";
		popup_element.style.left = left + "px";
		popup_element.zIndex = 99;
		
	}

	this.Cancel = function()
	{
		// We have to scrap the flash from inside of the div.
		GetElement(movie_viewer.FLASH_DIV).innerHTML = "&nbsp;";
		
		// Let's get rid of that event listener
		RemoveEventHandler("resize", this.CalibrateMoviePos);
		RemoveEventHandler("scroll", this.CalibrateMoviePos);

		// Get rid of our movie.
		GetElement(movie_viewer.BACKGROUND_DIV).style.display = "none";
		GetPopup().style.display = "none";

		// Show the select boxes again.
		ToggleSelects("visible");
	}
	
	function GetElement(id)
	{
		return(document.getElementById(id));
	}

	function GetPopup()
	{
		return(GetElement(movie_viewer.FOREGROUND_DIV));
	}

	// Browser related functions.
	function InnerDimensionsInfo()
	{
		var dimensions = new Array(2);
		
		if(self.innerWidth)
		{
			dimensions[0] = self.innerWidth;
			dimensions[1] = self.innerHeight-20;
		}else
		if(document.documentElement && document.documentElement.clientWidth)
		{
			dimensions[0] = document.documentElement.clientWidth;
			dimensions[1] = document.documentElement.clientHeight-20;
		} else
		if(document.body)
		{
			dimensions[0] = document.body.clientWidth;
			dimensions[1] = document.body.clientHeight-20;
		}

		return(dimensions);
	}

	function ScrollDimensionsInfo()
	{
		var dimensions = new Array(2);

		if(window.innerHeight && window.scrollMaxY)
		{
			dimensions[0] = document.body.scrollWidth;
			dimensions[1] = window.innerHeight + window.scrollMaxY;
		} else
		if(document.body.scrollHeight > document.body.offsetHeight)
		{
			dimensions[0] = document.body.scrollWidth;
			dimensions[1] = document.body.scrollHeight;
		} else
		{
			dimensions[0] = document.body.offsetWidth;
			dimensions[1] = document.body.offsetHeight;
		}

		return(dimensions);
	}

	function GetPageScrolledPosition()
	{
		var dimensions = new Array(2);

		if(self.pageYOffset)
		{
			dimensions[0] = self.pageXOffset;
			dimensions[1] = self.pageYOffset;
		}
		else if((document.documentElement) && (document.documentElement.scrollTop))
		{
			dimensions[0] = document.documentElement.scrollLeft;
			dimensions[1] = document.documentElement.scrollTop;
		}
		else if(document.body)
		{
			dimensions[0] = document.body.scrollLeft;
			dimensions[1] = document.body.scrollTop;
		}

		return(dimensions);
	}
	
	function ToggleSelects(state)
	{
		var selects = document.getElementsByTagName("select");
		for(var i = 0; i != selects.length; i++)
		{
			selects[i].style.visibility = state;
		}
	}
	
	function SetEventHandler(eventname, handler)
	{
		if(window.addEventListener)
		{
			window.addEventListener(eventname, handler, false);
		}
		else if(window.attachEvent)
		{
			window.attachEvent("on" + eventname, handler);
		}
	}

	function RemoveEventHandler(eventname, handler)
	{
		if(window.removeEventListener)
		{
			window.removeEventListener(eventname, handler, false);
		}
		else if(window.detachEvent)
		{
			window.detachEvent("on" + eventname, handler);
		}
	}

	// Necessary for an ugly hack - FF/Mac can't handle Flash combined with CSS opacity
	function IsFirefoxMac()
	{
		var userAgent = navigator.userAgent.toLowerCase();
  		return((userAgent.indexOf('mac') != -1) && (userAgent.indexOf('firefox') != -1));
	}

	function Round(num, precision)
	{
		if(typeof precision == "undefined")
		{
			precision = 0;
		}
	
		var multiplier = Math.pow(10, precision);
	
		return(Math.round(num * multiplier) / multiplier);
	}

// Use this to properly write out the HTML for any Flash.
function FlashWriter(url, width, height, swfpath)
{
	// Options here are "window", "opaque", and "transparent"
	var DEFAULT_WINDOW_SETTING = "window";

	// Defaults for optional stuff below
	var quality = "high";
	var id = "flash" + GetRandomNumber(1000000, 9999999);
	var wmode = DEFAULT_WINDOW_SETTING;
	var script_access = "sameDomain";
	var allow_fullscreen = "false";
	var params = "path="+swfpath+"/";
	var has_flash = LookForFlashPlugin();

	this.SetQuality = function(new_quality)
	{
		quality = new_quality;
	}

	this.SetID = function(new_id)
	{
		id = new_id;
	}

	this.SetTransparent = function(is_transparent)
	{
		wmode = is_transparent ? "transparent" : DEFAULT_WINDOW_SETTING;
	}

	this.SetFullScreen = function(fullscreen)
	{
		allow_fullscreen = fullscreen ? "true" : "false";
	}

	this.SetScriptAccess = function(new_script_access)
	{
		script_access = new_script_access;
	}

	this.ToString = function()
	{
		var str = "";

		if(has_flash)
		{
			str += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="' + width + '" height="' + height + '" id="' + id + '">';

			str += '<param name="allowScriptAccess" value="' + script_access + '" />';
			str += '<param name="allowFullScreen" value="' + allow_fullscreen + '" />';
			str += '<param name="menu" value="false" />';
			str += '<param name="movie" value="' + url + '" /><param name="quality" value="' + quality + '" />';
			str += '<param name="wmode" value="' + wmode + '" />';

			if(swfpath != 'drpaths')
			{
				// IE needs this
				str += '<param name="flashvars" value="' + params + '" />';
			}

			str += '<embed src="' + url + '" quality="' + quality + '" ';

			if(swfpath != 'drpaths')
			{
				// Non-IE browsers need this
				str += 'flashvars="' + params + '" ';
			}

			str += 'wmode="' + wmode + '" width="' + width + '" height="' + height + '" name="' + id + '" allowScriptAccess="' + script_access + '" allowFullScreen="' + allow_fullscreen + '" menu="false" type="application/x-shockwave-flash" pluginspage="http://www.adobe.com/go/getflashplayer" />';
			str += '</object>';
		}
		else
		{
			str += '<p style="text-align: center; margin-top: 2em; margin-bottom: 2em; padding-top: 3em; padding-bottom: 3em; background: #333333">You don\'t appear to have <a target="_blank" href="http://www.adobe.com/go/getflashplayer">Flash</a> installed. <a target="_blank" href="http://www.adobe.com/go/getflashplayer">Click here</a> to get it (it\'s free).</p>';
		}

		return(str);
	}

	this.Print = function()
	{
		document.write(this.ToString());
	}

	function LookForFlashPlugin()
	{
		var flash_versions = 12;

		if (navigator.plugins && navigator.plugins.length) {
			// Netscape style plugin detection
		    for (x = 0; x <navigator.plugins.length; x++) {
		        if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {
		            return(true);
		        }
		    }
		}
		else if (window.ActiveXObject) {
			// ActiveX style plugin detection
		    for (x = 2; x <= flash_versions; x++) {
		        try {
		            oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
		            if (oFlash) {
		                return(true);
		            }
		        }
		        catch(e) { }
		    }
		}

		return(false);
	}

	function GetRandomNumber(low, high)
	{
		return(Math.floor((Math.random() * (high - low + 1)) + low));
	}
	
}

}
