var pageTitleBase = "Jiggzy.com : ";
var pageArray = new Array("Welcome", "Services", "Portfolio", "About", "Contact", "Quiche");
var welcomeImages = new Array("images/welcome.png", "images/welcome_quiche.png", "images/welcome_site.png", "images/welcome_software.png", "images/welcome_game.png", "images/welcome_about.png", "images/welcome_contact.png", "images/welcome_google.png", "images/checkbox.png", "images/checkbox_checked.png", "images/googleconfirm_areyousure.png", "images/googleconfirm_yes.png", "images/googleconfirm_or.png", "images/googleconfirm_no.png");
var servicesImages = new Array("images/heading_services.png");
var portfolioImages = new Array("images/heading_portfolio.png", "images/portfolio_mintocomponents.jpg", "images/portfolio_bicshavers.jpg", "images/portfolio_safetydance.jpg", "images/portfolio_chc.jpg", "images/portfolio_2minutedrill.jpg", "images/portfolio_collection.jpg", "images/portfolio_oldsite.jpg", "images/portfolio_photography.jpg", "images/portfolio_dealadayonline.jpg", "images/portfolio_emergencyrescue.jpg", "images/portfolio_pocketpresence.jpg", "images/portfolio_scrambledlegs.jpg", "images/portfolio_weddinggift.jpg", "images/portfolio_artscrawlposter.jpg", "images/portfolio_tempmusicair.jpg");
var aboutImages = new Array("images/me.jpg", "images/heading_about.png", "images/sm_icon_greader.png", "images/sm_icon_greader_highlight.png", "images/sm_icon_flickr.png", "images/sm_icon_flickr_highlight.png", "images/sm_icon_twitter.png", "images/sm_icon_twitter_highlight.png");
var contactImages = new Array("images/heading_contact.png", "images/smiley.jpg", "images/leftarrow.png", "images/input_left.png", "images/input_right.png", "images/textarea_left.png", "images/textarea_right.png");
var quicheImages = new Array("images/heading_quiche.png", "images/quiche.jpg");
var navImages = new Array("images/navAbout.png", "images/navAboutOver.png", "images/navAboutCurrent.png", "images/navContact.png", "images/navContactOver.png", "images/navContactCurrent.png", "images/navCopyright.png", "images/navJiggzyCom.png", "images/navJiggzyComOver.png", "images/navPortfolio.png", "images/navPortfolioOver.png", "images/navPortfolioCurrent.png", "images/navServices.png", "images/navServicesOver.png", "images/navServicesCurrent.png");
var imagesToPreload = new Array(welcomeImages, servicesImages, portfolioImages, aboutImages, contactImages, quicheImages, navImages);
var imagesToPreloadCountdown = new Array(welcomeImages.length, servicesImages.length, portfolioImages.length, aboutImages.length, contactImages.length, quicheImages.length, navImages.length);
var oneTimeSetupComplete = new Array(false, false, false, false, false, false);
var imagesHaveStartedToLoad = new Array(false, false, false, false, false, false, false); /* +1 for nav */
var pageImagesAreLoaded = new Array(false, false, false, false, false, false, false); /* +1 for nav */
var cssImagesAreLoaded = false;
if (noPreload) {
	for (var i = 0; i < pageImagesAreLoaded.length; i++) {
		pageImagesAreLoaded[i] = true;
	}
	cssImagesAreLoaded = true;
}
var regularNavigationInProgress = false;
var lastPageIndex;
var currentPageIndex;
var currentPageSection;
function getPageIndex(name) {
	switch (name.toLowerCase()) {
		case "welcome":
		case "jiggzycom":
			return 0;
		case "services":
			return 1;
		case "portfolio":
			return 2;
		case "about":
			return 3;
		case "contact":
			return 4;
		case "quiche":
			return 5;
		case "nav":
			return 6;
		default:
			return 0;
	}
}

$(document).ready(function() {
	$("#javascriptDisabled").remove();
	preloadImages(6); /* preloads nav and calls navLoaded() when finished */
});

