var effects = new Array()
var pageFrame   = "";
var newPage     = "";
var loadingPage = null;
var currentPage = "home";
var zipCode;var sCategory;
var nextTopic   = "";
var browser=navigator.appName;
var b_version=navigator.appVersion;
var version=parseInt(navigator.appVersion.split("MSIE")[1]);
var providerMenu = false;
window.addEvent('domready', function(){
	window.realAlert = window.alert;
	window.alert     = function(text, nextText, nextUrl) {
		// TODO
		if (!text)
			return false;
		$('modal-text').innerHTML = text;
		if (!nextText)
		{
			$('modal-detail').style.display = "none";
			$('modal-next').style.display   = "none";
		} else {
			$('modal-detail').style.display = "block";
			$('modal-next').style.display   = "block";
			$('modal-detail').innerHTML     = nextText;
		}
		
		if (nextUrl)
		{
			$('modal-next').addEvent('click', function(el) {window.location.href = nextUrl});
			$('modal-detail').addEvent('click', function(el) {window.location.href = nextUrl});
		}
		$('modal-popup').style.display      = 'block';
		var fx = new Fx.Morph('modal-popup', {duration: 400});
		fx.set({'opacity': 0});
		fx.start({'opacity': 1});
		linkify();
		return true;
	};
	
	window.closeAlert   = function(text, nextText, nextUrl) {
		if ($('modal-popup').style.opacity == 1)
		{
			var fx = new Fx.Morph('modal-popup', {duration: 400});
			fx.set({'opacity': 1});
			fx.start({'opacity': 0});
			return true;
		}
	};
		
	effects['content-box-right'] = new Fx.Tween($('content-box-right'), {
		onChainComplete: function(enva) {
			if (enva.style.width != "0px")
			{
				changeFunctions();
			} else {
				effects['innerNav'].start("width", 0);
				//effects['flashNav'].start()
			}
			scrollPage();
		}
	});
	
	effects['dashboard-box'] = new Fx.Tween($('dashboard-box'), {
		onChainComplete: function(enva) {
			if (enva.style.width != "0px")
			{
				changeFunctions();
			} else {
				effects['innerNav'].start("width", 0);
			}
		},
		onStart: function(enva)
		{
			//toggleFlash(1);
		}
	});
	
	effects['adContent'] = new Fx.Tween($('adContent'), {
		link: 'chain',
		onChainComplete: function(enva) {
			if (($('adContent').style.width == '0px') || ($('adContent').style.width == '0'))
				$('ad-html-text').innerHTML = '';
		}
	});
	effects['tour-div']  = new Fx.Tween($('tour-div'));	
	effects['innerNav']  = new Fx.Tween($('innerNav'));
	effects['innerNav2'] = new Fx.Tween($('innerNav2'), {link: 'chain'});
	effects['find-provider'] = new Fx.Tween($('find-provider'), {link: 'cancel'});
	effects['find-provider'].set("height", 20);
	effects['breadcrumb-menu'] = new Fx.Tween($('breadcrumb-menu'));
	effects['breadcrumb-menu'].set("height", 0);
	effects['index-main'] = new Fx.Tween($('index-main'), {});
	effects['share-thoughts-container'] = new Fx.Tween($('share-thoughts-container'), {duration: 100});
	effects['share-thoughts-container'].set("opacity", 0);
	effects['share-thoughts-container'].set("margin-left", 0);
	//effects['outside_canvas'] = new Fx.Tween($('outside_canvas'), {});
	effects['map-outside-canvas'] = new Fx.Tween($('map-outside-canvas'), {});
	effects['map-outside-canvas'].set("opacity", 0);
	effects['map-outside-canvas'].set("margin-left", 0);
	
	$('drr-btn-open').addEvent('click', function()
	{
		showCommentBox();
	});
	
//	effects['index-main'].set("opacity", 0);
	
	$('breadcrumb').addEvent('click', function(el) {
		if ($('breadcrumb-menu').style.height != "0px")
			effects['breadcrumb-menu'].start("height", 0);
		else
		{
			var jsonRequest = new Request.JSON(
							{
								url: "/ajax/history",
								onComplete: function(history){
									openBreadcrumb(history)
								}
							});
			jsonRequest.get();
		}
	});
	
	if (browser=="Microsoft Internet Explorer" && version == 6)
		fixPNGs();

/*	$('commentForm').addEvent('submit', function(e) {
		//Prevents the default submit event from loading a new page.
		e.stop();
		this.set('send', {
			onComplete: function(response) {
				mySlide.slideOut();
				alert("Your comment has been submitted!  Thank you!");
			}
		});
		//Send the form.
		$('comment-page').value = currentPage;
		if ($('comment-text').value.length > 0)
			this.send();
		else
			alert("You must enter a comment!");
	});*/

	//document.write('<script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&sensor=true_or_false&key=ABQIAAAAVnLwH_9x2orDnz7DrEyV4RQFNYzhlnwXFc5f2NG4yh1NBiG1kxTZRMiPRpGz0fGPbn5f7R1ssAmg2w"></script>');
	//document.close();
});

