navs = {};

// image filenames (off state):      section_name-off.*
// image filenames (over/on state):  section_name-on.*
// nav container ID:                 logo
navs.logo = {
	init: function() {
		this.preload();
		$('#logo a span').hover(
			// hover on
			function () {
				$(this).css('background-image', navs.logo.rollover($(this).css('background-image')));
			},
			// hover off
			function () {
				// prevent the creation of stacked actions
				$(this).stop(true, false);
				$(this).css('background-image', navs.logo.rolloff($(this).css('background-image')));
			}
		);
	},

	preload: function() {
		$(window).bind('load', function() {
			var preloadCssImgUrl = $('#logo a span').css('background-image');
			// remove url(...) shell
			// requires absolute image paths
			if (preloadCssImgUrl) {
				var preloadImgSrc = preloadCssImgUrl.replace(/^url\([\'\"]*/, '').replace(/[\'\"]*\)$/, '');
				$('<img>').attr('src', navs.logo.rollover(preloadImgSrc));
			}
		});
	},

	rollover: function(src) {
		return src.split('-off.').join('-on.');
	},

	rolloff: function(src) {
		return src.split('-on.').join('-off.');
	}
};

// JS variable with active section:  var topNavActive = 'section_name'
// nav link IDs:                     topNav_section_name
// CSS class (over/on state):        .selected
navs.topNav = {
	init: function() {
		this.preload();
		$('#topNav a').each(
			function(i, obj) {
				if ($(this).attr('id') == 'topNav_'+topNavActive) {
					// highlight the current section
					$(this).addClass('selected');
				} else {
					$(this).hover(
						// hover on
						function () {
							$(this).addClass('selected');
						},
						// hover off
						function () {
							// prevent the creation of stacked actions
							$(this).stop(true, false);
							$(this).removeClass('selected');
						}
					);
				}
			}
		);
	},

	preload: function() {
		$(window).bind('load', function() {
			var preloadImgUrl = "/images/background-masthead-on.png";
			$('<img>').attr('src', preloadImgUrl);
		});
	}
};

/////////////////////////////////////////////////////////////////////////////

var AJAX_SUCCESS = 0;
var AJAX_FAILURE = 1;

var REPORT_COOKIE_PREFIX = 'downrightnow_report_';
var REPORT_COOKIE_LIFETIME_DAYS = 1;

function submitReport(userReportType) {
	$('form#reportForm input#seq').attr('value', parseInt(new Date().getTime()/1000));
	$('form#reportForm input#user_report_type').attr('value', userReportType);

	$('#reportForm').css('display', 'none');
	$('#reportFormProgress').css('display', 'block');

	if ($('form#reportForm input#service_shortname').attr('value') == 'unset') {
		submitReportError();
	} else {
		$.ajax({
			type: 'POST',
			url: $('form#reportForm').attr('action'),
			data: $('form#reportForm').serialize(),
			dataType: 'text',	// expected response
			timeout: 10 * 1000,	// 10s
			success: submitReportSuccess,
			error: submitReportError
		});
	}

	return false;
}

function submitReportSuccess(data, textStatus) {
	if (data == AJAX_SUCCESS) {
		$('#reportFormProgress').css('display', 'none');
		$('#reportFormSuccess').css('display', 'block');
		var shortName = $('form#reportForm input#service_shortname').attr('value');
		var userReportType = "Unknown";
		switch (parseInt($('form#reportForm input#user_report_type').attr('value'))) {
			case 1:
				userReportType = "Service Up";
				break;
			case 2:
				userReportType = "Service Problems";
				break;
			case 3:
				userReportType = "Service Down";
				break;
			default:
		}
		if (typeof pageTracker == 'object') {
			pageTracker._trackEvent('User Reports', userReportType, shortName);
		}
		$.cookie(REPORT_COOKIE_PREFIX+shortName, 1,
			{ expires: REPORT_COOKIE_LIFETIME_DAYS });
		markDupeReportButtons();
	} else {
		submitReportError();
	}
}

function submitReportError(XMLHttpRequest, textStatus, errorThrown) {
	$('#reportFormProgress').css('display', 'none');
	$('#reportFormError').css('display', 'block');
}

function showReportForm(serviceName, shortName, url) {
	$('form#reportForm input#service_shortname').attr('value', shortName);
	$('#reportFormVisitLink').attr('href', url);
	$('.reportFormServiceName').text(serviceName);

	$('#reportFormProgress').css('display', 'none');
	$('#reportFormSuccess').css('display', 'none');
	$('#reportFormError').css('display', 'none');

	if ($.cookie(REPORT_COOKIE_PREFIX+shortName)) {
		$('form#reportForm').css('display', 'none');
		$('#reportFormDupe').css('display', 'block');
	} else {
		$('#reportFormDupe').css('display', 'none');
		$('form#reportForm').css('display', 'block');
	}

	$('#reportFormBox').modal({
		containerId: 'simplemodal-container-reportForm',
		closeHTML: '<h2><a href="#">X</a>Report an Issue with '+serviceName+'</h2>',
		position: ['25%',],
		// persistance required to avoid loss of PNG transparency
		// in IE6 upon repeat window openings
		persist: true
	});
}

function markDupeReportButtons() {
	$('.reportButton').each(
		function(i, obj) {
			var shortName = $(this).attr('id');
			if (shortName && shortName.length) {
				shortName = shortName.replace(/reportButton_/, '');
				if ($.cookie(REPORT_COOKIE_PREFIX+shortName)) {
					$(this).addClass('reportButtonDupe');
				}
			}
		}
	);
}

/////////////////////////////////////////////////////////////////////////////

var relativeDatesTimer = null;
var relativeDatesUpdateFrequencyMs = 60 * 1000; // 1m

function updateRelativeDates() {
	$('.timestamp').humaneDates();
}

var refreshHash = '#refresh';
var refreshPageTimer = null;
var pageRefreshFrequencyMs = 5 * 60 * 1000; // 5m

function doPageRefresh() {
	if ($('#simplemodal-container-reportForm').length) {
		// postpone reload if modal windows are open
		refreshPageTimer = setTimeout('doPageRefresh()', pageRefreshFrequencyMs);
	} else {
		window.location.reload();
	}
}

function setPageRefresh(state, refreshNow) {
	if (state) {
		if (window.location.hash != refreshHash) {
			window.location.hash = refreshHash;
		}
		if (refreshNow) {
			window.location.reload();
		} else {
			refreshPageTimer = setTimeout('doPageRefresh()', pageRefreshFrequencyMs);
		}
	} else if (refreshPageTimer) {
		window.location.hash = '';
		clearTimeout(refreshPageTimer);
	}
}

/////////////////////////////////////////////////////////////////////////////

function trackOutboundLink(href) {
	if (typeof pageTracker == 'object') {
		pageTracker._trackEvent('Outbound Links', 'Click', href);
	}
}

/////////////////////////////////////////////////////////////////////////////

$(document).ready(
	function() {
		try {
			$('.requiresJavaScript').css('display', 'inline');
			$('.javaScriptLink').attr('href', '#');
			if ($('.timestamp').length) {
				relativeDatesTimer = setInterval('updateRelativeDates()', relativeDatesUpdateFrequencyMs);
				updateRelativeDates();
				$('.timestampRelative, .toolTip').wTooltip({
					className: 'toolTipAppearance'
				});
			}
			navs.logo.init();
			navs.topNav.init();
			if (window.location.hash == refreshHash) {
				$('#autoRefresh').attr('checked', 'checked');
				setPageRefresh(true);
			} else {
				$('#autoRefresh').attr('checked', '');
			}
			markDupeReportButtons();
		} catch(err) {}
	}
);
