var Global = {};

Global.MENU = [{ url: 'about.html', caption: 'About Us' },
	{ url: 'alex_visco.html', caption: 'Meet The Team', menu: [
		{ url: 'alex_visco.html', caption: 'Alex Visco, MD' },
		{ url: 'michael_kelly.html', caption: 'Michael Kelly, DC' },
		{ url: 'juan_nunez.html', caption: 'Juan C. Nunez, DPT' },
		{ url: 'renee_kilianski.html', caption: 'Renee Kilianski' },
		{ url: 'constance_bliszcz.html', caption: 'Constance Bliszcz' }] },
	{ url: 'conditions.html', caption: 'Conditions We Treat' },
	{ url: 'pain.html', caption: 'Pain Management' },
	{ url: 'phys_ther.html', caption: 'Physical Therapy' },
	{ url: 'chiropractic.html', caption: 'Chiropractic' },
	{ url: 'success_stories.html', caption: 'Success Stories' },
	{ url: 'contact.html', caption: 'Contact' }];

Global.onLoad = function()
{
	// Get the file name.
	var i, p, h = window.location.href;
	i = h.lastIndexOf('/');
	if ((0 <= i) && (h.length > i))
		p = h.substr(i + 1);

	var o = document.getElementById('mainMenu');
	o.innerHTML = '';
	o.appendChild(document.createElement('span'));	// For the left corner.
	o.appendChild(this.createMenu(this.MENU, 0, p));
}

Global.swapImage = function(elem, src)
{
	// Get the first child, which should be image.
	var img = elem.firstChild;
	if (!img)
		return;

	img.originalSrc = img.src;
	img.src = src;
}

Global.restoreImage = function(elem)
{
	// Get the first child, which should be image.
	var img = elem.firstChild;
	if (!img)
		return;

	img.overSrc = img.src;
	img.src = img.originalSrc;
}

Global.gotoNewsletter = function()
{
	var o = NewsletterDOM.generate();

	ModalDialog.open('Newsletter Signup', o);
	o.myFirstField.focus();

	return false;
}

Global.gotoHealthCareSuccess = function()
{
	window.open('http://www.healthcaresuccess.com/','','menubar=yes,scrollbars=yes,resizable=yes,width=1000,height=700');
	return false;
}

Global.openMap = function()
{
	window.open('http://www.mapquest.com/maps?address=739+Bloomfield+Street&city=Hoboken&state=NJ&country=US','','menubar=yes,scrollbars=yes,resizable=yes,width=1000,height=900');
	return false;
}

Global.createMenu = function(v, l, p)
{
	var o = document.createElement('div');
	o.className = (0 == l) ? 'menu' : 'submenu';

	for (var i = 0; i < v.length; i++)
		o.appendChild(this.createItem(v[i], l, p));

	return o;
}

Global.createItem = function(item, level, path)
{
	var a = document.createElement('a');
	var b = false;

	// Determine if the current item is selected.
	if (path)
	{
		// If not selected, check it's children, too.
		if (!(b = (item.url == path)) && item.menu)
		{
			for (var i = 0; i < item.menu.length; i++)
				if (b = (item.menu[i].url == path))
					break;
		}
	}

	item.level = level;	// Need to know the depth.

	a.href = item.url;
	a.innerHTML = item.caption;
	a.myItem = item;
	a.onmouseout = this.menu_onMouseOut;
	a.onmouseover = this.menu_onMouseOver;
	a.className = (b ? 'selected' : '');

	return a;
}

Global.menu_onMouseOver = function(ev)
{
	var e = this.myItem;
	var p, l = e.level;

	// For children (level greater than zero) make sure the parent stays open
	if ((0 < l) && ((p = this.parentNode).openedTimeoutId))
	{
		clearTimeout(p.openedTimeoutId);
		p.openedTimeoutId = undefined;	// IE doesn't like the DELETE statement.
	}

	// Also, make sure that any children menus stay open.
	if ((p = this.openedMenu) && p.openedTimeoutId)
	{
		clearTimeout(p.openedTimeoutId);
		p.openedTimeoutId = undefined;

		// DO not need to recreate this menu.
		return;
	}

	// Any submenu?
	if (!e.menu)
		return;

	var o = this.openedMenu = Global.createMenu(e.menu, l + 1);
	document.body.insertBefore(o, document.body.firstChild);
	Positioner.under(this, o);
}

