var movie_viewer = new MovieViewer();

function MovieViewer()
{
	// Our elements.
	this.BACKGROUND_DIV 	= "overlayblackout";
	this.FOREGROUND_DIV 	= "popin";
	this.FLASH_DIV			= "popmovie";

	// Names of our superbanners at the top and bottom
	var BANNER_NAMES		= new Array("topsuperbanner", "bottomsuperbanner", "banner200200");

	// URL to fetch our text ads from
//	var TEXT_AD_URL			= "http://3.adbrite.com/mb/text_group.php?sid=40759&br=1&dk=706572736f6e616c735f31";
//	var TEXT_AD_ADULT_URL	= "http://ads.adbrite.com/mb/text_group.php?sid=576150&br=1&dk=706572736f6e616c735f315f335f776562";

	var TEXT_AD_URL			= "http://server.cpmstar.com/view.aspx?poolid=1134&script=1";
	var TEXT_AD_ADULT_URL	= "http://server.cpmstar.com/view.aspx?poolid=1182&script=1";

	// Dimensions of the Heavy stuff
	var HEAVY_WIN_WIDTH		= 990;
	var HEAVY_WIN_HEIGHT	= 520;

	// This can only be set once.
	var activeuser_id = null;
	var activeuser_name = null;
	var activeuser_session = null;

	// Transitions go here.
	this.EFFECTS_IN = 0.05;
	this.EFFECTS_OUT = 0.15;

	var ourbody, pbackground;
	var movie_width, movie_height, window_min_width, content_type;
	var have_text_ad = false;
	var show_heavy = false;

	// flag to indicate if movie is already displayed
	var is_displayed = false;

	this.Launch = function(title, movie, width, height, min_width, content_rating)
	{
		if (!is_displayed) {
			is_displayed = true;

			// First thing, let's see if we're doing the Heavy ad here or not
			if(document.getElementById("show_heavy"))
			{
				show_heavy = true;
			}

			// Insert our movie
			var flash_writer = new FlashWriter(movie, width, height);
			flash_writer.SetScriptAccess("never");
			flash_writer.SetFullScreen(true);

			var f_params = new Array();

			if(activeuser_name != null && activeuser_id != null)
			{
				f_params.push("ng_username=" + activeuser_name);
				f_params.push("NewgroundsAPI_UserName=" + activeuser_name);
				f_params.push("NewgroundsAPI_UserID=" + activeuser_id);
			}
			if(activeuser_session != null)
			{
				f_params.push("NewgroundsAPI_PublisherID=1");
				f_params.push("NewgroundsAPI_SessionID=" + activeuser_session);
			}

			if (f_params.length > 0) {
				flash_writer.SetParams(f_params.join("&"));
			}

			GetElement(movie_viewer.FLASH_DIV).innerHTML = flash_writer.ToString();

			// Let's scrap the super banners.
			ToggleBanners("hidden");

			// Get our values for repetitive use.
			movie_width = width;
			movie_height = height;
			window_min_width = min_width;
			content_type = content_rating;

			// 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(http://img.ngfiles.com/blackbox.png)";
				pbackground.style.backgroundRepeat = "repeat";
			}

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

			// Insert our player ad
			/*if(show_heavy)
			{
				Husky.start("huskyad");
			}
			else
			*/
			if(!(have_text_ad))
			{
				if((content_type) && (!(InArray(content_type, new Array("e", "t")))))
					InsertTextAd(true);
				else
					InsertTextAd();

				have_text_ad = true;
			}

			// 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\">Newgrounds Presents:</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 = (show_heavy ? HEAVY_WIN_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;

		if(!(show_heavy))
		{
			// 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";
		}
		else
		{
			popup_height = HEAVY_WIN_HEIGHT;
			popup_width = HEAVY_WIN_WIDTH;
		}

		// 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;

		if(show_heavy)
		{
			// Beware the hard-coded stuff here.
			var player_element = document.getElementById("player-wrap");
			top = Round((HEAVY_WIN_HEIGHT - (movie_height + 50)) / 2);
			if(top < 0)
			{
				top = 0;
			}

			player_element.style.top = top + "px";
			player_element.style.left = "217px";		// 217 instead of 220... WTF?
		}
	}

	this.Cancel = function()
	{
		// We have to scrap the flash from inside of the div.
		GetElement(movie_viewer.FLASH_DIV).innerHTML = "&nbsp;";

		if(show_heavy)
		{
			Husky.stop();
		}

		// Bring our ads back.
		ToggleBanners("visible");

		// 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");

		is_displayed = false;
	}

	this.SetActiveUser = function(id,name)
	{
		if(activeuser_name == null)
		{
			activeuser_name = name;
		}
		if(activeuser_id == null)
		{
			activeuser_id = id;
		}
	}

	this.SetActiveSession = function(session_id)
	{
		if(activeuser_session == null)
		{
			activeuser_session = session_id;
		}
	}

	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(document.documentElement && document.documentElement.clientWidth)
		{
			dimensions[0] = document.documentElement.clientWidth;
			dimensions[1] = document.documentElement.clientHeight;
		} else
		if(self.innerWidth)
		{
			dimensions[0] = self.innerWidth;
			dimensions[1] = self.innerHeight;
		} else
		if(document.body)
		{
			dimensions[0] = document.body.clientWidth;
			dimensions[1] = document.body.clientHeight;
		}

		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 ToggleBanners(state)
	{
		var banner;
		for(var i=0; i<BANNER_NAMES.length; i++)
		{
			banner = GetElement(BANNER_NAMES[i]);
			if(banner)
			{
				banner.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 AdultAds()
	{
		GetElement("popad_textlink").href = "http://www.adbrite.com/mb/commerce/purchase_form.php?opid=576150&afsid=55544";
	}*/

	// NOTE: should we need to revert to text ads, this will be what handles it.
	function InsertTextAd(is_adult)
	{
		// Thanks to http://www.mikeonads.com/category/ad-networks/ for this!
		// It captures the document.write()s from the ad and inserts them properly.
		// First we override document.write()
		(function(){

			function SetAd(ad)
			{
				var values = GetCPMStarValues(ad);
				var ad_headline = document.getElementById("popin_cpmstarHeadline");
				var ad_body = document.getElementById("popin_cpmstarText");

				ad_headline.href = values["link"];
				ad_headline.innerHTML = values["title"];
				ad_body.href = values["link"];
				ad_body.innerHTML = values["desc"];

				// GetElement("popin_ad").innerHTML = ad;		// For AdBrite
			}

			if( typeof( Document)!='undefined' && typeof( HTMLDocument)!='undefined' ){
				// Gecko, Firefox, Opera
				HTMLDocument.prototype.write = function(s){
					SetAd(s);
					document.close();
				};
			}else if(document.uniqueID && document.expando){
				// Internet Explorer
				document.write = function(s){
					 SetAd(s);
					 document.close();
				}
			}else if(document.constructor){
				// Safari
				document.write  = function(s){
					SetAd(s);
				};
			}
		})();

		// Now insert the script stuff, and let the above code handle the output
		var script_element = document.createElement("script");
		script_element.setAttribute("type", "text/javascript");
		script_element.setAttribute("src", (is_adult ? TEXT_AD_ADULT_URL : TEXT_AD_URL));

		var ad_container = GetElement("popadtextoutter");
		ad_container.appendChild(script_element);
//		ad_container.removeChild(ad_container.firstChild);	// Opera hack - ???

// Not needed for the CPMStar stuff - was needed for AdBrite
//		if(is_adult)
//		{
//			AdultAds();
//		}
	}

	function GetCPMStarValues(ad_js)
	{
		var values = new Array();
		var matches;

		matches = /cpmStarAdInfo\['title'\]\s*=\s*'(.+[^\\])'/i.exec(ad_js);
		values["title"] = (matches == null) ? "unknown" : matches[1];

		matches = /cpmStarAdInfo\['desc'\]\s*=\s*'(.+[^\\])'/i.exec(ad_js);
		values["desc"] = (matches == null) ? "unknown" : matches[1];

		matches = /cpmStarAdInfo\['link'\]\s*=\s*'(.+[^\\])'/i.exec(ad_js);
		values["link"] = (matches == null) ? "unknown" : matches[1];

		return(values);
	}
}
