/*
er_wait_times_v2.js
Javascript that pulls ER Wait Time Data

Title:          ER Wait Times
Version:        2
Author:         Jeremiah Weeden-Wright
Based on:		Brian Traughber's js Google Feeds pull
Date Updated:   07/08/11

*/

// Global Vars
var er_widget_data = []; 	// Date from the widget, saved from the HTML
var er_feed_results = [];	// Actual results returned from querying the feeds
var er_feeds = [];			// List of actual URLs to query and status
var total_er_feeds = 0;
var er_feeds_processed = 0;
var er_use_cufon = false;
var er_max_feed_attempts = 5;
var er_feed_attempt_interval = 2000;

// Initialize google feeds for AJAX query of ER Feeds
google.load("feeds", "1");

// On Page Load, get the feed
jQuery(function(){

	// vars
	var er_feed_names = [];	// Unique list of feed names from the widget data

	// For each widget on the page, pull the vars
	jQuery(".ehc-er-wait").each(function() {
		
		// set up variables from the widget; get them from the data elements on the div
		var widget_data = {
			"current_widget"	: this,
			"feed_titles"		: jQuery(this).attr('data-map_feed_titles'),
			"facilities"		: jQuery(this).attr('data-map_facilities'),
			"type"				: jQuery(this).attr('data-map_type'),
			"min_format"		: jQuery(this).attr('data-map_min_format'),
			"include_hours"		: jQuery(this).attr('data-map_include_hours'),
			"use_cufon"			: jQuery(this).attr('data-map_use_cufon'),
			"pub_date_format"	: jQuery(this).attr('data-map_pub_date_format')
		};

		// Save all the required feeds to a list removing duplicates
		if(widget_data.feed_titles.indexOf(",") != -1) {
			jQuery(widget_data.feed_titles.split(",")).each(function() {
				var found = false;
				var facility_title = jQuery.trim(this);
				// Look up feeds from feed titles
				for(var i = 0; i < er_feed_names.length; i++) {
					// If it already is in the list, its a dup, ignore it
					if(facility_title == er_feed_names[i]) {
						found = true;
						break;
					}
				}
				if(!found) {
					er_feed_names.push(facility_title);
				}
			});
		} else {
			// Only a single record, check for dups
			var found = false;
			// Look up feeds from feed titles
			for(var i = 0; i < er_feed_names.length; i++) {
				// If it already is in the list, its a dup, ignore it
				if(widget_data.feed_titles == er_feed_names[i]) {
					found = true;
					break;
				}
			}
			if(!found) {
				er_feed_names.push(widget_data.feed_titles);
			}
		}

		// Only setup the drop down functionality if dropdown is selected
		// ONLY 1 DROPDOWN per page will function correctly
		if(widget_data.facilities.split(",").length > 2) {
			jQuery('.ehc-er-disclaimer').hide();
			jQuery('.ehc-er-facility-select').change(function() {
				if(jQuery(this).val() == 'Select Facility') {
					jQuery('.ehc-er-facility-option[rel]').hide();
					jQuery('.ehc-er-disclaimer').hide();
					jQuery('.ehc-er-facility-dropdown-message').show();
				} else {
					jQuery('.ehc-er-facility-option[rel]').hide();
					jQuery('li[rel="ER Time '+jQuery(this).val() + '"]').show();
					jQuery('.ehc-er-facility-dropdown-message').hide();
					jQuery('.ehc-er-disclaimer').show();
				}
			});
		}

		// Cache the widget data
		er_widget_data.push(widget_data);
	});

	// Look up the actual feed URL and other info in the global variable ER_WAIT_TIME_FEEDS
	for (var i = 0; i < er_feed_names.length; i ++) {
		for (var j = 0; j < ER_WAIT_TIME_FEEDS.length; j++) {
			if (er_feed_names[i] == ER_WAIT_TIME_FEEDS[j].feed_name) {
				var er_feed_map = {
					"feed_info"	: ER_WAIT_TIME_FEEDS[j],
					"status"	: "setup"
				};
				er_feeds.push(er_feed_map);
				total_er_feeds = total_er_feeds + 1;
				break;
			}
		}
	}

	// Go through each feed and cache the feed data
	jQuery(er_feeds).each(function() {
		getFeed(this);
	});
	
	// Sleep in an iterative loop and use a for loop to check if all feeds were successful	
	checkFeedsForSuccess(0);
});