Global.menu_onMouseOut = function(ev)
{
	var me = this;
	var a = this.openedMenu;

	// Close any children menus.
	if (a)
		a.openedTimeoutId = setTimeout(function() { Global.closeMenu(a, me); }, 500);

	// DO NOT close the main menu so check for the level.
	if (0 < this.myItem.level)
	{
		// DO NOT resuse the variable above. Separate needed for each inline function.
		var b = this.parentNode;
		b.openedTimeoutId = setTimeout(function() { Global.closeMenu(b); }, 500);
	}
}

Global.closeMenu = function(elem, parent)
{
	// Make sure it's ready to close.
	if (!elem.openedTimeoutId)
		return;

	document.body.removeChild(elem);
	elem.openedTimeoutId = undefined;
	if (parent)
		parent.openedMenu = undefined;
}

/** AJAX helper base class.
* 
* Subclass must set the rootPath member variable.
*/
var Ajaxer = {}

/** Constants. */
Ajaxer.CONTENT_TYPE_POST = 'application/x-www-form-urlencoded; charset=utf-8';
Ajaxer.CONTENT_TYPE_XML = 'text/xml; charset=utf-16';

//Gets an XMLHttpRequest object for different browsers.
Ajaxer.getRequester = function()
{
	if (window.XMLHttpRequest)
		return new XMLHttpRequest();

	return new ActiveXObject('Microsoft.XMLHTTP');
}

Ajaxer.handleReadyStateChange = function(req, callback, url, map, data)
{
	if (4 != req.readyState)
		return;

	if (200 == req.status)
		window.alert(req.responseText);
}

/** Makes a async call to post data. */
Ajaxer.asynchPostMap = function(url, map, callback)
{
	var data = this.serializeParams(map);
	var req = this.getRequester();
	var me = this;
	req.open('POST', url, true);
	req.setRequestHeader('Content-Type', this.CONTENT_TYPE_POST);	
	req.onreadystatechange = function() { me.handleReadyStateChange(req, callback, url, map, data); }
	req.send(data);	
}

Ajaxer.serializeParams = function(map)
{
	var data = '';

	for (var id in map)
	{
		var value = map[id];
		if (undefined == value)
			continue;

		// For dates.
		else if (undefined != value.getTime)
		{
			if (0 < data.length)
				data+= '&';
	
			data+= id + '=' + escape(value.getTime());
		}

		// For arrays.
		else if ((undefined != value.length) && (typeof(value) != 'string'))
		{
			for (var i = 0; i < value.length; i++)
			{
				if (0 < data.length)
					data+= '&';
		
				data+= id + '=' + escape(value[i]);
			}
		}
		else
		{
			if (0 < data.length)
				data+= '&';
	
			data+= id + '=' + escape(value);
		}
	}

	return data;
}

/** Handles simple HTML INPUT controls.
	@param doc The appropriate window.document object. Useful for popups.
*/
var Inputter = {}

Inputter.generate = function(name, type, isChecked)
{
	if (document.all)
	{
		var checked = isChecked ? ' checked' : '';
		return document.createElement('<input name="' + name + '" type="' + type + '"' + checked + ' />');
	}
	
	var output = document.createElement('input');
	if (window.isSafari) output.id = name;	// Otherwise doesn't register as an element in the form.
	output.name = name;
	output.type = type;
	output.checked = isChecked;
	
	return output;
}

Inputter.genButton = function(name, caption, onclick)
{
	var output = this.generate(name, 'button');

	output.value = caption;
	if (undefined != onclick)
		output.onclick = onclick;

	return output;
}

Inputter.genHidden = function(name, value)
{
	var output = this.generate(name, 'hidden');
	if (undefined != value)
		output.value = value;

	return output;
}