var openBreadcrumb = function(data)
{
	if (!data)
		return false;
	$('breadcrumb-menu').innerHTML = "";
	for (i = 0; i < data.length; i++)
	{
		tabbed = ((data[i].tabbed != 0)?" indent" + data[i].tabbed:"");
		$('breadcrumb-menu').innerHTML += "<li" + (data[i].active?" class=\"active-page" + tabbed + "\"":"") + "><a href=\"" + data[i].page + "\">" + data[i].text + "</a></li>\n";
	}
//	$('breadcrumb-menu').innerHTML += "</ul>\n";
	setTimeout("effects['breadcrumb-menu'].start(\"height\", (" + data.length + " * 17));", 1000);
	linkify();
}
/*
var toggleMap       = function(on)
{
	if ($('outside_canvas').style.width != "0px" || !on)
		effects['outside_canvas'].start("width", 0);
	if ($('outside_canvas').style.width == "0px" || on)
		effects['outside_canvas'].start("width", 500);
}
*/

var toggleMap       = function(on)
{
	if ($('map-outside-canvas').style.marginLeft == "0px")
	{
		effects['map-outside-canvas'].start("margin-left", -400);
		$('map-outside-canvas-handle').style.background = "url('/pl/www/images/map-tab2.png')";
	} else {
		effects['map-outside-canvas'].start("margin-left", 0);
		$('map-outside-canvas-handle').style.background = "url('/pl/www/images/map-tab.png')";
	}
}

var createMarker = function(point, text)
{
	// Create a base icon for all of our markers that specifies the
	// shadow, icon dimensions, etc.
	baseIcon = new GIcon(G_DEFAULT_ICON);
	baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	baseIcon.iconSize = new GSize(32, 33);
	baseIcon.shadowSize = new GSize(37, 34);
	baseIcon.iconAnchor = new GPoint(9, 34);
	baseIcon.infoWindowAnchor = new GPoint(9, 2);
	// Create a lettered icon for this point using our icon class
	var letteredIcon = new GIcon(baseIcon);
	if (arguments[2])
		letteredIcon.image = arguments[2];
	else
		letteredIcon.image = "/images/circle.png";
	
	// Set up our GMarkerOptions object
	markerOptions = { icon:letteredIcon };
	var marker = new GMarker(point, markerOptions);
	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(text);
	});
	return marker;

}

var toggleProviders = function()
{
	if (providerMenu == false)
		setProviderMenuUp();
	else if ($('innerNav2').style.height == '60px')
			setProviderMenuDown();
		else
			setProviderMenuUp();
}
var setProviderMenuDown = function()
{
	providerMenu = 'down';
	effects['innerNav2'].start("height", 552);
	effects['find-provider'].start("height", 20);
	$('find-provider-text').style.display = "none";
	effects['adContent'].start("opacity", 0);
}
var setProviderMenuUp = function()
{
	providerMenu = 'up';
	effects['innerNav2'].start("height", 60);
	effects['find-provider'].start("height", 70);
	$('find-provider-text').style.display = "block";
	effects['adContent'].start("opacity", 1);
}
var setProviderMenuOpen = function()
{
	if ($('innerNav2').style.width != '200px')
		effects['innerNav2'].start("width", 200);
}
var setProviderMenuClosed = function()
{
	if ($('innerNav2').style.width == '200px')
		effects['innerNav2'].start("width", 0);
}
var isProviderMenuOpen = function()
{
	if ($('innerNav2').style.width == '200px')
		return true;
	else
		return false;
}
var isProviderMenuClosed = function()
{
	return !isProviderMenuOpen();
}

var resetLinks = function(text)
{
	$$(document.links).filter(function(el) {
		if (el.rel && el.rel.test(/^toggler/i))
		{
			el.style.color = "";
			el.parentNode.className = "";
		}
		if (el.href.replace(text, "") != el.href)
		{
			el.style.color = "#fff";
			el.parentNode.className = "currentLI";
		}
	});
}