// Recursive function - need to make sure it stops itself after max feed attempts is reached
function checkFeedsForSuccess(attempts) {
	// Hide message, show loader
	jQuery('.ehc-er-loading .ehc-er-load-message').hide();
	jQuery('.ehc-er-loading img').show();

	// Check feeds
	var done_searching = true;
	jQuery(er_feeds).each(function() {
		if(this.status != "success") {
			getFeed(this);
			done_searching = false;
		}
	});

	attempts = attempts + 1;
	if (attempts < er_max_feed_attempts && !done_searching) {
		t=setTimeout("checkFeedsForSuccess("+attempts+")",er_feed_attempt_interval);
	} else {
		// Max tries, hide the loading bar and present message (retry calls this method again)
		jQuery('.ehc-er-loading img').hide();
		jQuery('.ehc-er-loading .ehc-er-load-message').show()
				.html("Could not retrieve ER feeds. <a href='javascript:checkFeedsForSuccess(0)'>Retry</a>");
	}
}

// Retrieves the feed and sends the XML data to processFeed
function getFeed(er_feed_map) {
  	// Setup random extra on URL to avoid google caching URL
	var non_cache = "?"+Math.random();
    var feed_url = er_feed_map.feed_info.feed_url + non_cache;

	// Get the feed from Google
	var feed = new google.feeds.Feed(feed_url);
	feed.setResultFormat(google.feeds.Feed.XML_FORMAT);
	// How many child elements to grab (default is 4, most ER Wait times feeds are larger than that though)
	feed.setNumEntries(100);
	
	// Call the function process feed with the results
	feed.load(saveFeeds);

	// Handle the loaded feed
	function saveFeeds(result) {
		success = true;
		if (!result.error) {

			var items = result.xmlDocument.getElementsByTagName('item');
			if (items.length > 0) {
				jQuery(items).each(function() {
					// Add all variables from feed into JS array
					var feed_result = [];
					er_feed_map.status = "success";
					feed_result.feed_info = er_feed_map.feed_info;
					feed_result.facility = this.getElementsByTagName("title")[0].firstChild.nodeValue;
					feed_result.pub_date = this.getElementsByTagName("pubDate")[0].firstChild.nodeValue;
					feed_result.er_time = this.getElementsByTagName("description")[0].firstChild.nodeValue;
					feed_result.pub_date_formatted = false;
					er_feed_results.push(feed_result);
				});
				er_feeds_processed = er_feeds_processed + 1;
				setupFacilitiesForWidgets();
			} else {
				er_feed_map.status = "fail";
			}
		} else {
			er_feed_map.status = "fail";
		}
	}
}