function navLoaded() {
	$("li.navLink a").mouseover(function() {
		var navId = $(this).parent().attr('id');
		var pageIndex = getPageIndexFromNavId(navId);
		if (currentPageIndex != pageIndex || pageIndex == 0) {
			$(this).children("img").attr("src", "images/" + navId + "Over.png");
		}
	}).mouseout(function() {
		var navId = $(this).parent().attr('id');
		var pageIndex = getPageIndexFromNavId(navId);
		if (currentPageIndex != pageIndex || pageIndex == 0) {
			$(this).children("img").attr("src", "images/" + navId + ".png");
		}
	}).click(function() {
		var navId = $(this).parent().attr('id');
		var pageIndex = getPageIndexFromNavId(navId);
		gotoPage(pageIndex);
	}).each(function() {
		$(this).html("<img src='images/" + $(this).parent().attr('id') + ".png' alt='" + $(this).attr('title') + "' />");
	});
	$('#navCopyright').html("<img src='images/navCopyright.png' alt='© 2009 Nick Cherry' />");
	$("#navFullWidth").fadeIn(300);
	showOverlay();
	lastPageIndex = -1;
	currentPageIndex = -1;
	var index = extractPageIndexFromUrl();
	var section = extractPageSectionFromUrl();
	gotoPage(index, section);
	$.address.change(urlChanged);
	$.preloadCssImages({
		onCompleteFunction: cssImagesLoaded
	});
	for (var i = 0; i < pageArray.length; i++) {
		loadPageImages(i);
	}
}

function cssImagesLoaded() {
	cssImagesAreLoaded = true;
}

function showOverlay(switchPagesOnFinish) {
	adjustOverlayHeight();
	if (switchPagesOnFinish) {
		$('#overlay').fadeIn(300, switchPages);
	} else {
		$('#overlay').fadeIn(300);
	}
}

function hideOverlay() {
	adjustOverlayHeight();
	if (lastPageIndex > -1) {
		$.scrollTo(0);
	}
	$('#overlay').fadeOut(300);
}

function adjustOverlayHeight() {
	$('#overlay').height($(document).height());
}

function switchPages() {
	var lastPage = pageArray[lastPageIndex];
	var currentPage = pageArray[currentPageIndex];
	if (pageImagesAreLoaded[currentPageIndex] && cssImagesAreLoaded) {
		hideAllPages();
		$("#page" + currentPage).show();
		setPageTitle(currentPage);
		setPageUrl(currentPage, currentPageSection);
		if (currentPageIndex == 1) {
			highlightAndMoveService(extractPageSectionFromUrl());
		}
		regularNavigationInProgress = false;
		hideOverlay();
		$('#mainLoading').fadeOut(400);
		if (currentPage == 4 || currentPage == 6) { /* contact or nav */
			preloadImagesWithNoEvents(currentPage);
		}
	} else {
		$.timer(500, function(timer) {
			if (pageImagesAreLoaded[currentPageIndex] && cssImagesAreLoaded) {
				timer.stop();
				switchPages();
			}
		});
	}
}

function showCurrentPage() {
	$("#page" + page).show();
}

function hideLastPage() {
	$("#page" + page).hide();
}

function loadPageImages(index) {
	switch (index) {
		case 0: /*Welcome*/
			break;
		case 1: /*Services*/
			if (supportsFontFace) {
				removeItemFromArrayWhereValueEquals("images/heading_services.png", imagesToPreload[index]);
			}
			break;
		case 2: /*Portfolio*/
			if (supportsFontFace) {
				removeItemFromArrayWhereValueEquals("images/heading_portfolio.png", imagesToPreload[index]);
			}
			break;
		case 3: /*About*/
			if (supportsFontFace) {
				removeItemFromArrayWhereValueEquals("images/heading_about.png", imagesToPreload[index]);
			}
			break;
		case 4: /*Contact*/
			if (supportsFontFace) {
				removeItemFromArrayWhereValueEquals("images/heading_contact.png", imagesToPreload[index]);
			}
			break;
		case 5: /*Quiche*/
			if (supportsFontFace) {
				removeItemFromArrayWhereValueEquals("images/heading_quiche.png", imagesToPreload[index]);
			}
			/* */
			break;
	}
	preloadImages(index);
}