var page;

var preloadPage = function(identifier, slidetype)
{
/*	ident = identifier.split("|");
	page  = new Request({url: '/ajax/question/' + ident[ident.length - 1], 
		onSuccess: function(html) {
			if (html == '-1')
				loadPage(this.options.pageIdent, this.options.loadInto);
			else
			{
				loadingPage = newPage   = this.options.pageIdent;
				pageFrame = this.options.loadInto;
				alert(html);
				changeFunctions();
				$('answer-form').addEvent('submit', function(e) {
					//Prevents the default submit event from loading a new page.
					e.stop();
					this.set('send', {
						onComplete: function(response) {
							closeAlert();
							loadPage(newPage, pageFrame);
							newPage   = "";
							pageFrame = "";
						}
					});
					//Send the form.
					this.send();
				});

			}	
		},
		method: 'get',
		loadInto: slidetype,
		pageIdent: identifier.replace("-toggle", ""),
		evalScripts: true
	});
	page.send();
	return false;*/
	loadPage(identifier, slidetype);
}

var softLoadPage = function(identifier, slidetype)
{
	var fx = new Fx.Morph(slidetype, {duration: 200});
	fx.set({'opacity': 1, 'display': 'block'});
	fx.start({'opacity': 0});
	loadingPage = identifier.replace("-toggle", "");
	page = new Request({url: '/ajax/' + identifier.replace("-toggle", "").replace(/\|/g, "/"), 
		onSuccess: function(html) {
			//window.location.hash = "#" + this.options.pageIdent + "[" + this.options.loadInto + "]";
			loadContent(html, this.options.loadInto)
			var fx = new Fx.Morph(this.options.loadInto, {duration: 500});
			fx.set({'opacity': 0, 'display': 'block'});
			fx.start({'opacity': 1});
			pageTracker._trackPageview(this.options.url.replace('/ajax', ''));
		},
		method: 'get',
		loadInto: slidetype,
		pageIdent: identifier.replace("-toggle", ""),
		evalScripts: true
	});
	page.send();
	return false;
}

var softLoadContent = function(html, slidetype)
{
	$(slidetype).innerHTML = html;
	return false;
}

var loadPage = function(identifier, slidetype)
{
	loadingPage = identifier.replace("-toggle", "");
	page = new Request({url: '/ajax/' + identifier.replace("-toggle", "").replace(/\|/g, "/"), 
		onSuccess: function(html) {
			//window.location.hash = "#" + this.options.pageIdent + "[" + this.options.loadInto + "]";
			loadContent(html, this.options.loadInto)
			pageTracker._trackPageview(this.options.url.replace('/ajax', ''));
		},
		method: 'get',
		loadInto: slidetype,
		pageIdent: identifier.replace("-toggle", ""),
		evalScripts: true
	});
	page.send();
	return false;
}

var loadContent = function(html, slidetype)
{
	$(slidetype).innerHTML = html;
	doSlide = function() {
		if (slidetype == 'content-box-right')
			effects[slidetype].start("width", 530);
		else
			effects[slidetype].start("width", 780);
	}
	setTimeout("doSlide()", 500);
	return false;
}

var attachToCheckbox = function()
{
	$$(document.getElementsByTagName('input')).filter(function(el) {
		return el.id && el.id.test(/^checkbox/i);
	}).addEvent('click', function(el) {
		if (checking)
			return false;
		save = new Request({url: '/ajax/checkbox/' + this.id.replace("checkbox-", "") + '/' + (this.checked?"1":"0"), 
			onSuccess: function(html) {
				// TODO: Check, uncheck or prompt for signup.
				if (html == "2" || html == "0")
					this.options.checkbox.checked = false;
				if (html == "2")
					alert("To use the checklist you must be logged in or <a href=\"/register\">register</a>!");
				if (html == "1")
					alert("Your checklist has been updated!");
				checking = false;
			},
			method: 'get',
			checkbox: el
		});
		save.send();
		checking = true;
	})
}

var checking = false;

var attachDefinitions = function()
{
	$$('a.definition').each(function(el) {

		values = el.title.split("::");
		el.store('tip:title', values[0]);
		el.store('tip:text', values[1]);
		if ($type(values[2]))
			el.store('tip:spn', values[2]);
		if ($type(values[3]))
			el.store('tip:spntext', values[3]);

		var SimpleTip = new Tips(el, {
			showDelay: 0,
			hideDelay: 50,
			maxTitleChars: 50,
			showOnMouseEnter: false,
			offsets: {x: -115, y: 10},
			fixed: true
		});
		return;
	})
}

