/**
 * Popup-related UI Handlers
 *
 * @author   Sean McCann
 * @version  1
 * @date     2007.01.27
 *
 * Changelog
 * - 2007-03-22:  Fixed bug where URI input was not being correctly escaped (Sean McCann)
 * - 2007-03-08:  Stripped is_array() check from PopupFill to make it Safari-compatible (Gabe)
 * - 2007-01-27:  Initial code written (Sean McCann)
 *
 */

function PopupCreate() {
	var popup;

	// Create a new popup wrapper
	popup = document.createElement('div');
	popup.className = 'popup-wrapper';
	popup.style.position = 'absolute';

	// Position the popup semi-randomly near
	// the center of the browser window
	var x_position = (parseInt(getPageWidth()) / 2) - 175;
	var x_entropy = Math.floor(Math.random() * getPageWidth()/10);
	var y_position = parseInt(getPageYOffset()) + parseInt(getPageHeight()) / 4;
	var y_entropy = Math.floor(Math.random() * getPageHeight()/5);

	popup.style.top = (y_position + y_entropy) + 'px';
	popup.style.left = (x_position + x_entropy) + 'px';

	// ...and stick it into our document
	document.body.appendChild(popup);

	return popup;
}


function PopupRequest( url, handler ) {
	dao.requestData(url, handler);
}

function PopupClose( id ) {
	/**
	 * Ok, this is really strange, but it has everything to do with scope, iframes,
	 * and the popular Prototype library.  Here's the quick explanation:
	 *
	 * - The $() function is essentially an alias for document.getElementById().
	 *   	It was popularized by the Prototype library, and reimplemented for Mudbug in common.functions.js
	 * - Sometimes, PopupClose() is called from within an <iframe>.  In those cases,
	 *   	 the id of the element that needs to be closed can only be reached using "parent.document.getElementById()"
	 * - To accommodate being called from either situation, our local implementation of
	 *   	$() was changed to use "this.document.getElementById()" if it exists.  This allows us to use the call()
	 *   	method of an object to change the document scope.  for instance:  $.call(parent, 'some_id')
	 * - PopupClose() is called directly, so the scope of PopupClose (ie. "this") must be passed to $().  The "close"
	 *   	button in the iframe runs "PopupClose.call(parent, id)", then PopupClose() performs the following line, and
	 *   	finally, $() runs "this.document.getElementById()".
	 */
	var popup = $.call(this, id);

	/**
	 * for technical reasons, all popups
	 * are encased in an automatically created
	 * wrapper element
	 */
	var wrapper = popup.parentNode;

	// remove the popup and its wrapper
	wrapper.parentNode.removeChild(wrapper);
}


function PopupFill( id ) {
	var popup;

	if (dao.requestIsComplete()) {
		var data = dao.getData();

		// If we didn't get anything at all, just exit
		// as if nothing ever happened
		if (data == "") return true;

		// Sometimes our popup controller will return a piece
		// of javascript for us to execute.  Check the Content-Type
		// of the response before proceeding
		var content_type = trim(dao.getResponseHeader("Content-Type"));
		if (content_type.search(/^text\/javascript;/) != -1) {
			PopupClose(id);
			eval(data);

			// eval'ing the returned data will probably executing something
			// that displays updates for a portion of our page.  Since this
			// can cause issues with overflow in our layout body, we need
			// to recalculate the height each time we assume that some part
			// of the page is updated
			// NOTE: we don't need this for the Stryker Southeast site
			// fix_height('body_container');
		}
		else {
			// If our popup window doesn't already
			// exist, create it.
			try {
				popup = $(id).parentNode;
			}
			catch (e) {
				popup = PopupCreate();
			}

			// Load our data into the popup window
			popup.innerHTML = data;

			// Tell the form in the popup how to submit Ajax-style
			var i;
			var forms = popup.getElementsByTagName('form');

			for (i = 0; i < forms.length; i++){
				forms[i].onsubmit = AjaxFormSubmit;
				forms[i].response_handler = function(){ return PopupFill( id ); }	// used by AjaxFormSubmit
			}
		}

		return true;
	}
	else {
		return false;
	}
}


/**
 * Makes it possible to submit a form without
 * reloading the entire page
 *
 * NOTE: this function expects to be executed as
 * a method of the form in question
 */
function AjaxFormSubmit() {
	var i;

	// Build a query string to send form data via GET
	var query_string = '';

	// Set the URI encoding function to use.
	// encodeURIComponent(), part of Javascript 1.5 Core, is
	// the recommended function to use in these scenarios.
	// escape(), which is older and more widely supported,
	// doesn't correctly translate all characters and lacks
	// Unicode support.
	var encodeURI = (typeof(encodeURIComponent) != 'undefined') ? encodeURIComponent : escape;

	for (i = 0; i < this.elements.length; i++) {

		// Don't submit unchecked checkbox and radio buttons
		if (! ((this.elements[i].type == 'radio' || this.elements[i].type == 'checkbox') && !this.elements[i].checked) )
		{
			query_string += (query_string) ? '&' : '?';
			query_string += this.elements[i].name + '=' + encodeURI(this.elements[i].value);
		}
	}

	// Submit our form data using our AJAX methodology.
	// Note:  When this form was initially created, a "response_handler"
	// was registered with the form so that we could tell our DAO how
	// to handle the data that is returned from the form processing script
	dao.requestData(this.action + query_string, this.response_handler);

	return false;
}

function RefreshElement( id ) {
	if (dao.requestIsComplete()) {
		var data = dao.getData();
		var container = $.call( this, id );
		container.innerHTML = data;

		// Refreshing our element can cause overflow issues in our layout.
		// We will need to recalculate the height of the main layout container
		// each time we update a part of the page.

		// NOTE: We don't have a "body_container" element in this site.
		// Interestingly enough, this does not produce problems in most
		// browsers, but IE6 freaks out.  For now, we're leaving this out
		//
		// fix_height.call(this, 'body_container');

		return true;
	}
	else {
		return false;
	}
}
