var TENTHMIL = {
	Config : {
		iSlidePaging : 6
		,gaUA : "UA-12131804-1"
		,iTimelineStartDate : "-5000"
		,iUserCeiling : 10
		,sHoverClass : "ie-hover"
		,sHoverSel : "li.share"
		,sHTMLtag : "can-has-js"
		,sParamsTimeline : "bundle=true&amp;timeline-use-local-resources=true"
		,sPathImg : "/-/img/"
		,sPathTimeline : "/-/js/lib/timeline/"
		,sPathTimelineAJAX : "/-/js/lib/timeline/api/simile-ajax-api.js"
		,sPathTimelineEvents : "/timeline/events"
		,sPathAEtemplate : "/-/tmpl/add-edit-event-times.html"
		,sPNGSel : "img, #nav-wrapper, #splash, #splash .inner, .sub-nav, .sub-nav ul, #slides ul.nav a, body.tm-home #slides p.pages, #campaign-index li, #campaign-index h2, #campaign-index li a, #content, #content .inner, #content .inner-container, .author-partner ul li, #footer, #footer .inner, div.simileAjax-bubble-innerContainer div, .poll-results span, #q-screen, .promo-unwatch p img, .promo-watch p img, #sitemap-policy ul li, #sitemap-rest ul li"
		,sPollSlug : "results"
		,aAddressDefaults : [
			{
				id : "ae-venue-address-street"
				,val : "Street"
			}
			,{
				id : "ae-venue-address-city"
				,val : "City"
			}
			,{
				id : "ae-venue-address-state"
				,val : "State"
			}
			,{
				id : "ae-venue-address-zip"
				,val : "Zipcode"
			}
		]
		,aSocialDefaults : [
			{
				id : "register-web"
				,val : "http://"
			}
			,{
				id : "register-twitter"
				,val : "http://www.twitter.com/"
			}
			,{
				id : "register-facebook"
				,val : "http://www.facebook.com/"
			}
		]
	}

	/*
		STOP EDITING HERE
	*/
	,init : function() {
		var c = TENTHMIL;
		var p = c.Project;

		$(document).ready(function() {
			p.tagIt();

			p.slides();
			p.calArchive();
			p.eePatches.init();
			p.faqbox();
			p.pollListing();
			p.timeline();
			p.toggle();
			p.watchList();
			if (typeof DD_belatedPNG != "undefined") {
				p.ieHover();
				DD_belatedPNG.fix(c.Config.sPNGSel);
			}
		});
		$.ga.load(c.Config.gaUA);
	}

	/*
		CLIENT-SPECIFIC FUNCTIONS
	*/
	,Project : {
		tagIt : function() {
			var c = TENTHMIL;
			$("html").addClass(c.Config.sHTMLtag);
		}

		,calArchive : function() {
			var c = TENTHMIL;
			var p = c.Project;
			$("#secondary .calendar").each(function() {
				var oNav = $(this).find("caption a.prev, caption a.next");
				var oContent = $(this).children("div");

				oNav.click(function() {
					$.ajax({
						cache : false,
						url: $(this).attr("href"),
						success : function(src) {
							oContent.html(src);
							p.calArchive();
						}
					});
					return false;
				});
			});
		}

		,calPicker : {
			// Parameters
			Config : {
				aMonths : ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
				,aDays : ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
				,aMonthLengths : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
			}

			,init : function() {
				var c = TENTHMIL;
				var p = c.Project;

				$("div.ae-date").append('<div class="date-picker"><a class="sprite-cal" href="#">Calendar</a><div class="cal"><p class="help">Choose a day:</p><div class="inner"></div></div></div>');
				$(".date-picker .inner").html(p.calPicker.build());

				// Open/close the calendar when clicking on the calendar icon
				$("a.sprite-cal").click(function() {
					var oPar = $(this).parent();

					$("a.sprite-cal").not(this).parent().removeClass("active");

					if (oPar.hasClass("active")) {
						oPar.removeClass("active");
					} else {
						oPar.addClass("active");
					}
					return false;
				});

				// Close the calendar if a form field gains focus
				$("a.sprite-cal").parents("form").find("input, textarea").focus(function() {
					$("a.sprite-cal").parent().removeClass("active");
				});

				p.calPicker.behave();
			}
			,behave : function() {
				var c = TENTHMIL;
				var p = c.Project;
				var t = p.calPicker;

				$(".cal tbody a").click(function() {
					var oDiv = $(this).parents(".date-picker");

					var sSlug = $(this).attr("href").split("#")[1];
					var aSlug = sSlug.split("-");
					var iM = parseInt(aSlug[0]);
					var iD = parseInt(aSlug[1]);
					var iY = parseInt(aSlug[2]);

					// Supporting the new ISO-ish date format (i590)
					if (iD < 10) {
						iD = "0" + iD;
					}
					if (iM < 10) {
						iM = "0" + iM;
					}

					var oFields = oDiv.siblings("input[type=text]");
					var oTextM = oFields.filter("[name$=month]");
					var oTextD = oFields.filter("[name$=day]");
					var oTextY = oFields.filter("[name$=year]");

					oTextM.attr("value", iM);
					oTextD.attr("value", iD);
					oTextY.attr("value", iY);

					return false;
				});

				$(".cal caption b").click(function() {
					$(this).parents("table").replaceWith(t.build());
					t.behave();
				});

				$(".cal caption a").click(function() {
					var sSlug = $(this).attr("href").split("#")[1];
					var aSlug = sSlug.split("-");
					var iM = aSlug[0];
					var iY = aSlug[1];

					$(this).parents("table").replaceWith(t.build(iM, iY));
					t.behave();

					return false;
				});
			}
			,build : function(m, y) {
				var c = TENTHMIL;
				var p = c.Project;
				var t = p.calPicker;

				// This month
				var oDate = new Date();
				var iM = (isNaN(m)) ? oDate.getMonth() : parseInt(m);
				var iY = (isNaN(y)) ? oDate.getFullYear() : parseInt(y);
				var sM = t.Config.aMonths[iM];
				var iMonthLength = t.Config.aMonthLengths[iM];

				// Get information about starting points
				var firstDay = new Date(iY, iM, 1);
				var startDay = firstDay.getDay();

				// Is this a leap year?
				if (iM == 1) {
					if ((iY % 4 == 0 && iY % 100 != 0) || iY % 400 == 0) {
						iMonthLength = 29;
					}
				}

				// TOGGLE IT
				var iNextM = iM + 1;
				var iNextY = iY;
				var iPrevM = iM - 1;
				var iPrevY = iY;

				if (iM == 11) {
					var iNextM = 0;
					var iNextY = iY + 1;
				}

				if (iM == 0) {
					var iPrevM = 11;
					var iPrevY = iY - 1;
				}

				// Begin building the HTML string
				var sHTML = '<table><caption><b>' + sM + ' ' + iY + '</b><a class="prev" href="#' + iPrevM + '-' + iPrevY + '">Previous</a> <a class="next" href="#' + iNextM + '-' + iNextY + '">Next</a></caption><thead><tr>';
				for (var i = 0; i < t.Config.aDays.length; i++) {
					sHTML += '<th scope="col"><abbr title="' + t.Config.aDays[i] + '">' + t.Config.aDays[i].charAt(0) + '</abbr></th>';
				}
				sHTML += '</tr></thead>';

				// LOOP LIKE YOU'VE NEVER LOOPED BEFORE
				var day = 1;
				// Outer loop: weeks
				for (var i = 0; i < 9; i++) {
					if (i == 0) {
						sHTML += '<tbody><tr>';
					}
					// Inner loop: days
					for (var j = 0; j <= 6; j++) {
						sHTML += '<td>';
						if (day <= iMonthLength && (i > 0 || j >= startDay)) {
							sHTML += '<a href="#' + (iM + 1) + '-' + day + '-' + iY + '">' + day + '</a>';
							day++;
						}
						sHTML += '</td>';
					}
					if (day > iMonthLength) {
						break;
					} else {
						sHTML += '</tr><tr>';
					}
				}
				sHTML += '</tr></tbody></table>';

				return sHTML;
			}
		}
		,faqbox : function() {
			if ($("a.info").length) {
				var fHideIt = function() {
					$("body").removeClass("show-q");

					if (this.tagName && this.tagName.toUpperCase() == "A") {
						return false;
					}
				}

				$("body").append('<div id="q-screen"></div><div id="q-content"><div class="inner"></div></div>');

				$("#q-screen, #q-content").click(fHideIt);

				$("a.info").click(function() {
					var sSlug = $(this).attr("href").split("#")[1];
					var oTitle = $("#" + sSlug);
					var sTitle = oTitle.html();
					var oAnswer = oTitle.next("dd").html();

					$("#q-content div.inner").html('<h2>' + sTitle + '</h2><div>' + oAnswer + '<a class="close" href="#">{ x } Close window.</a></div>');
					$("#q-content a.close").click(fHideIt);
					$("body").addClass("show-q");

					return false;
				});

				// Hide the modal window if the escape key is pressed
				document.onkeydown = function(e) {
					var keycode = (e == null) ? event.keyCode : e.which;

					if (keycode == 27) { // is escape?
						fHideIt();
					}
				}
			}
		}
		,eePatches : {
			init : function() {
				var c = TENTHMIL;
				var p = c.Project;
				var t = p.eePatches;

				t.addresses();
				t.formEvents();
			}
			,addresses : function() {
				var c = TENTHMIL;
				var iCeil = c.Config.aAddressDefaults.length;
				for (var i = 0; i < iCeil; i++) {
					var oEntry = c.Config.aAddressDefaults[i];
					var oEl = $("#" + oEntry.id);
					if (oEl.length) {
						oEl.attr("def", oEntry.val);
						if (oEl.attr("value").length == 0) {
							oEl.attr("value", oEntry.val);
						}

						oEl.focus(function() {
							if ($(this).attr("value") == $(this).attr("def")) {
								$(this).attr("value", "");
							}
						});
						oEl.blur(function() {
							if ($(this).attr("value") == "") {
								$(this).attr("value", $(this).attr("def"));
								$(this).removeClass("changed");
							} else {
								if ($(this).attr("value") != $(this).attr("def")) {
									$(this).addClass("changed");
								}
							}
						});
					}
				}
			}
			,formEvents : function() {
				var c = TENTHMIL;
				var p = c.Project;

				// Insert placeholder DIV
				$("div.ae-datetime:last").after('<div class="temp"></div>');

				// Load in the template; continue with the rest of the script patch if it loads successfully
				$("div.ae-datetime + div.temp").load(c.Config.sPathAEtemplate, function() {
					// Convert input@type=text to input@type=hidden; strip out the old fields
					$("div.ae-datetime input[type=text]").each(function() {
						var oEl = $(this);
						var sID = oEl.attr("id");
						var sVal = oEl.attr("value");
						var sName = oEl.attr("name");
						var sHTML = '<input type="hidden" id="' + sID + '" name="' + sName + '" value="' + sVal + '" />';

						var oForm = oEl.parents("form");
						oForm.append(sHTML);

						oEl.parents("div.ae-datetime").remove();
					});

					// Fire the calendar picker
					p.calPicker.init();

					// Is there a default value?
					var sStartVal = $("#ae-datetime-st").attr("value");
					if (sStartVal.length > 0) {
						var rDT = /^(\d{4})\-(\d{1,2})\-(\d{1,2}) (\d{2}):(\d{2}) ([AP]M)/g;
						rDT.exec(sStartVal);

						var sY = RegExp.$1;
						var sMo = RegExp.$2;
						var sD = RegExp.$3;
						var sH = RegExp.$4;
						var sMin = RegExp.$5;
						var sMerid = RegExp.$6;

						$("#ae-start-date-year").attr("value", sY);
						$("#ae-start-date-month").attr("value", sMo);
						$("#ae-start-date-day").attr("value", sD);
						$("#ae-start-time-hour").attr("value", sH);
						$("#ae-start-time-min").attr("value", sMin);
						$("#ae-start-time-day option[value=" + sMerid + "]").attr("selected", "selected");
					}

					var sEndVal = $("#ae-datetime-end").attr("value");
					if (sEndVal.length > 0) {
						var rDT = /^(\d{4})\-(\d{1,2})\-(\d{1,2}) (\d{2}):(\d{2}) ([AP]M)/g;
						rDT.exec(sEndVal);

						var eY = RegExp.$1;
						var eMo = RegExp.$2;
						var eD = RegExp.$3;
						var eH = RegExp.$4;
						var eMin = RegExp.$5;
						var eMerid = RegExp.$6;

						$("#ae-end-date-year").attr("value", eY);
						$("#ae-end-date-month").attr("value", eMo);
						$("#ae-end-date-day").attr("value", eD);
						$("#ae-end-time-hour").attr("value", eH);
						$("#ae-end-time-min").attr("value", eMin);
						$("#ae-end-time-day option[value=" + eMerid + "]").attr("selected", "selected");
					}

					// onSubmit concatenation
					$("form#entryform").submit(function() {
						$("#ae-datetime-st").attr("value", $("#ae-start-date-year").attr("value") + "-" + $("#ae-start-date-month").attr("value") + "-" + $("#ae-start-date-day").attr("value") + " " + $("#ae-start-time-hour").attr("value") + ":" + $("#ae-start-time-min").attr("value") + " " + $("#ae-start-time-day").attr("value"));

						// Is the end month, year, and/or day left blank? Then we'll use the start day's values.
						if (($("#ae-end-date-year").attr("value").length == 0) || ($("#ae-end-date-month").attr("value").length == 0) || ($("#ae-end-date-day").attr("value").length == 0)) {
							$("#ae-datetime-end").attr("value", $("#ae-start-date-year").attr("value") + "-" + $("#ae-start-date-month").attr("value") + "-" + $("#ae-start-date-day").attr("value") + " " + $("#ae-end-time-hour").attr("value") + ":" + $("#ae-end-time-min").attr("value") + " " + $("#ae-end-time-day").attr("value"));
						} else {
							$("#ae-datetime-end").attr("value", $("#ae-end-date-year").attr("value") + "-" + $("#ae-end-date-month").attr("value") + "-" + $("#ae-end-date-day").attr("value") + " " + $("#ae-end-time-hour").attr("value") + ":" + $("#ae-end-time-min").attr("value") + " " + $("#ae-end-time-day").attr("value"));
						}

						alert($("#ae-datetime-end").attr("value"));

						$("div.ae-datetime + div.temp").remove();

						return true;
					});
				});
			}
		}
		,ieHover : function() {
			var c = TENTHMIL;
			$(c.Config.sHoverSel).hover(function() {
				$(this).addClass(c.Config.sHoverClass);
			}, function() {
				$(this).removeClass(c.Config.sHoverClass);
			});
		}
		,pollListing : function() {
			var c = TENTHMIL;
			var iC = 0;

			$(".poll-listing form p.action").each(function() {
				var sHTML = '<a href="#results-' + iC + '">Show Results <img alt="" src="' + c.Config.sPathImg + 'action-arrow-lrg.gif" /></a>';
				var oResults = $(".poll-listing .poll-results");

				if (window.location.hash.split("#")[1] != c.Config.sPollSlug) {
					oResults.attr("id", "results-" + iC);
					$(this).append(sHTML);
					oResults.addClass("suppress");

					$(this).children("a").click(function() {
						oResults.removeClass("suppress");
						$(this).remove();

						return false;
					});
				}

				iC++;
			});
		}
		,slides : function() {
			var c = TENTHMIL;
			$("#slides li").addClass("slide");
			var oSlides = $("#slides li.slide");
			c.Config.autoScroll = true;

			if (oSlides.length > 1) {

				$("#slides").append('<ul class="nav"><li class="prev"><a href="#">Previous</a></li><li class="next"><a href="#">Next</a></li></ul>');
				$("#slides li.slide:first-child").addClass("first");
				$("#slides li.slide:last-child").addClass("last");

				var tmp = 1;

				// Build the numbered slide navigation
				$("#slides").append('<p class="pages"></p>');

				oSlides.each(function() {
					$("#slides p.pages").append('<a class="top" href="#slide-' + tmp + '">' + tmp + '</a>');

					$(this).attr("id", "slide-" + tmp);

					if (tmp != 1) {
						$(this).hide();
					} else {
						$(this).show();
						$("#slides p.pages a:first-child").addClass("active");
					}
					tmp++;
				});

				$("#slides p.pages a").click(function() {
					c.Config.autoScroll = false;

					if (!$(this).hasClass("active")) {
						var sSlug = $(this).attr("href").split("#")[1]; // THANKS, INTERNET EXPLORER. REALLY.

						$("#slides li.slide").hide();
						$("#slides li.slide[id=" + sSlug + "]").fadeIn(600);

						// Change the display of the bullets
						$("#slides p.pages a").removeClass("active");
						$(this).addClass("active");
					}

					return false;
				});

				// Function to show a slide (stored in fShow for auto-paging/timeout purposes)
				var fShow = function(sDir) {
					var sDir = (c.Config.autoScroll) ? "next" : sDir;
					var oCurrent = $("#slides li.slide:visible");

					if (sDir == "next") {
						if (oCurrent.hasClass("last")) {
							var oShow = $("#slides ol li.first");
						} else {
							var oShow = oCurrent.next("li.slide");
						}
					} else if (sDir == "prev") {
						if (oCurrent.hasClass("first")) {
							var oShow = $("#slides ol li.last");
						} else {
							var oShow = oCurrent.prev("li.slide");
						}
					}

					var sId = oShow.attr("id");
					$("#slides p.pages a").removeClass("active");
					$("#slides p.pages a[href$=#" + sId + "]").addClass("active");

					oCurrent.hide();
					oShow.fadeIn(600);

					if (c.Config.autoScroll) {
						c.Config.slideTimer = window.setTimeout(fShow, c.Config.iSlidePaging * 1000);
					}
				};

				// Click handlers for the previous/next links kills the auto-paging
				$("#slides ul.nav a").click(function() {
					window.clearTimeout(c.Config.slideTimer);
					c.Config.autoScroll = false;

					var sDir = $(this).parents("li").attr("class");

					fShow(sDir);

					return false;
				});

				// Start paging through the slides onload()
				$(window).load(function() {
					window.setTimeout(fShow, c.Config.iSlidePaging * 1000);
				});
			}
		}
		,timeline : function() {
			var c = TENTHMIL;
			var p = c.Project;

			if (typeof SimileAjax != "undefined") {
				SimileAjax.History.enabled = false;
				var oTimeline = $("#timeline").get(0);

				if (oTimeline) {
					$("#timeline-stage .featured").after('<div id="tl-main"></div>');
					var oTarget = $("#tl-main").get(0);

					$(window).load(function() {
						var eventSource = new Timeline.DefaultEventSource();

						var theme = Timeline.ClassicTheme.create();
						theme.event.bubble.width = 300;
						theme.event.bubble.height = 120;
						theme.event.track.height = 35;
						theme.event.track.offset = 15;
						theme.event.tape.height = 3;
						theme.timeline_start = new Date(Date.UTC(-9000, 0, 1));
						theme.timeline_stop  = new Date(Date.UTC(2900, 0, 1));

						var aZones = [
							{
								start: "Jan 01 1500 00:00:00 GMT-0500"
								,end: "Dec 31 1899 23:59:59 GMT-0500"
								,magnify: 7
								,unit: Timeline.DateTime.CENTURY
							}
							,{
								start: "Jan 01 1900 00:00:00 GMT-0500"
								,end: "Dec 31 1989 23:59:59 GMT-0500"
								,magnify: 60
								,unit: Timeline.DateTime.DECADE
							}
							,{
								start: "Jan 01 1990 00:00:00 GMT-0500"
								,end: "Dec 31 " + new Date().getFullYear() + " 23:59:59 GMT-0500"
								,magnify: 450
								,unit: Timeline.DateTime.YEAR
							}
						];

						var d = Timeline.DateTime.parseGregorianDateTime(c.Config.iTimelineStartDate)
						var bandInfos = [
							Timeline.createHotZoneBandInfo({
								zones : aZones
								,date: d
								,intervalPixels: 150
								,intervalUnit: Timeline.DateTime.MILLENNIUM
								,theme: theme
								,width: "15px"
							}),
							Timeline.createHotZoneBandInfo({
								zones : aZones
								,date: d
								,eventSource: eventSource
								,intervalPixels: 150
								,intervalUnit: Timeline.DateTime.MILLENNIUM
								,theme: theme
								,width: "190px"
							}),
							Timeline.createHotZoneBandInfo({
								zones : aZones
								,date: d
								,eventSource: eventSource
								,intervalPixels: 150
								,intervalUnit: Timeline.DateTime.MILLENNIUM
								,layout: 'overview'
								,theme: theme
								,width: "50px"
							})
						];

						for (var i = 0; i < bandInfos.length; i++) {
							bandInfos[i].decorators = [
								new Timeline.SpanHighlightDecorator({
									startDate: new Date(Date.UTC(-40000, 0, 1)),
									endDate: new Date(Date.UTC(-8000, 0, 1)),
									cssClass: "timeline-ether-bg", // use same color as background
									inFront: true, // we want this decorator to be in front
									theme: theme
								}),
								new Timeline.SpanHighlightDecorator({
									startDate: new Date(Date.UTC(3000, 0, 1)),
									endDate: new Date(Date.UTC(10000, 0, 1)),
									cssClass: "timeline-ether-bg",
									inFront: true,
									theme: theme
								})
							];
						}

						bandInfos[1].syncWith = 0;
						bandInfos[2].syncWith = 0;
						bandInfos[2].highlight = true;

						tl = Timeline.create(oTarget, bandInfos);

						var sPathXML = c.Config.sPathTimelineEvents + "?" + new Date().getTime();

						Timeline.loadXML(sPathXML, function(xml, url) {
							eventSource.loadXML(xml, url);
						});

						$("div.timeline-date-label").each(function() {
							var sText = $(this).text();

							if (sText.toUpperCase().substr(-3) == "1BC") {
								var iText = (parseInt(sText) - 1);
								$(this).text(iText + "BC");
							}
						});
					});
				}
			}
		}
		,toggle : function() {
			var oToggle = $("input.toggle");
			oToggle.each(function() {
				var rClass = $(this).attr("class").match("\b?toggle\-(.*)");
				if (RegExp.$1) {
					var sId = "#" + RegExp.$1;

					$(sId).hide();
					$(this).click(function() {
						if (this.checked) {
							$(sId).slideDown();
						} else {
							// Reset the fields if the parent is unchecked.
							$(sId).find("input[type!=hidden]").each(function() {
								this.value = "";
								this.checked = false;
							});
							$(sId).slideUp();
						}
					});
				}
			});
		}
		,watchList : function() {
			var c = TENTHMIL;
			var p = c.Project;
			var oItems = $("div.watching-event li");
			if (oItems.length > c.Config.iUserCeiling) {
				$("div.watching-event").append('<p class="action"><a href="#">See all &raquo;</a></p>');
				var tmp = 0;
				for (var i = c.Config.iUserCeiling; i < oItems.length; i++) {
					$(oItems[i]).addClass("extra");
				}
				$("div.watching-event").addClass("squelch");

				$("div.watching-event p.action a").toggle(function() {
					$("div.watching-event").removeClass("squelch");
					$(this).html("&laquo; Hide extra")
					return false;
				}, function() {
					$("div.watching-event").addClass("squelch");
					$(this).html("See all &raquo;")
					return false;
				});
			}
		}
	}
};

TENTHMIL.init();