var attachDocuments = function()
{
	$$('a.document').each(function(el) {
		el.store('tip:title', el.innerHTML);
		el.store('tip:text', "Until the Estate Digital Lockbox&trade; is available, documents can be printed and used as a guide to store information.");

		var SimpleTip = new Tips(el, {
			showDelay: 0,
			hideDelay: 50,
			showOnMouseEnter: false,
			offsets: {x: -115, y: 10},
			fixed: true
		});
		return;
	})

/* we no longer require the user to login
	$$('a.document-login').each(function(el) {
		el.store('tip:title', el.innerHTML);
		el.store('tip:text', "In order to access the document library and download documents you must be logged in.  <a href=\"/register\">free registration</a>");

		var SimpleTip = new Tips(el, {
			showDelay: 0,
			hideDelay: 50,
			showOnMouseEnter: false,
			offsets: {x: -115, y: 10},
			fixed: true
		});
		return;
	})
*/
}


var attachHovers = function()
{
	$$('a.hover').each(function(el) {

		values = el.title.split("::");
		el.store('tip:title', values[0]);
		el.store('tip:text', values[1]);

		var SimpleTip = new Tips(el, {
			showDelay: 0,
			hideDelay: 500,
			showOnMouseEnter: false,
			offsets: {x: -115, y: 10},
			fixed: true
		});
		return;
	})
}

var searchElements = function()
{
	category = "";
	for (i = 0; i < document.directorySearch.category.length; i++)
	{
		if (document.directorySearch.category[i].checked)
			category = document.directorySearch.category[i].value;
	}
	if (category == "")
	{
		alert("Please select a service category.");
	} else if ($('zipcode').value == '') {
		alert("Please select a zipcode.");
	} else
	{
		zipCode = $('zipcode').value;
		window.location.hash = "#directory-search|" + category + "|" + $('zipcode').value;
	}
	return false;
}

var searchElements2 = function()
{
	category = $('left-category').value
	if (category == "")
	{
		alert("Please select a service category.");
		return false;
	}
	if ($('left-zipcode').value == '') {
		alert("Please select a zipcode.");
		return false;
	}
	if ($('left-zipcode').value != '' && $('left-category').value != '')
	{
		zipCode = $('left-zipcode').value;
		window.location.hash = "#directory-search|" + category + "|" + $('left-zipcode').value;
	}
	return false;
}

var searchElements3 = function()
{
	category = document.directorySearchSPN.category.value
	if (category == "")
	{
		alert("Please select a service category.");
	} else if ($('spn-zipcode').value == '') {
		alert("Please select a zipcode.");
	} else {
		zipCode = $('spn-zipcode').value;
		window.location.hash = "#directory-search|" + category + "|" + $('spn-zipcode').value;
	}
	return false;
}

var searchElements4 = function()
{
	category = $('home-category').value
	if (category == "")
	{
		alert("Please select a service category.");
	} else if ($('home-zipcode').value == '') {
		alert("Please select a zipcode.");
	} else
	{
		zipCode = $('home-zipcode').value;
		window.location.hash = "#directory-search|" + category + "|" + $('home-zipcode').value;
	}
	return false;
}

var searchElements5 = function()
{
	category = $('left2-category').value
	if (category == "")
	{
		if ($('left2-zipcode').value != '')
			zipCode = $('left2-zipcode').value;
		alert("Please select a service category.");
		return false;
	}
	if ($('left2-zipcode').value == '') {
		alert("Please select a zipcode.");
		return false;
	}
	if ($('left2-zipcode').value != '' && $('left2-category').value != '')
	{
		zipCode = $('left2-zipcode').value;
		window.location.hash = "#directory-search|" + category + "|" + $('left2-zipcode').value;
//		window.location.hash = "#spn|" + category;
	}
	return false;
}

var topicThread = 0;

var showCommentThread = function(id)
{
	if (id != 0)
	{
		topicThread = id;
		page = new Request({url: '/ajax/comments/' + id, 
			onSuccess: function(html) {
				$('share-thoughts-text').innerHTML = html;
			},
			method: 'get',
			evalScripts: true
		});
		page.send();
	} else {
		topicThread = id;
		page = new Request({url: '/ajax/comments/' + currentPage, 
			onSuccess: function(html) {
				$('share-thoughts-text').innerHTML = html;
			},
			method: 'get',
			evalScripts: true
		});
		page.send();
	}
}