function preloadImagesWithNoEvents(pageIndex) {
	if (pageIndex == 4) {
		var imgs = new Array(contactImages.length);
		for (var i = 0; i < contactImages.length; i++) {
			imgs[i].src = contactImages[i];
		}
	} else if (pageIndex == 6) {
		var imgs = new Array(navImages.length);
		for (var i = 0; i < navImages.length; i++) {
			imgs[i].src = navImages[i];
		}
	}
}


function preloadImages(pageIndex) {
	if (imagesToPreload[pageIndex].length == 0) {
		imagesHaveStartedToLoad[pageIndex] = true;
		pageImagesAreLoaded[pageIndex] = true;
	} else {
		if (!imagesHaveStartedToLoad[pageIndex]) {
			imagesHaveStartedToLoad[pageIndex] = true;
			var imgs = imagesToPreload[pageIndex];
			var img;
			for (var i = 0; i < imgs.length; i++) {
				img = new Image();
				addEvent(img, 'onerror', preloadImagesOnError);
				addEvent(img, 'onload', preloadImagesOnLoad);
				img.id = pageIndex;
				img.src = imgs[i];
			}
		}
	}
}

function preloadImagesOnError(e) {
	/*alert('Error loading ' + this.src);*/
	imageLoaded(this);
}

function preloadImagesOnLoad(e) {
	imageLoaded(this);
}

function imageLoaded(obj) {
	removeEvent(obj, 'onerror', preloadImagesOnError);
	removeEvent(obj, 'onload', preloadImagesOnLoad);
	if (--imagesToPreloadCountdown[obj.id] == 0) {
		pageImagesAreLoaded[obj.id] = true;
		if (obj.id == 6) {
			navLoaded();
		}
	}
}

