/**
 * MessageBox2 Object
 * @author Avery Brooks
 * @copyright 2007
 */

// We really need you, buddy.  If you're not around, i'm making a new one.

if (typeof(BigEar) != "object") {var BigEar = new MasterListener();}
if (!BigEar.isAwake) {BigEar.startListening();}


function MessageBox(myName) {

	/* Vars */

	this.myName			= myName;

	this.divID          = "preview_pane";

	this.curID          = 1;
	this.maxZ           = 100000;
	this.numLayers      = 0;

	// topmost object in our pile (by ID)
	this.topLayer		= null;

	this.header         = "";
	this.message        = "";

	this.imageURL       = "";
	this.dataURL        = "";
	this.actionURL      = "";
	this.getData		= {};
	this.postData		= {};

	this.showBackground = true;
	this.showCurtain    = true;
	this.showNav		= true;
	this.showClose      = true;
	this.showCancel		= false; // only will currently test this in iframe mode - nobody else will check
	this.autoCenter     = true;

	// Apply CSS to body to prevent "jumpy" behavior?
	this.touchBody		= false;

	// Key Commands
	this.escapeKeyToClear	= true;
	this.enterKeyToConfirm	= true;

	this.popupType      = 0;
	this.popupTypes     = Array("message", "error", "prompt", "image", "ajax", "iframe");

	this.xscale         = null;
	this.yscale         = null;

	this.XCheckOffset	= 10;
	this.YCheckOffset	= 200;

	this.iconDir        = "/Presentation/Images/icons/30px/";
	this.iconFiles      = ["message.png","error.png","error.png"];

	this.loaderIcon     = "/Presentation/Images/icons/loader.gif";

	/* Methods */

	/**
	 * openLayer
	 */
	this.openLayer = function () {

		// Remove scrollbars?
		if (this.touchBody) {
			$("body").css("overflow","hidden");
			$("html").css("overflow","hidden");
		}

		// BUILD FRAMEWORK

		this.maxZ++;

		// Append new objects to doc
		var curObj = document.getElementById(this.divID);

		if (curObj) {
			var insertionPoint = curObj;
		} else {
			var insertionPoint = $("<div/>")
				.attr("id",this.divID)
				.appendTo("body");
		}

		var wrapper = $("<div/>")
			.attr("id","msg_wrapper_"+this.curID)
			.attr("class","msg_wrapper")
			.css("z-index",this.maxZ++)
			.appendTo(insertionPoint);

		// Do the rest
		this.topLayer = "msg_wrapper_"+this.curID;

		if (this.showBackground) {
			var background = $("<div/>")
				.attr("id","msg_background_"+this.curID)
				.addClass("msg_background")
				.css("z-index",this.maxZ++)
				.css("opacity",0)
				.appendTo(wrapper)
			this.makeFullSize(background);
			$(background).animate(
				{"opacity":.8},
				100
			);
		}

		var contents = $("<div/>")
			.attr("id","msg_contents_"+this.curID)
			.addClass("msg_contents");

		switch (this.popupType) {
			case 0:
				$(contents).addClass("msg_message");
				break;
			case 1:
				$(contents).addClass("msg_error");
				break;
			case 2:
				$(contents).addClass("msg_prompt");
				break;
			case 2:
				$(contents).addClass("msg_image");
				break;
		}

		$(contents).css("z-index",this.maxZ++);

		if (this.xscale != null && this.yscale != null) {
			$(contents)
				.css("width",this.xscale)
				.css("height",this.yscale);
		}

		$(wrapper).append(contents);

		if (this.showCurtain) {
			var curtain = $("<div/>")
				.attr("id","msg_curtain_"+this.curID)
				.addClass("msg_curtain")
				.css("z-index",this.maxZ++);

			if (this.showLoader) {
				// Add loader icon
				var loaderSpin = $("<img/>")
					.attr("id","loader_icon_"+this.curID)
					.addClass("loader_icon")
					.attr("src",this.loaderIcon);

				var pageVals = this.getPageSize();
				var centerX = (pageVals[2] - this.XCheckOffset) / 2 - 64 + this.getScrollLeft();
				var centerY = (pageVals[3] - this.YCheckOffset) / 2 - 64 + this.getScrollTop();

				$(loaderSpin)
					.css("position","absolute")
					.css("left",centerX)
					.css("top",centerY)
				.appendTo(curtain);
			}

			$(wrapper).append(curtain);
			this.makeFullSize(curtain);
		}

		// ADD CONTENT

		// HEADER / COPY ?

		if (this.popupType === 0 || this.popupType === 1 || this.popupType === 2) {

			var div_tag = document.createElement("div");

			var icon = $("<img/>")
				.attr("id","msg_icon_"+this.curID)
				.addClass("msg_icon")
				.attr("src",this.iconDir + this.iconFiles[this.popupType])
				.appendTo(div_tag);
		
			var h3_tag = $("<h3/>")
				.append(this.header)
				.appendTo(div_tag);

			var p_tag = $("<p/>")
				.append(this.message)
				.appendTo(div_tag);

			$(contents)
				.append(div_tag)
				.css("opacity",0)
				.css("float","none")
				.width(300)
				.css("height","auto");

			if (!this.autoCenter) {
				$(contents).css("margin-left",(-1 * $(contents).width() /2));
				$(contents).css("margin-top",(-1 * $(contents).height() / 2));
			}

			$(contents).animate(
				{"opacity":1},
				300
			);

		}

		// IMAGE ?

		if (this.popupType === 3) {

			var image_container = document.createElement("img");
			$(image_container).attr("id","image_preview"+this.curID);
			$(image_container).addClass("imagePreview");

			if (!$.browser.msie) {

				// All the good kids

				$(image_container).bind("load",Array(this.autoCenter,this.curID),function(e){
					if (!e.data[0]) {
						$(contents).css(
							"margin-left",
							(-1 * $(contents).width() / 2)
						);
						$(contents).css(
							"margin-top",
							(-1 * $(contents).height() / 2)
						);
					} else {
						centerObj_init("msg_contents_"+e.data[1]);
					}
					$(curtain)
						.empty()
						.fadeOut(
							300,
							function() {
								$(this).remove();
							}
						);
				});
				$(image_container).attr("src",this.imageURL);
				$(contents).append(image_container);

			} else {

				// IE is a big baby, so lets use an Image object to
				// load the data and fire our "load" event from that

				var ImageLoad = new Image();

				$(ImageLoad).bind("load",null,function(e){
					$(image_container).attr("src",$(ImageLoad).attr("src"));
				});

				$(image_container).bind("load",this.autoCenter,function(e){
					if (!e.data) {
						$(contents).css(
							"margin-left",
							(-1 * $(contents).width() / 2)
						);
						$(contents).css(
							"margin-top",
							(-1 * $(contents).height() / 2)
						);
					}
				});

				$(ImageLoad).attr("src",this.imageURL);
				$(contents).append(image_container);
			}
		}

		// AJAX LOAD ?

		if (this.popupType === 4) {
			var data_container = $("<div/>")
				.attr("id","data_container_"+this.curID);

			var scale_after_load = (this.yscale == null) ? true : false;

			$.get(
				this.dataURL,
				this.getData,
				function(data) {
					$(data_container).html(data);
					$(contents).append(data_container);
					$(contents).css("margin-left",0);
					if (scale_after_load) $(contents).css("margin-top",(-1 * $(contents).height() / 2));
			 		$(curtain).fadeOut(
			 			400,
			 			function() {
			 				$(curtain).remove();
			 			}
			 		);
				}
			);
		}

		// IFRAME POPOVER

		if (this.popupType === 5) {

			// This has to be encoded to apply to "fit" in the src attribute

			if (typeof(this.getData) == "object") {
				var dataGetParams = "?";
				for (i in this.getData) dataGetParams += (i + "=" + this.getData[i] + "&");
			}

			var iFrameHeight = (!this.showNav) ? "100%" : "90%";

			var data_container = $("<iframe/>")
				.attr("id","data_container_"+this.curID)
				.css("width","100%")
				.css("height",iFrameHeight)
				.css("border","0")
				.attr("src",this.dataURL+dataGetParams)
				.appendTo(contents);

			var centerWidth  = $(contents).width();
			var centerHeight = $(contents).height();
			// var centerWidth = this.xscale;
			// var centerHeight = this.yscale;

			/*
			$(contents)
				.css("margin-left",(-1 * centerWidth / 2))
				.css("margin-top",(-1 * centerHeight / 2));
				\*/

		}

		// BUILD NAV

		if (this.showNav) {

			// this.showClose == true --> dep?

			var nav_elements = document.createElement("div");
			$(nav_elements).attr("id","msg_nav_elements_"+this.curID);
			$(nav_elements).attr("class","msg_nav_elements");
			$(contents).append(nav_elements);

			if (this.popupType === 0 || this.popupType === 1 || (this.popupType === 5 && this.showClose)) {
	
				// OK Button for Message or Error
	
				var ok_button = document.createElement("button");
				$(ok_button).attr("id","msg_next_"+this.curID);
				$(ok_button).attr("class","msg_button");
				$(ok_button).append("ok");
				$(nav_elements).append(ok_button);

				$(ok_button).bind("click", this, function(e) {
					e.data.closeLayer(this.parentNode.parentNode.parentNode);
				});
				$(ok_button).focus();

			} else if (this.popupType === 2) {

				// OK / CANCEL actions for Prompt

				var ok_button = document.createElement("button");
				$(ok_button).attr("id","msg_ok_"+this.curID);
				$(ok_button).attr("class","msg_button");
				$(ok_button).append("ok");
				$(nav_elements).append(ok_button);

				$(ok_button).bind("click", this.actionURL, function(e) {
					window.location = e.data;
				});

				var cancel_button = document.createElement("button");
				$(cancel_button).attr("id","msg_cancel_"+this.curID);
				$(cancel_button).attr("class","msg_button");
				$(cancel_button).append("cancel");
				$(nav_elements).append(cancel_button);

				$(cancel_button).bind("click", this, function(e) {
					e.data.closeLayer(this.parentNode.parentNode.parentNode);
				});
				$(cancel_button).focus();

			}

			// show a system styled button to match java elements
			if (this.showCancel) {
				var cancel_button = document.createElement("button");
				$(cancel_button).attr("id","msg_cancel_"+this.curID);
				// $(cancel_button).attr("class","msg_button");
				$(cancel_button).attr("class","msg_button_system");
				$(cancel_button).append("&nbsp; Cancel &nbsp;");
				$(nav_elements).append(cancel_button);

				$(cancel_button).bind("click", this, function(e) {
					e.data.closeLayer(this.parentNode.parentNode.parentNode);
				});
				$(cancel_button).focus();
			}


			// Add notice text for "click anywhere?"
			if (this.popupType === 3) {
				var close_text = document.createElement("p");
				$(close_text)
					.append("Click anywhere to close.")
					.appendTo(nav_elements);
			}

			if (this.escapeKeyToClear) {
				// Escape to cancel
				$("body").bind(
					"keyup",
					this,
					function(e) {
						if (e.keyCode == 27) {
							e.preventDefault();
							$("body").unbind("keyup");
							e.data.closeLayer();
							return false;
						}
					}
				);
			}

			// Click anywhere to close?
			if (this.popupType === 0 || this.popupType === 3) {
				$(wrapper).bind("click", this, function(e) {
					e.data.closeLayer(this);
				});
			}
		}

		// Append new objects to doc

		if (this.autoCenter && $.browser.msie) {
			centerObj_init("msg_contents_"+this.curID);
		}
		// centerObj_init("msg_contents_"+this.curID);

		if (this.showCurtain && $.browser.msie) {
			now = new Date();
			stopTime = now.getTime() + 200;
			while (now.getTime() < stopTime) {now = new Date();}
			$("#msg_curtain_"+this.curID).empty();
			$("#msg_curtain_"+this.curID).fadeOut(400);
		} else if (this.showCurtain && this.popupType !== 3) {
			$("#msg_curtain_"+this.curID).fadeOut(200);
		}

		if (this.popupType !== 3) {
			centerObj_init("msg_contents_"+this.curID);
		}

		this.numLayers ++;
		this.curID ++;

		return;
	}

	/**
	 * closeLayer
	 */
	this.closeLayer = function (curObj) {

		if (!curObj) {
			if (this.topLayer) {
				curObj = document.getElementById(this.topLayer);
			} else {
				return;
			}
		}

		$(curObj).remove();
		this.numLayers --;
		if (this.numLayers == 0) {
			centerObj_destruct($(curObj).attr("id"));
			this.topObject = null;
		} else {
			this.topObject = "#msg_wrapper_"+this.numLayers;
		}
		// this dude is gonnnne!  reflect so in the object

		return;
	}

	/**
	 * fullSizeGo!
	 */
	this.fullSizeGo = function(curObj) {
		var sizeArray = this.getPageSize();
		$('#'+curObj).width(sizeArray[0]);
		$('#'+curObj).height(sizeArray[1]);
	}

	this.makeFullSize = function(curObj) {
		// Add Listener:
		parent.BigEar.addAction(this.myName+".fullSizeGo('"+$(curObj).attr("id")+"')",2);
		// Initial scale:
		var sizeArray = this.getPageSize();
		$(curObj).width(sizeArray[0]);
		$(curObj).height(sizeArray[1]);
	}

	this.getPageSize = function() {

		// The offsets hardcoded here are to fix some layout concerns with v1 layout of the CMS
		// Eg:  the document height
		// They can be removed when that is resolved

		return Array(
			($(window).width() > $(document).width() ? $(window).width() : $(document).width()) + this.XCheckOffset,
			($(window).height() > $(document).height() ? $(window).height() : $(document).height()) + this.YCheckOffset,
			$(window).width() + this.XCheckOffset,
			$(window).height() + this.YCheckOffset
		);

	}

	this.getScrollTop = function() {
		var scrollTop;
		if (window.pageYOffset){  
			scrollTop = window.pageYOffset 
		} else if(document.documentElement && document.documentElement.scrollTop){ 
			scrollTop = document.documentElement.scrollTop; 
		} else if(document.body){ 
			scrollTop = document.body.scrollTop; 
		}
	return scrollTop;
	}

	this.getScrollLeft = function() {
		var scrollLeft;
		if (window.pageXOffset){  
			scrollLeft = window.pageXOffset 
		} else if(document.documentElement && document.documentElement.scrollLeft){ 
			scrollLeft = document.documentElement.scrollLeft; 
		} else if(document.body){ 
			scrollLeft = document.body.scrollLeft; 
		}
	return scrollLeft;
	}

	/** Popover Launchers **/

	this.showMessage = function(newHeader,newMessage) {
		this.showLoader = false;
		this.setPopupType(0);
		this.setHeader(newHeader);
		this.setMessage(newMessage);
		this.showCurtain = true;
		this.setShowNav(true);
		this.setShowClose(true);
		this.openLayer();
		return;
	}

	this.showError = function(newHeader,newMessage) {
		this.showLoader = false;
		this.xscale = null;
		this.yscale = null;
		this.setPopupType(1);
		this.setHeader(newHeader);
		this.setMessage(newMessage);
		this.showCurtain = true;
		this.setShowNav(true);
		this.setShowClose(true);
		this.openLayer();
		return;
	}

	this.showPrompt = function(newHeader,newMessage,actionURL) {
		this.showLoader = false;
		this.xscale = null;
		this.yscale = null;
		this.setPopupType(2);
		this.setHeader(newHeader);
		this.setMessage(newMessage);
		this.setActionURL(actionURL);
		this.showCurtain = true;
		this.setShowNav(true);
		this.setShowClose(true);
		this.openLayer();
		return;
	}

	this.showImage = function(imageURL, XScale, YScale) {

		this.showLoader = true;

		// Setters will handle null etc
		this.setXScale(XScale);
		this.setYScale(YScale);

		this.setPopupType(3);
		this.setImageURL(imageURL);
		this.showCurtain = true;
		this.setShowNav(true);
		this.setShowClose(false);
		this.openLayer();
		return;
	}

	this.showURL = function(showURL, showClose, XScale, YScale, GetData) {

		this.showLoader = false;

		// Setters will handle null etc
		this.setXScale(XScale);
		this.setYScale(YScale);

		if (typeof(GetData) == "object") {
			this.getData = GetData;
		} else {
			this.getData = {};
		}

		this.setPopupType(4);
		this.setDataURL(showURL);
		this.setShowNav(showClose);
		this.setShowClose(showClose);
		this.showCurtain = true;
		this.openLayer();
		return;
	}

	this.showFramedURL = function(showURL, showClose, XScale, YScale, GetData, showCancel) {

		this.showLoader = false;

		// Setters will handle null etc
		this.setXScale(XScale);
		this.setYScale(YScale);

		if (typeof(GetData) == "object") {
			this.getData = GetData;
		} else {
			this.getData = {};
		}

		this.setPopupType(5);
		this.setDataURL(showURL);

		this.setShowNav(showClose || showCancel);
		this.setShowClose(showClose);
		this.setShowCancel(showCancel);

		this.showCurtain = false;
		this.autoCenter  = false;
		this.openLayer();

		return;
	}

	/** Setters **/

	this.setPopupType = function(popType) {
		if (this.popupTypes[popType]) {
			this.popupType = popType;
			return this.popupTypes[popType];
		} else {
			return false;
		}
	}

	this.setActionURL = function(actionURL) {
		this.actionURL = actionURL;
		return;
	}

	this.setImageURL = function(imageURL) {
		this.imageURL = imageURL;
		return;
	}

	this.setDataURL = function(dataURL) {
		this.dataURL = dataURL;
		return;
	}

	this.setHeader = function(newHeader) {
		this.header = newHeader;
		return;
	}

	this.setMessage = function(newMessage) {
		this.message = newMessage;
		return;
	}

	this.setShowClose = function(val) {
		this.showClose = (val == true) ? true : false;
		return;
	}

	this.setShowCancel = function(val) {
		this.showCancel = (val == true) ? true : false;
		return;
	}

	this.setShowNav = function(val) {
		this.showNav = (val == true) ? true : false;
		return;
	}

	this.setXScale = function(xval) {
		if(xval) {
			this.xscale = xval;
		} else if (xval == null || xval == 'undefined') {
			this.xscale = 'auto';
		}
		return;
	}

	this.setYScale = function(yval) {
		if(yval) {
			this.yscale = yval;
		} else if (yval == null || yval == 'undefined') {
			this.yscale = 'auto';
		}
		return;
	}

} // End of Object

