var scroller_options = {
	title: 'Latest Alerts',
	rss_url: 'rss.xml',	// Needs to have 'text/xml' mimetype for IE?
	container: '#rss_scroller'
}


// Add foundational elements and then load items 
var scroller_init = function() {
	var month = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
	
	/* generate the base HTML in the container */
	$(scroller_options.container).html('\
		<h1>{title}</h1>\
		<form action="#">\
			<label for="alertFilter">Filter:</label>\
			<select id="alertFilter" name="alertFilter">\
				<option value="">All Alerts</option>\
				<optgroup label="Geographic Area">\
					<option value="region">Regional</option>\
					<option value="portland">Portland</option>\
					<option value="multnomah_co">Multnomah County</option>\
					<option value="clackamas_co">Clackamas County</option>\
					<option value="columbia_co">Columbia County</option>\
					<option value="washington_co">Washington County</option>\
					<option value="clark_co">Clark County</option>\
				</optgroup>\
				<optgroup label="Alert Type">\
					<option value="roads">Roads</option>\
					<option value="transit">Transit</option>\
					<option value="health">Public Health</option>\
					<option value="utility">Utilities</option>\
					<option value="fire">Fire</option>\
					<option value="police">Law Enforcement</option>\
					<option value="emergency">Emergency Manangement</option>\
					<option value="social">Social Services</option>\
					<option value="weather">Weather</option>\
					<option value="other">Other</option>\
				</optgroup>\
			</select>\
		</form>\
		<div id="reloadAlerts">\
			<h3>Looking for the latest alerts?</h3>\
			<p>We continuously check for any new alerts and automatically display them on the page as they arrive. However, it\'s been a while since you last interacted with this page and we need to make sure you\'re still monitoring this page.</p>\
			<p>If you\'d like us to resume checking for new alerts, please click the button below or refresh the page.</p>\
			<div class="buttonWrapper"><button class="sexybutton sexyyellow" onclick="resumeAutoReload()"><span><span>Check for New Alerts</span></span></button></div>\
		</div>\
		<img class="spinner" src="/shared/js/rss-scroller/images/spinner.gif" alt="Loading...">\
		<div class="items"><ul></ul></div>\
	'.supplant(scroller_options));
	/* end the base HTML generation */
	
	// Event handler for item links
	$(scroller_options.container + ' li').live('click',function() {
		window.location = $(this).find('a.source').attr('href');
	});

	// onChange handler for the alert filter select box
	$('#alertFilter').change(function() {
		window.location.hash = this.value;
		if (this.value.length)
			$.cookie('filter', this.value, { expires: 30 });
		else
			$.cookie('filter', null);		// Delete cookie
		scroller_init();
	});

	// Load items
	scroller_load();
};