function setupFacilitiesForWidgets() {
	// Only run this function once all facilities are returned
	if(er_feeds_processed == total_er_feeds) {

		// For each widget, we'll need to find the facilities for those widgets in the cached feeds
		jQuery(er_widget_data).each(function() {
			var current_widget_data = this;

			// For each facility specified in the widget
			var results = [];
			jQuery(current_widget_data.facilities.split(",")).each(function() {
				var er_facility = this;
				er_facility = jQuery.trim(er_facility);

				// For each er_feed_result
				for(i = 0; i < er_feed_results.length; i++) {
					// Find a match for the widget's specified facility in the feed results
					if(er_feed_results[i].facility == er_facility) {

						// Add 00: to beginning and strip off Mins
						var time = er_feed_results[i].er_time;
						if(time.indexOf("Coming Soon") == -1) {
							time = time.replace("Mins","").replace(" ","");
							if(current_widget_data.include_hours == "true") {
								// Add hours
								if (time.length == 1) {
									time = "0" + time;
								}
								time = "00:" + time;
							}
						} else {
							time = "Coming Soon";
						}
						er_feed_results[i].er_time = time;

						// Setup the date based on the publication date set
						var already_formatted = er_feed_results[i].pub_date_formatted;
						if (already_formatted != true) {
							var pub_date = er_feed_results[i].pub_date;
							pub_date = pub_date.replace(/ -0700/,""); //.replace(/AM/," am").replace(/PM/," pm");
						
							// Check for and save any timezone info
							// - all feeds are standard format with last 3 characters as timezone
							var timezone = pub_date.substring(pub_date.length - 3, pub_date.length);
							pub_date = pub_date.substring(0,pub_date.length - 4); // includes removing the space

							// Date formats are different for different feeds
							var old_date_format = er_feed_results[i].feed_info.date_format;
					        var new_date_format = current_widget_data.pub_date_format;
							pub_date = formatDate(new Date(getDateFromFormat(pub_date,old_date_format)),new_date_format);

							// Add timezone back to date
							pub_date = pub_date + " " + timezone;
							er_feed_results[i].pub_date = pub_date;
							er_feed_results[i].pub_date_formatted = true;
						}
						results.push(er_feed_results[i]);
						break; // Need to use 'for loop' so can break before end if match if found (can't use jQuery.each)
					}
				}				
			});
				
			// Print results in the er-wait div
			if(current_widget_data.facilities.split(",").length > 2
				&& current_widget_data.type != 'list') {
				var options = jQuery(".ehc-er-facility-select");
				jQuery(results).each(function() {
					// Setup the drop down
					options.append(jQuery("<option />").val(this.facility).text(this.facility));

					// Setup the hidden divs to be revealed by drop down selects
					var feed_html = '<li class="ehc-er-facility-option" rel="ER Time '+this.facility+'" style="display:none">'
									+ '<span class="ehc-er-pubdate">'
									+ this.pub_date
									+ '</span><span class="ehc-er-time"><span class="ehc-er-digits">'
									+ this.er_time
									+ '</span><span class="ehc-er-mins">' 
									+ current_widget_data.min_format
									+ '</span></span></li>';
					jQuery(current_widget_data.current_widget).find(".ehc-er-facility-times").append(feed_html);
					jQuery(current_widget_data.current_widget).after().css("clear","both");
				});
			} else {
				if(current_widget_data.facilities.split(",").length == 2
					&& current_widget_data.type != "list") {
					jQuery(current_widget_data.current_widget).parent().css("width","478px");
				}
				jQuery(results).each(function() {
					var feed_html = '<li><span class="ehc-er-facility-title">'
									+ this.facility
									+ '</span><span class="ehc-er-pubdate">'
									+ this.pub_date
									+ '</span><span class="ehc-er-time"><span class="ehc-er-digits">'
									+ this.er_time
									+ '</span><span class="ehc-er-mins">' 
									+ current_widget_data.min_format
									+ '</span></span></li>';
					jQuery(current_widget_data.current_widget).find(".ehc-er-facility-times").append(feed_html);
					jQuery(current_widget_data.current_widget).after().css("clear","both");
				});
			}

			// Setup cufon if true
			if(current_widget_data.use_cufon == "true" || er_use_cufon) {
				// CUFON only
				Cufon.replace('.ehc-er-facility-times li .ehc-er-digits');
				// Use cufon for all widgets as at least 1 on the page is using it (don't want to include more than once)
				er_use_cufon = true;
				// Set padding on div less to compensate for cufon
				jQuery(".ehc-er-facility-times-one-facility li .ehc-er-time").css("padding","6px 10px 1px 0px");
			}		
		});
		
		// Hide the loading bar
		jQuery('.ehc-er-loading').hide();
	}
}