function setupPageLogic(index) {
	switch (index) {
		case 0: /*Welcome*/
			if (!oneTimeSetupComplete[index]) {
				oneTimeSetupComplete[index] = true;
				$('#pageWelcome h1').before("<h1><img id='welcomeImg' src='images/welcome.png' /></h1>").remove();
				$('#pageWelcome h2').remove();
				$('#pageWelcome li span').each(function() {
					var parent = $(this).parent();
					switch (parent.attr('id')) {
						case "welcomeResponse_quiche":
							parent.append("<img src='images/welcome_quiche.png'>");
							break;
						case "welcomeResponse_site":
							parent.append("<img src='images/welcome_site.png'>");
							break;
						case "welcomeResponse_software":
							parent.append("<img src='images/welcome_software.png'>");
							break;
						case "welcomeResponse_game":
							parent.append("<img src='images/welcome_game.png'>");
							break;
						case "welcomeResponse_about":
							parent.append("<img src='images/welcome_about.png'>");
							break;
						case "welcomeResponse_contact":
							parent.append("<img src='images/welcome_contact.png'>");
							break;
						case "welcomeResponse_google":
							parent.append("<img src='images/welcome_google.png'>");
							break;
						case "welcomeResponse_googleconfirm":
							var confirm = "";
							confirm += "<img src='images/googleconfirm_areyousure.png' alt='Are you sure? ' />";
							confirm += "<img id='googleConfirmNo' src='images/googleconfirm_no.png' alt='Nope, just tricking.' />";
							confirm += "<img src='images/googleconfirm_or.png' alt=' || ' />";
							confirm += "<img id='googleConfirmYes' src='images/googleconfirm_yes.png' alt='You bet. Take me away from here!' />";
							parent.append(confirm);
							$('#googleConfirmNo').click(googleConfirmNoClick);
							$('#googleConfirmYes').click(googleConfirmYesClick);
							break;
					}
					$(this).remove();
				});
			}
			$('#welcomeResponsesUl div.checkbox').removeClass("checked").click(welcomeResponseCheckboxClicked);
			$('#welcomeResponse_googleconfirm').hide();
			break;
		case 1: /*Services*/
			if (!oneTimeSetupComplete[index]) {
				oneTimeSetupComplete[index] = true;
				if (!supportsFontFace) {
					$('#pageServices h1').before("<h1><img id='headingServices' class='heading' src='images/heading_services.png' /></h1>").remove();
				}
				$('div.serviceContainer h2').click(function() {
					$(this).siblings().toggle();
				/*
				 var isHighlighted = $(this).parent().hasClass('highlight');
				 $(this).parent().removeClass('highlight').siblings().removeClass('highlight');
				 if ($(this).siblings().is(':visible')) {
				 if (isHighlighted) {
				 $(this).removeClass('highlight').siblings().hide();
				 } else {
				 $(this).parent().addClass('highlight');
				 }
				 } else {
				 $(this).siblings().show().parent().addClass('highlight');
				 }
				 */
				});
			}
			if (!regularNavigationInProgress) {
				highlightAndMoveService(extractPageSectionFromUrl());
			}
			break;
		case 2: /*Portfolio*/
			if (!oneTimeSetupComplete[index]) {
				oneTimeSetupComplete[index] = true;
				if (!supportsFontFace) {
					$('#pagePortfolio h1').before("<h1><img id='headingPortfolio' class='heading' src='images/heading_portfolio.png' /></h1>").remove();
				}
				$('#portfolioExhibit span.backToTop').click(function() {
					$.scrollTo(0, 200);
				});
				$('div.portfolioItem div.image a.portfolioPic').each(function() {
					$(this).append('<span class="imageHighlight"></span><img src="images/' + $(this).attr('id') + '" />').parent().mouseover(function() {
						$(this).find('span.imageHighlight').show();
					});
					$(this).parent().mouseout(function() {
						$(this).find('span.imageHighlight').hide();
					});
					if ($(this).attr('href') == '') {
						$(this).css('cursor', 'default').parent().unbind('mouseover').click(function() {
							return false;
						});
					}
				});
				$('');
				$('#portfolioNav span').click(function() {
					filterPortfolio($(this).attr('id').substring('portfolioNavLink'.length), true);
				});
				$('div.clientLogo').mouseover(function() {
					$(this).children('img, p').toggle();
				}).mouseout(function() {
					$(this).children('img, p').toggle();
				});
			}
			$('div.clientLogo').each(function() {
				$(this).children('p').hide();
				$(this).children('img').show();
			});
			filterPortfolio(extractPageSectionFromUrl());
			break;
		case 3: /*About*/
			if (!oneTimeSetupComplete[index]) {
				oneTimeSetupComplete[index] = true;
				if (!supportsFontFace) {
					$('#pageAbout h1').before("<h1><img id='headingAbout' class='heading' src='images/heading_about.png' /></h1>").remove();
				}
				$('#pageAbout img.smIcon').each(function() {
					$(this).attr('src', 'images/' + $(this).attr('id')).parent().mouseover(function() {
						var img = $(this).children('img');
						var id = img.attr('id');
						img.attr('src', 'images/' + id.substring(0, id.indexOf('.')) + '_highlight.png');
					}).mouseout(function() {
						var img = $(this).children('img');
						img.attr('src', 'images/' + img.attr('id'));
					});
				});
				$('img.aboutPic').each(function() {
					$(this).attr('src', 'images/' + $(this).attr('id'));
				});
			}
			break;
		case 4: /*Contact*/
			if (!oneTimeSetupComplete[index]) {
				oneTimeSetupComplete[index] = true;
				if (!supportsFontFace) {
					$('#pageContact h1').before("<h1><img id='headingContact' class='heading' src='images/heading_contact.png' /></h1>").remove();
				}
				$('#contactMessage').limit(2000);
				$('#contactFormUl li.inputPrompt').append("<span class='highlight2 strong'></span>");
				$('#contactSubmit').parent().append("<span class='highlight2 strong bigger1'></span>");
				$('#contactFormUl input, textarea').each(function() {
					if ($(this).attr('type') == 'textarea') {
						wrapTextarea($(this));
					} else {
						wrapInput($(this));
					}
					$(this).focus(function() {
						$(this).addClass('focused').prev('div.fieldGraphicContainer').children('div.fieldGraphic').addClass('focused');
					}).blur(function() {
						$(this).removeClass('focused').prev('div.fieldGraphicContainer').children('div.fieldGraphic').removeClass('focused');
					});
				});
			}
			$('#contactFormUl li.inputPrompt span').empty();
			$('#contactSubmit').click(contactSubmitClicked).attr('disabled', false).removeClass('disabledSubmit').siblings('span').empty();
			$('#contactFormUl input, textarea').attr('disabled', false).val('').removeClass('focused').prev('div.fieldGraphicContainer').children('div.fieldGraphic').removeClass('focused');
			break;
		case 5: /*Quiche*/
			if (!supportsFontFace) {
				$('#pageQuiche h1').before("<h1><img id='headingQuiche' class='heading' src='images/heading_quiche.png' /></h1>").remove();
			}
			if (!oneTimeSetupComplete[index]) {
				oneTimeSetupComplete[index] = true;
				$('#pageQuiche img').each(function() {
					$(this).attr('src', 'images/' + $(this).attr('id'));
				});
			}
			break;
	}
}