Inputter.genSubmit = function(name, caption)
{
	var output = this.generate(name, 'submit');

	output.value = caption;

	return output;
}

Inputter.genTextBox = function(name, maxLength, size)
{
	var output = this.generate(name, 'text');

	if (maxLength)
		output.maxLength = maxLength;

	if (size)
		output.size = size;

	return output;
}

/** Modal Dialog Box - First overlays the main page with a semi-transparent layer
to block clicks outside of the popup. Next create a div with a slightly higher
zIndex.
The methods are global so there is no need to instantiate.
*/
var ModalDialog = {};

ModalDialog.CSS_SHIELD = 'modalShield';
ModalDialog.CSS_POPUP = 'modalDialog';
ModalDialog.shield = undefined;
ModalDialog.popup = new Array();
ModalDialog.ZINDEX = 100;

ModalDialog.open = function(caption, body)
{
	this.genShield();
	
	this.altSelectLists(true);
	this.run({ caption: caption }, body);
}

ModalDialog.close = function()
{
	if (!this.shield)
		return;
	
	var elem = this.popup.pop();
	document.body.removeChild(elem);

	// Remove the shield when all the popups are gone.
	if (0 == this.popup.length)
	{
		this.shield.style.display = 'none';
		this.altSelectLists(false);
	}
}

ModalDialog.run = function(criteria, body)
{
	var me = this;
	var output = this.getPopup();
	var table = document.createElement('table');
	table.className = this.CSS_POPUP;
	var tr = table.insertRow(0);
	tr.className = 'modalDialogHeader';
	
	var td = tr.insertCell(0);
	td.className = 'modalDialogCaption';
	td.appendChild(document.createTextNode(criteria.caption));
	td = tr.insertCell(1);
	td.className = 'modalDialogActions';
	
	var a = document.createElement('a');
	a.href = 'javascript:void(null);';
	a.onclick = function(ev) { me.close(); return false; };
	a.appendChild(document.createTextNode('X'));
	td.appendChild(a);
	
	tr = table.insertRow(1);
	td = tr.insertCell(0);
	td.className = 'modalDialogContainer';
	td.colSpan = 2;
	td.appendChild(body);
	
	output.innerHTML = '';
	output.appendChild(table);
	output.style.display = 'block';
	Positioner.center(output);
	
	return output;
}

ModalDialog.genShield = function()
{
	if (undefined == this.shield)
		this.shield = this.genBody(this.CSS_SHIELD);
	
	// Always set the coordinates as the height of the page can change.
	var coords = Positioner.getBodyDimensions();
	this.shield.style.width = coords.x + 'px';
	this.shield.style.height = coords.y + 'px';
	this.shield.style.display = 'block';
}

ModalDialog.getPopup = function()
{
	var output = this.genBody(this.CSS_POPUP);
	output.style.zIndex = this.ZINDEX + this.popup.length;
	this.popup.push(output);
	
	return output;
}

ModalDialog.genBody = function(className)
{
	var output = document.createElement('div');
	output.className = className;
	
	document.body.insertBefore(output, document.body.firstChild);
	
	return output;
}

/** Alternate the visibility of the select list of IE, as they don't respect a higher z-index. */
ModalDialog.altSelectLists = function(hide)
{
	if (!document.all)
		return;

	var items = document.body.getElementsByTagName('select');
	var newValue = (hide) ? 'hidden' : 'visible';
	
	for (var i = 0; i < items.length; i++)
		items[i].style.visibility = newValue;

	items = document.getElementById('flashDemo');
	if (items)
		items.style.display = (hide) ? 'none' : 'block';
}

var NewsletterDOM = {}