var toggleShareThoughts = function()
{
	topicThread = '';
	if ($('share-thoughts-container').style.marginLeft != "0px")
	{
		slideShareThoughtsInOut();
		return false;
	}
	page = new Request({url: '/ajax/comments/' + currentPage, 
		onSuccess: function(html) {
			$('share-thoughts-text').innerHTML = html;
			slideShareThoughtsInOut();			
		},
		method: 'get',
		evalScripts: true
	});
	page.send();
}

var slideShareThoughtsInOut = function()
{
//	effects['share-thoughts-container']  = new Fx.Tween($('share-thoughts-container'));
	if ($('share-thoughts-container').style.marginLeft == "0px")
	{
		effects['share-thoughts-container'].start("margin-left", -350);
		$('share-thoughts-handle').style.background = "url('/pl/www/images/shareThoughts-tab2.png')";
	} else {
		effects['share-thoughts-container'].start("margin-left", 0);
		$('share-thoughts-handle').style.background = "url('/pl/www/images/shareThoughts-tab.png')";
	}
}

var checkAccordians = function()
{
	var myAccordion = new Accordion($('faqs'), 'h3.toggler', 'div.element', {
		opacity: false,
		onActive: function(toggler, element){
			//toggler.setStyle('color', '#41464D');
		},
		onBackground: function(toggler, element){
			//toggler.setStyle('color', '#528CE0');
		}
	});
}