// Get items and add them to the foundation initialized above
var scroller_load = function() {
	var newItems = $('<div><ul></ul></div>');
	
	// Load filter specified in url hash (if any), or saved in cookie (if any)
	var filter = '';
	var filterParam = '';
	if (window.location.hash == '' && $.cookie('filter') != null) {
		window.location.hash = $.cookie('filter');
	}
	if (window.location.hash.length > 1) {
		filter = window.location.hash.substr(1);	// Strip leading '#'
		var filterOpt = $('#alertFilter').find('option[value=' + filter + ']');
		if (filterOpt.length) {
			filterOpt.attr("selected","selected");
			filterParam = "?filter=" + filter;
		} else {
			// Invalid hash in URL so remove it
			filter = '';
			window.location.hash = filter;
		}
	}
	
	/* GET AJAX call to the RSS feed  */
	$.get(scroller_options.rss_url + filterParam,{},function(xml) {
		$('item',xml).each(function(i) {
			// Convert timestamp into local timezone and human friendly format
			// Uses toString() from date.js -- http://code.google.com/p/datejs/wiki/FormatSpecifiers
			timestamp = new Date($(this).find('pubDate').text()).toString('dddd, MMMM d, yyyy h:mm tt');
			
			var item = {
				location: $(this).find('link').text(),
				img:''
			};
			
			if (item.location.indexOf('publicalerts') > -1 || item.location.indexOf('PublicAlerts') > -1){
				item.img = 'publicalerts.png';
			}
			else if (item.location.indexOf('TripCheckPDX') > -1){
				item.img = 'tripcheck.png';
			}
			else if (item.location.indexOf('CRESA') > -1){
				item.img = 'cresa.png';
			}
			else if (item.location.indexOf('211infoAlerts') > -1){
				item.img = '211infoAlerts.png';
			}
			else if (item.location.indexOf('portlandfirepio') > -1){
				item.img = 'portlandfire.gif';
			}
			else if (item.location.indexOf('TVFR') > -1){
				item.img = 'tvfr.png';
			}
			else if (item.location.indexOf('clackamasfire') > -1){
				item.img = 'ClackamasFire.png';
			}
			else if (item.location.indexOf('PBOTinfo') > -1){
				item.img = 'pbot.png';
			}
			else if (item.location.indexOf('BDSPortland') > -1){
				item.img = 'BDSPortland.jpg';
			}
			else if (item.location.indexOf('BESPortland') > -1){
				item.img = 'bescso.png';
			}
			else if (item.location.indexOf('OregonGuard') > -1){
				item.img = 'oregonguard.png';
			}
			else if (item.location.indexOf('PDXParksandRec') > -1){
				item.img = 'parksandrec.png';
			}
			else if (item.location.indexOf('PDXInfo8234000') > -1){
				item.img = 'pdxinfo.png';
			}
			else if (item.location.indexOf('PortlandHousing') > -1){
				item.img = 'phb.jpg';
			}
			else if (item.location.indexOf('portlandwater') > -1){
				item.img = 'water.png';
			}
			else if (item.location.indexOf('HillsboroFire') > -1){
				item.img = 'HillsboroFire.png';
			}
			else if (item.location.indexOf('SandyFireDist') > -1){
				item.img = 'SandyFireDist.png';
			}
			else if (item.location.indexOf('flypdx') > -1){
				item.img = 'flypdx.jpg';
			}
			else if (item.location.indexOf('TRIMET') > -1){
				item.img = 'trimet.png';
			}
			else if (item.location.indexOf('WACTRAN') > -1){
				item.img = 'ctran.png';
			}
			else if (item.location.indexOf('portofportland') > -1){
				item.img = 'pop.png';
			}
			else if (item.location.indexOf('weather.gov') > -1){
				item.img = 'nws.png';
			}
			else if (item.location.indexOf('pbnotify') > -1 || item.location.indexOf('PortlandPolice') > -1){
				item.img = 'police.png';
			}
			else if (item.location.indexOf('washcoroads') > -1){
				item.img = 'washcoroads.png';
			}
			else if (item.location.indexOf('nwnatural') > -1){
				item.img = 'nwnatural.png';
			}
			else if (item.location.indexOf('ClarkCoWA') > -1 || item.location.indexOf('ClarkCoWa') > -1){
				item.img = 'ClarkCoWA.png';
			}
			else if (item.location.indexOf('MultCoBridges') > -1){
				item.img = 'MultCoBridges.png';
			}
			else if (item.location.indexOf('MultCoRoads') > -1){
				item.img = 'MultCoRoads.png';
			}
			else if (item.location.indexOf('MultCoEM') > -1){
				item.img = 'MultCoEM.png';
			}
			else if (item.location.indexOf('multco') > -1){
				item.img = 'multco.png';
			}
			else if (item.location.indexOf('multcopets') > -1){
				item.img = 'multcopets.png';
			}
			else if (item.location.indexOf('MultCoHealth') > -1){
				item.img = 'MultCoHealth.png';
			}
			else if (item.location.indexOf('clackamascounty') > -1){
				item.img = 'Clackamascounty.png';
			}
			else if (item.location.indexOf('pgemedia') > -1){
				item.img = 'pgemedia.png';
			}
			
			$(newItems).find('ul').append('\
				<li>\
					<p>\
						<a href="{linkURL}"><img width="40" height="40" src="images/feedicons/{image}" alt=""></a>\
						{title}<br>\
						<a class="date source" href="{linkURL}">{timestamp}</a>\
					</p>\
				</li>\
			'.supplant({
				linkURL: $(this).find('link').text(),
				image: item.img,
				title: $(this).find('title').text(),
				timestamp: timestamp
			}));
		});
		
		// Show message if there are no alerts
		if ($('item',xml).length == 0) {
			$(newItems).find('ul').append('\
				<li>\
					<p>\
						<em>No recent alerts</em>\
						<a class="source" href="#"></a>\
					</p>\
				</li>\
			');
		}
		
		// Replace current items with new items
		$(scroller_options.container + ' .items').html( $(newItems).html() );
		
		// Hide the AJAX spinner
		$(scroller_options.container + ' img.spinner').hide();
	},'xml');
};


// Enable automatically reloading alerts every RELOAD_INTERVAL seconds
var enableAutoReload = function() {
	var RELOAD_INTERVAL = 60;		// Reload interval (in seconds)
	var RELOAD_TIMEOUT = 60;		// Duration (in minutes) after which auto reloading stops until manually resumed
	
	$('#reloadAlerts').slideUp();
	
	var initTime = new Date().getTime() / 1000 / 60;
	var reloadInterval = window.setInterval(function() {
		var currentTime = new Date().getTime() / 1000 / 60;
		var minutesElapsed = Math.floor(currentTime - initTime);
		
		// Auto reload for RELOAD_TIMEOUT minutes, then prompt to resume auto reloading
		// This forces the auto reloading on an open page to eventually timeout
		if (minutesElapsed < RELOAD_TIMEOUT) {
			// console.log("Reloading alerts...", minutesElapsed);
			scroller_load();
		} else {
			clearInterval(reloadInterval);
			
			// Prompt user to resume auto reloading
			$('#reloadAlerts').slideDown();
		}
	}, RELOAD_INTERVAL * 1000);
};

// 'Check for New Alerts' button handler to reload alerts and resume auto reloading
var resumeAutoReload = function() {
	scroller_load();
	enableAutoReload();	
};


// Kick it all off after page loads...
$(document).ready(function() {
	scroller_init();	
	enableAutoReload();	
});


// Supplant function allows for variable substitution inside a string
// http://javascript.crockford.com/remedial.html
String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};