NewsletterDOM.generate = function()
{
	var me = this;
	var e, c, r, h, t, o = document.createElement('form');
	o.action = '_gdForm/webformmailer.asp';
	o.method = 'post';
	o.target = '_new';
	o.onsubmit = function(ev) { me.handleSubmit(this); return false; };
	o.appendChild(e = document.createElement('h4'));
	e.innerHTML = 'East Coast Spine, Joint and Sports Medicine e-newsletters are coming soon.<br />If you&rsquo;d like to receive them, please complete the information below:';

	o.appendChild(t = document.createElement('table'));
	h = t.createTHead();
	h.appendChild(r = this.createRow('*Email Address', 'email', 35, 35));
	o.myFirstField = r.myField;
	h.appendChild(this.createRow('*First Name', 'firstName', 35, 35));
	h.appendChild(this.createRow('*Last Name', 'lastName', 35, 35));
	h.appendChild(this.createRow('Phone', 'phone', 18, 18));

	h.appendChild(r = document.createElement('tr'));
	r.appendChild(document.createElement('td'));
	r.appendChild(c = document.createElement('td'));
	c.appendChild(Inputter.genSubmit('submitter', 'Submit'));
	c.appendChild(document.createTextNode(' '));
	c.appendChild(Inputter.genButton('canceler', 'Cancel', function(ev) { ModalDialog.close(); }));

	o.appendChild(document.createElement('br'));
	o.appendChild(e = document.createTextNode('* Required fields'));

	return o;
}

NewsletterDOM.createRow = function(caption, name, maxLength, size)
{
	var c, o = document.createElement('tr');
	o.appendChild(c = document.createElement('th'));
	c.innerHTML = caption;
	o.appendChild(c = document.createElement('td'));
	c.appendChild(o.myField = Inputter.genTextBox(name, maxLength, size));

	return o;
}

NewsletterDOM.handleSubmit = function(form)
{
	var o = {};
	o.subject = 'Newsletter Submission';
	o.redirect = 'thank_pop.txt';
	o.email = form.email.value;
	o['First Name'] = form.firstName.value;
	o['Last Name'] = form.lastName.value;
	o.phone = form.phone.value;

	Ajaxer.asynchPostMap('_gdForm/webformmailer.asp', o);

	ModalDialog.close();
}

//Base class for positioner implementations
var Positioner = {}

// Coordinate data class.
function CoordInfo(x, y)
{
	this.x = x;
	this.y = y;
}

Positioner.getBodyDimensions = function() { return new CoordInfo(document.body.offsetWidth, document.body.offsetHeight); }

Positioner.getCoords = function(elem)
{
	var value = new CoordInfo(0, 0);

	while (elem.offsetParent && ('BODY' != elem.tagName.toUpperCase()))
	{
		var position = elem.style.position;

		if ((undefined != position) && ('absolute' == position.toLowerCase()))
		{
			value.x+= parseInt(elem.style.left);
			value.y+= parseInt(elem.style.top);

			// Break, because the parent position is absolute on the page.
			return value;
		}
		else
		{
			value.x+= elem.offsetLeft;
			value.y+= elem.offsetTop;
		}
		elem = elem.offsetParent;
	}

	value.x+= elem.offsetLeft;
	value.y+= elem.offsetTop;

	return value;
}

Positioner.position = function(elem, coord)
{
	elem.style.position = 'absolute'; 
	elem.style.left = coord.x + 'px';
	elem.style.top = coord.y + 'px';
}

/** Centers the element on the viewable client area.
 * @param elem element being positioned.
 */
Positioner.center = function(elem)
{
	var topper = document.all ? document.documentElement : window;
	var clientWidth = (window.innerWidth) ? window.innerWidth : topper.clientWidth;
	var clientHeight = (window.innerHeight) ? window.innerHeight : topper.clientHeight;
	var scrollLeft = document.all ? topper.scrollLeft : topper.scrollX;
	var scrollTop = document.all ? topper.scrollTop : topper.scrollY;

	this.position(elem, new CoordInfo(((clientWidth - elem.offsetWidth) / 2) + scrollLeft,
		((clientHeight - elem.offsetHeight) / 2) + scrollTop));
}

/**
 * @param elem element being positioned.
 */
Positioner.under = function(base, elem)
{
	var coord = this.getCoords(base);
	coord.y+= base.offsetHeight;
	this.position(elem, coord);
}