var changeTitle = function()
{
	data           = currentPage.replace(/\//g, "|").replace(/\_/g, " ").split("|");
	tempPage       = currentPage.replace(/\//g, "|").replace(/\_/g, " ");
	if (data[0] == "topic" || data[0] == "step")
		document.title = data[1].replace(/\-/g, " ").ucWords() + " | My Estate Manager";
	else if (data[0] == "directory-search")
		document.title = "Directory Search | " + data[2].ucWords() + " | My Estate Manager";
	else if (data[0] == 'dlb')
		document.title = "Digital Lock Box | My Estate Manager";
	else if (data[0] == 'mpa')
		document.title = "My Personal Administrator | My Estate Manager";
	else if (data[0] == 'resources')
		document.title = "Reference Center | My Estate Manager";
	else if (data[0] == 'spn' && !tempPage.contains("|"))
		document.title = "Service Partner Network | My Estate Manager";
	else if (data[0] == 'spn' && tempPage.contains("|"))
		document.title = data[1].ucWords() + " | Service Partner Network | My Estate Manager";
	else
		document.title = data[0].ucWords() + " | My Estate Manager";
/*	header = $$('.topic-head h2')
	if (header.length <= 0)
		return;
	if (header.length == 1)
		$('page-title').innerHTML = "<em>Page:</em> " + header[0].innerHTML;
	else if ($type(header[0].innerHTML) == 'string')
		$('page-title').innerHTML = "<em>" + header[0].innerHTML.replace(" |","") + ":</em> " + header[1].innerHTML;
	else
		$('page-title').innerHTML = "<em>Page:</em> Home";
		
	loadComments();*/
}

var loadComments = function()
{
	title = strip_tags($('page-title').innerHTML).replace(":", "-").replace(/\ /gi, "");
	//title = title.stripTags();
	page = new Request({url: '/comments/' + title, 
		onSuccess: function(html) {
			$('commentArea').innerHTML = html;
		},
		method: 'get',
		evalScripts: true
	});
	//page.send();
}

var submitComment = function()
{
	
	alert("Your comment has been submitted!");
	return false;
}

var setFontSize = function(size)
{
	//document.body.setStyle('font-size', size);
	$('content-box-right').setStyle('font-size', size);
	$$('contentBoxCont').setStyle('font-size', size);
}

var theFadeOuts = new Array();
var theFadeIns  = new Array();

var checkForAd = function()
{
    // cancelFades
    for (i = 0; i < theFadeIns.length; i++)
        clearTimeout(theFadeIns[i])
    for (i = 0; i < theFadeOuts.length; i++)
        clearTimeout(theFadeOuts[i])
					
	new Request(
		{
			url: '/ajax/ad-text/' + currentPage.replace("/", "-"),
			onSuccess: function (html)
			{
				if (html != "-1")
				{
					// Insert the html
					$('ad-html-text').innerHTML = html;
					$$('.ad-page').each(function(el) {
						el.setStyle("opacity", '0');
						el.setStyle("display", 'none');
						time = parseInt(el.id.replace('ad-page-', ''));
						theFadeIns[theFadeIns.length] = setTimeout("fadeIn('" + el.id + "', " + $$('.ad-page').length + ")", (time * 10000));
						theFadeOuts[theFadeOuts.length] = setTimeout("fadeOut('" + el.id + "')", ((time + 1) * 10000));
					});
					if (browser == "Microsoft Internet Explorer" && version == 6)
						fixPNGs();
					effects['adContent'].start("width", 251);
				} else {
					if ($('adContent').style.width == '251px')
						effects['adContent'].start("width", 0);
 				}
			},
			method: 'get'
		}
	).send();
}

var fadeIn = function(id, count)
{
	// cancelFades
	/*for (i = 0; i < theFadeIns.length; i++)
		clearTimeout(theFadeIns[i])*/
	var fx = new Fx.Morph(id, {duration: 400});
	fx.set({'opacity': 0, 'display': 'block'});
	fx.start({'opacity': 1});
	theFadeIns[theFadeIns.length] = setTimeout("fadeIn('" + id + "', " + count + ")", (count * 10000));
	theFadeOuts[theFadeOuts.length] = setTimeout("fadeOut('" + id + "')", (count + 1) * 10000);
}

var fadeOut = function(id)
{
	/*for (i = 0; i < theFadeOuts.length; i++)
		clearTimeout(theFadeOuts[i])*/
	var fx = new Fx.Morph(id, {duration: 400});
	fx.set({'opacity': 1, 'display': 'none'});
	fx.start({'opacity': 0});
}

var backgroundSwapAction = function(el1, el2, bkgd)
{
	el1.style.background = "url(" + bkgd + ")";
	el1.style.display	= "block";
	var fx = new Fx.Morph(el1, {duration: 800});
	fx.set('opacity', 0);
	fx.start({'opacity': 1});
	var fx = new Fx.Morph(el2, {duration: 1200, onChainComplete: function(el) {
		el.style.display = "none";
	}});
	fx.set('opacity', 1);
	fx.start({'opacity': 0});
}
var backgroundSwap = function()
{
/*
	one = $('content1');
	two = $('content2');
	if (one.style.opacity == 0)
	{
		// Fade two to one
		var fx = new Fx.Morph('content1', {duration: 400});
		fx.set({'opacity': 0});
		fx.start({'opacity': 1});
		var fx = new Fx.Morph('content2', {duration: 800, onChainComplete: function(el) {
			next = (parseInt(el.className.replace('bg', '')) + 2)
			next = (next > 11)?1:next;
			el.className = 'bg' + next;
		}});
		fx.set({'opacity': 1});
		fx.start({'opacity': 0});
	} else if (two.style.opacity == 0)
	{
		next = (parseInt(two.className.replace('bg', '')) + 2)
		next = (next > 10)?2:next;
		two.className = 'bg' + next;
		// Fade one to two
		var fx = new Fx.Morph('content2', {duration: 400});
		fx.set({'opacity': 0});
		fx.start({'opacity': 1});
		var fx = new Fx.Morph('content1', {duration: 800, onChainComplete: function(el) {
			next = (parseInt(el.className.replace('bg', '')) + 2)
			next = (next > 11)?1:next;
			el.className = 'bg' + next;
		}});
		fx.set({'opacity': 1});
		fx.start({'opacity': 0});
	}
	*/
	page = new Request({url: '/ajax/background/' + currentPage, 
		onSuccess: function(html) {
			if (html != '-1')
			{
				one = $('content1');
				two = $('content2');
				if ((browser == "Microsoft Internet Explorer")&&(one.style.opacity == undefined)) { 
					// Special case for first time through here in IE
					backgroundSwapAction(two,one,html);
				} else if (one.style.opacity == 0 && two.className != html) {
					backgroundSwapAction(one,two,html);
				} else if (two.style.opacity == 0 && one.className != html) {
					backgroundSwapAction(two,one,html);
				}
			}
		},
		method: 'get',
		evalScripts: true
	});
	page.send();
}

var flashData = '';

var toggleFlash = function(sh)
{
/*
	var fx = new Fx.Morph('flashStuff', {duration: 400, onComplete: function (el) {
		if (el.style.opacity == 0)
		{
			flashData = $('flashStuff').innerHTML;
			$('flashStuff').innerHTML = "";
		}
	}});
	if (sh == 1)
		$('flashStuff').innerHTML = flashData;
	fx.start({'opacity': sh});	*/
	effects['index-main'].start('opacity', sh);
}
/*
var closeSlide = function()
{
	if (window.location.hash.replace("topic", "") != window.location.hash && window.location.hash.replace("topics", "") != window.location.hash.replace("topic", "") || currentPage.contains("spn|"))
		history.back(-1);
	else
		window.location.hash = "#home";
	
	$('content-box-right').innerHTML = '';
	effects['content-box-right'].start('width', 0);
	effects['share-thoughts-container'].start("margin-left", 0);
	$('share-thoughts-handle').style.background = "url('/images/shareThoughts-tab.png')";
	toggleMap(0);
}
*/

var closeSlide = function()
{
	if (window.location.hash.replace("topic", "") != window.location.hash && window.location.hash.replace("topics", "") != window.location.hash.replace("topic", "") || currentPage.contains("spn|"))
		history.back(-1);
	else
		window.location.hash = "#home";
	
	$('content-box-right').innerHTML = '';
	effects['content-box-right'].start('width', 0);
	effects['share-thoughts-container'].start("margin-left", 0);
	$('share-thoughts-handle').style.background = "url('/images/shareThoughts-tab.png')";
	effects['map-outside-canvas'].start("opacity", 0);
	setTimeout("toggleMap(0);", 1000);
}

function strip_tags($text)
{
	return $text.replace(/<\/?[^>]+>/gi, '');
}

var showCommentBox = function()
{
	data  = '<form method="post" action="/ajax/comment" name="commentForm" id="commentForm">';
	data += '<input type="hidden" name="comment[page]" id="comment-page" />';
	if (topicThread != '')
		data += '<input type="hidden" name="comment[reply]" id="comment-reply" value="' + topicThread + '" />';
	data += '<div style="width: 75%; margin: 0 auto;">';
	data += '<center>share your experiences or ask the opinions of others</center><br />';
	data += 'Comments:<textarea style="width: 100%; height: 75px;" id="comment-text" name="comment[text]"></textarea><br /><br />';
	data += '<center><input type="submit" class="submit" value="submit" /></center>';
	data += '</div>';
	data += '</form>';
	alert(data);
	$('commentForm').addEvent('submit', function(e) {
		//Prevents the default submit event from loading a new page.
		e.stop();
		this.set('send', {
			onComplete: function(response) {
				closeAlert();
				showCommentThread(topicThread);
				setTimeout('alert("Thank you for sharing your experience. Please note that your input won\'t show up right away as we review each comment to protect the members of our community.")', 1500);
			}
		});
		//Send the form.
		$('comment-page').value = currentPage;
		if ($('comment-text').value.length > 0)
			this.send();
		else
			alert("You must enter a comment!");
	});
}

var showReplyBox = function(id)
{
	data  = '<form method="post" action="/ajax/comment" name="commentForm" id="commentForm">';
	data += '<input type="hidden" name="comment[page]" id="comment-page" />';
	data += '<input type="hidden" name="comment[reply]" id="comment-reply" value="' + id + '" />';
	data += '<div style="width: 75%; margin: 0 auto;">';
	data += '<center>share your experiences or ask the opinions of others</center><br />';
	data += 'Comments:<textarea style="width: 100%; height: 75px;" id="comment-text" name="comment[text]"></textarea><br /><br />';
	data += '<center><input type="submit" class="submit" value="submit" /></center>';
	data += '</div>';
	data += '</form>';
	alert(data);
	$('commentForm').addEvent('submit', function(e) {
		//Prevents the default submit event from loading a new page.
		e.stop();
		this.set('send', {
			onComplete: function(response) {
				closeAlert();
				showCommentThread(topicThread);
				setTimeout('alert("Thank you for sharing your experience. Please note that your input won\'t show up right away as we review each comment to protect the members of our community.")', 1500);
			}
		});
		//Send the form.
		$('comment-page').value = currentPage;
		if ($('comment-text').value.length > 0)
			this.send();
		else
			alert("You must enter a comment!");
	});
}

var activateAnswerForms = function()
{
	$$('.answer-form').each(function(el) {
		$(el.id).addEvent('submit', function(e) {
			//Prevents the default submit event from loading a new page.
			e.stop();
			this.set('send', {
				onComplete: function(response) {
					alert("Your answer has been recorded.");
					if ($("answer-push-" + this.options.data.id.replace("answer-form-", "")).value == "1")
						window.location.hash = nextTopic;
					if ($("answer-reload-" + this.options.data.id.replace("answer-form-", "")).value == "1")
						softLoadPage(currentPage, 'content-box-right');
					setTimeout("closeAlert()", 2500);
				}
			});
			//Send the form.
			this.send();
		});
	});
}

String.prototype.ucFirst = function () {
	return this.substr(0,1).toUpperCase() + this.substr(1,this.length);
};

String.prototype.ucWords = function () {
	return this.replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase ( ); } );
}