function gotoPage(index, section) {
	lastPageIndex = currentPageIndex;
	if (currentPageIndex == index) {
		if (currentPageSection == section) {
			/* */
		} else {
			currentPageSection = section;
			setupPageLogic(index);
		}
	} else {
		currentPageIndex = index;
		currentPageSection = section;
		setAllNavLinkImgsToUpState();
		setNavLinkToCurrent(currentPageIndex);
		var page = pageArray[index];
		showOverlay(true);
		setupPageLogic(index);
		loadPageImages(index);
	}
}

function getPageIndexFromNavId(id) {
	return getPageIndex(id.substring(3));
}

function hideAllPages() {
	$('div.page').hide();
}

function setAllNavLinkImgsToUpState() {
	$('li.navLink a img').each(function() {
		$(this).attr('src', 'images/' + $(this).closest('li.navLink').attr('id') + '.png');
	});
}

function setNavLinkToCurrent(pageIndex) {
	$('#nav' + pageArray[pageIndex] + ' img').attr('src', 'images/nav' + pageArray[pageIndex] + 'Current.png');
}

function setPageTitle(title) {
	document.title = pageTitleBase + title;
}

function extractPageIndexFromUrl() {
	var url = window.location.href;
	var poundIndex = url.indexOf("#/");
	var afterPound = url.substring(poundIndex + 2);
	var underscoreIndex = afterPound.indexOf("_");
	if (underscoreIndex >= 0) {
		return getPageIndex(afterPound.substring(0, underscoreIndex));
	} else {
		return getPageIndex(afterPound);
	}
}

function extractPageSectionFromUrl() {
	var url = window.location.href;
	var poundIndex = url.indexOf("#/");
	var afterPound = url.substring(poundIndex + 2);
	var underscoreIndex = afterPound.indexOf("_");
	if (underscoreIndex >= 0) {
		return afterPound.substring(underscoreIndex + 1);
	} else {
		return "";
	}
}

function setPageUrl(page, section) {
	var addressVal = page;
	if (section != null && section != undefined && section != "") {
		addressVal += "_" + section;
	}
	$.address.value(addressVal);
	/*****************************/
	trackViewWithGoogleAnalytics();
	/*****************************/
}

function urlChanged(event) {
	if (!regularNavigationInProgress) {
		var index = extractPageIndexFromUrl();
		var section = extractPageSectionFromUrl();
		gotoPage(index, section);
	} else {
		regularNavigationInProgress = false;
	}
}

function isNumeric(value) {
	if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
	return true;
}