var fixPNGs = function()
{
	$$('a').each(
		function(el){
			if (el.getStyle('background-image').contains('.png')) {
				DD_belatedPNG.fixPng(el);
	}});
	$$('input').each(
		function(el){
			if (el.getStyle('background-image').contains('.png')) {
				DD_belatedPNG.fixPng(el);
	}});
	$$('li').each(
		function(el){
			if (el.getStyle('background-image').contains('.png')) {
				DD_belatedPNG.fixPng(el);
	}});
	$$('div').each(
		function(el){
			if (el.getStyle('background-image').contains('.png')) {
				DD_belatedPNG.fixPng(el);
	}});
	$$('span').each(
		function(el){
			if (el.getStyle('background-image').contains('.png')) {
				DD_belatedPNG.fixPng(el);
	}});
	$$('img').each(
		function(el){
			if (el.src.contains('.png')) {
				DD_belatedPNG.fixPng(el);
	}});
	DD_belatedPNG.fix('.tip-title');
	DD_belatedPNG.fix('.tip-text');
	DD_belatedPNG.fix('.currentLI');
	DD_belatedPNG.fix('div.spn-hover a');
	DD_belatedPNG.fix('.selected');
	DD_belatedPNG.fix('.unselected');
	DD_belatedPNG.fix('.unchecked');
	DD_belatedPNG.fix('.checked');
	DD_belatedPNG.fix('div.top a:hover');
}