function welcomeResponseCheckboxClicked() {
	$('#welcomeResponsesUl div.checkbox').removeClass('checked');
	$(this).addClass("checked");
	var name = $(this).parent().attr('id').substring("welcomeResponse_".length);
	if (name.toLowerCase() != 'google') {
		regularNavigationInProgress = true;
		$('#welcomeResponsesUl div.checkbox').unbind();
	}
	switch (name.toLowerCase()) {
		case "quiche":
			gotoPage(5);
			break;
		case "site":
			gotoPage(1, "Sites");
			break;
		case "software":
			gotoPage(1, "Software");
			break;
		case "game":
			gotoPage(1, "Games");
			break;
		case "about":
			gotoPage(3);
			break;
		case "contact":
			gotoPage(4);
			break;
		case "google":
			$('#welcomeResponse_googleconfirm').fadeIn(300);
			break;
		default:
			gotoPage(0);
			break;
	}
}

function googleConfirmYesClick() {
	setPageUrl(0, 'Welcome');
	location.replace('http://www.google.com/');
}

function googleConfirmNoClick() {
	$('#welcomeResponse_googleconfirm').fadeOut(300);
	$('#welcomeResponsesUl div.checkbox').removeClass("checked").click(welcomeResponseCheckboxClicked);
}

function highlightAndMoveService(section) {
	if (section == null || section == undefined) {
		section = "";
	}
	var serviceToHighlight = false;
	switch (section.toLowerCase()) {
		case "site":
		case "sites":
			serviceToHighlight = "Sites";
			break;
		case "software":
			serviceToHighlight = "Software";
			break;
		case "game":
		case "games":
			serviceToHighlight = "Games";
			break;
		case "other":
		case "others":
			serviceToHighlight = "Other";
			break;
		default:
			break;
	}
	$('#pageServices div.serviceContainer, h2, p').removeClass('highlight');
	$('#pageServices div.serviceContainer p').hide();
	if (serviceToHighlight) {
		$('#servicesContainer' + serviceToHighlight + ', #servicesHeading' + serviceToHighlight + ', #servicesParagraph' + serviceToHighlight).addClass('highlight').show();
		$('#servicesContainer' + serviceToHighlight).prependTo('#allServicesContainer');
		var services = new Array('Sites', 'Software', 'Games', 'Other');
		var s;
		for (var i = 0; i < services.length; i++) {
			s = services[i];
			if (s != serviceToHighlight) {
				$('#servicesContainer' + s).appendTo('#allServicesContainer');
			}
		}
	}
}

function filterPortfolio(section, updateUrl) {
	if (section == null || section == undefined) {
		section = "";
	}
	var classToShow = false;
	var sectionForUrl = "";
	switch (section.toLowerCase()) {
		case "site":
		case "sites":
			classToShow = "site";
			sectionForUrl = "Sites";
			break;
		case "software":
			classToShow = "software";
			sectionForUrl = "Software";
			break;
		case "game":
		case "games":
			classToShow = "game";
			sectionForUrl = "Games";
			break;
		case "other":
		case "others":
			classToShow = "other";
			sectionForUrl = "Other";
			break;
		case "client":
		case "clients":
			classToShow = "clients";
			sectionForUrl = "Clients"
			break;
		default:
			sectionForUrl = "All";
			break;
	}
	if (classToShow) {
		$('div.portfolioItem').each(function() {
			if ($(this).hasClass(classToShow)) {
				$(this).show();
			} else {
				$(this).hide();
			}
		});
	} else {
		$('div.portfolioItem').show();
	}
	if (classToShow != "clients") {
		$("#clients").hide();
	}
	$('#portfolioNav span').removeClass('navLinkSelected');
	$('#portfolioNavLink' + sectionForUrl).addClass('navLinkSelected');
	if (updateUrl) {
		regularNavigationInProgress = true;
		setPageUrl(pageArray[currentPageIndex], sectionForUrl);
	}
	currentPageSection = sectionForUrl;
}

function trimContactFields() {
	$('#contactFormUl input, textarea').each(function() {
		$(this).val($.trim($(this).val()));
	});
}

function removeOnFinish() {
	$(this).remove();
}