var scrollPage = function()
{
	if ($(pageloc))
	{
		$$('.contentBoxCont').each(
			function(el) {
				el.scrollTo(0, 0);
				coords = $(pageloc).getCoordinates();
				el.scrollTo(0, coords.top - 165);
			}
		);
	} else if (pageloc == 'comments')
		toggleShareThoughts();
}

var changeFunctions = function()
{
	$$('tip-class-name').each(
		function(el)
		{
			el.parentNode.removeChild(el);
		}
	);
	if ($('breadcrumb-menu').style.height != "0px")
		effects['breadcrumb-menu'].start("height", 0);

	currentPage = loadingPage;
	// Directory Page Show
	if (currentPage.contains("directory-search") || (currentPage.contains("directory") && currentPage != "directory"))
	{
		effects['innerNav'].start("width", 200);
		url = window.location.hash.split("|");
		zipCode   = url[2];
		sCategory = url[1];
	} else
		effects['innerNav'].start("width", 0);
	
	// Service Partner Network pages
	if (currentPage == "spn")
		$('homeSearchLiveDiv').style.display  = "block";
	else
		$('homeSearchLiveDiv').style.display  = "none";

	if (currentPage == 'spn')
	{
		if (providerMenu != 'down')
			setProviderMenuDown();
	}
	else if (currentPage.contains('spn'))
	{
		if (providerMenu != 'up')
		setProviderMenuUp();
	}

	if (currentPage.contains('spn'))
	{
		if (isProviderMenuClosed())
			setProviderMenuOpen();
	} else if (isProviderMenuOpen())
		setProviderMenuClosed();

	// Start every new page with the ad closed, loading a new ad will open it
	effects['adContent'].start("width", 0);
	effects['adContent'].start("opacity", 1);

	attachToCheckbox();
/*
	if (browser!="Microsoft Internet Explorer" && version != 6)
		FancyForm.start();
*/
	changeTitle();
	attachDefinitions();
	attachDocuments();
	attachHovers();
	checkForAd();
	closeAlert();
	activateAnswerForms();
//	toggleFlash(0);
	backgroundSwap();
	linkify();
	Slimbox.scanPage();
	if (currentPage.contains("topic") || currentPage.contains("step"))
		effects['share-thoughts-container'].start("opacity", 1);
	if (currentPage.contains("directory-search") || currentPage.contains("directory"))
		effects['map-outside-canvas'].start("opacity", 1);
	else
		effects['map-outside-canvas'].start("opacity", 0);		
	if (browser=="Microsoft Internet Explorer" && version == 6)
		fixPNGs();
}

var setFormField = function(name, value) {
	var el = $(name);
	if ($type(el)) {
		if (el.type=='checkbox')
			el.checked = true;
		else if (el.type=='radio') {
			$$(name).each(function(rb) {
			if (rb.value == value) // Is 'value' passed in from the outside scope?
				rb.checked = true;
			});
		}
		else
			el.value = value;
	}
}