function contactSubmitClicked() {
	trimContactFields();
	var greenlight = true;
	$('#contactFormUl input, textarea').each(function() {
		if ($(this).val() == '') {
			greenlight = false;
			var name = $(this).attr('id').substring(7);
			switch (name) {
				case 'Name':
					msg = "Hey! What's your name?";
					break;
				case 'Email':
					msg = "How might I go about contacting you?";
					break;
				case 'Message':
					msg = "Surely you've got something to say!";
					break;
				default:
					msg = '';
			}
			$(this).parent().prev('li').children('span:empty').html("<img class='leftArrow' src='images/leftarrow.png' />" + msg).hide().fadeIn(200);
		} else {
			$(this).parent().prev('li').children('span').fadeOut(200, function() {
				$(this).empty();
			});
		}
	});
	if (greenlight) {
		$('#contactFormUl input, textarea').attr('disabled', true);
		$('#contactSubmit').attr('disabled', true).removeClass('submit').addClass('disabledSubmit').unbind('click').siblings('span').html('Your message has been sent. Thanks again!<img class="smiley" src="images/smiley.jpg" alt="8^)" />').hide().fadeIn(400);
		$.post("scripts/emailme.php", {
			name: $('#contactName').val(),
			email: $('#contactEmail').val(),
			message: $('#contactMessage').val()
		});
		
	}
}

function wrapInput(input) {
	input.before('<div class="fieldGraphicContainer"><div class="fieldGraphic inputGraphic"><img src="images/input_left.png" class="floatLeft" alt="" /><img src="images/input_right.png" alt="" class="floatRight" /></div></div>');
	input.prev('div.fieldGraphicContainer').css('zIndex', input.css('zIndex') - 1);
}

function wrapTextarea(textarea) {
	textarea.before('<div class="fieldGraphicContainer"><div class="fieldGraphic textareaGraphic"><img src="images/textarea_left.png" class="floatLeft" alt="" /><img src="images/textarea_right.png" alt="" class="floatRight" /></div></div>');
	textarea.prev('div.fieldGraphicContainer').css('zIndex', textarea.css('zIndex') - 1);
}

function removeItemFromArrayWhereValueEquals(valueToRemove, array) {
	array = jQuery.grep(array, function(value) {
		return value != valueToRemove;
	});
}

function removeWhiteSpace(text) {
	return text.replace(/^\s*|\s*$/g, '');
}


/**********************/
/**********************/
// addEvent and removeEvent, designed by Aaron Moore
function addEvent(element, listener, handler) {
	//if the system is not set up, set it up, and
	// store any outside script's event registration in the first handler slot
	if (typeof element[listener] != 'function' ||
	typeof element[listener + '_num'] == 'undefined') {
		element[listener + '_num'] = 0;
		if (typeof element[listener] == 'function') {
			element[listener + 0] = element[listener];
			element[listener + '_num']++;
		}
		element[listener] = function(e) {
			var r = true;
			e = (e) ? e : window.event;
			for (var i = 0; i < element[listener + '_num']; i++) 
				if (element[listener + i](e) === false) r = false;
			return r;
		}
	}
	//if handler is not already stored, assign it
	for (var i = 0; i < element[listener + '_num']; i++) 
		if (element[listener + i] == handler) return;
	element[listener + element[listener + '_num']] = handler;
	element[listener + '_num']++;
}

function removeEvent(element, listener, handler) {
	//if the system is not set up, or there are no handlers to remove, exit
	if (typeof element[listener] != 'function' ||
	typeof element[listener + '_num'] == 'undefined' ||
	element[listener + '_num'] == 0) return;
	//loop through handlers,
	//  if target handler is reached, begin overwriting each
	//  handler with the handler in front of it until one before the last
	var found = false;
	for (var i = 0; i < element[listener + '_num']; i++) {
		if (!found) found = element[listener + i] == handler;
		if (found && (i + 1) < element[listener + '_num']) element[listener + i] = element[listener + (i + 1)];
	}
	//if handler was found, decrement the handler count
	if (found) element[listener + '_num']--;
}

function trackViewWithGoogleAnalytics() {
	try {
		var pageTracker = _gat._getTracker("UA-10919241-1");
		pageTracker._trackPageview();
	} catch (err) {
		/*alert(err);*/
	}
}
