// Add another field for entering a new feed
function moreFeeds() {
	for (c = 0; c < 3; c++) {
		var newFeed = document.createElement('p');
		newFeed.innerHTML = '<label for="url_' + feedNum + '">Feed URL #' + feedNum + '</label><br />';
		newFeed.innerHTML += '<input type="hidden" id = "status_' + feedNum + '" name="status_' + feedNum + '" value="true" />';
		newFeed.innerHTML += '<input type="text" value="http://" class="url" name="urls[]" id="url_' + feedNum + '" maxlength="255" onblur="checkFeed(' + feedNum + ', false);" />';
		newFeed.innerHTML += spinnerImg(feedNum, 0);
		$('feeds').appendChild(newFeed);
		feedNum++;
	}
}

// Add feeds to the OPML import page
function moreOPMLFeeds() {
	for (c = 0; c < 3; c++) {
		var newFeed = document.createElement('p');
		newFeed.innerHTML += '<input type="hidden" id = "status_' + feedNum + '" name="status_' + feedNum + '" value="true" />';
		newFeed.innerHTML += '<input type="text" value="http://" class="opml_url" name="urls[]" id="url_' + feedNum + '" maxlength="255" onblur="checkFeed(' + feedNum + ', false);" />';
		newFeed.innerHTML += spinnerImg(feedNum, 0);
		$('feeds').appendChild(newFeed);
		feedNum++;
	}
}

// Switch the interface to show the OPML Import form
function importOpml() {
	Element.hide('feeds', 'more_feeds');
	Element.show('opml');
	Element.update('opml_toggle', '<a href="javascript:feedsList();">Enter List of Feeds...</a>');
	$('type').value = 'opml';
}

// Switch interface to the list of feeds
function feedsList() {
	Element.show('feeds', 'more_feeds');
	Element.hide('opml');
	Element.update('opml_toggle', '<a href="javascript:importOpml();">Import OPML List of Feeds...</a>');
	$('type').value = 'feeds';
}

// Check that a feed URL resolves
function checkFeed(num, force) {
	// This is what we're working on
	thisFeedNum = num;
	
	// Set status to "doing stuff"
	$('spinner_' + thisFeedNum).src = 'media/spinner.gif';
	
	// Get the URL that we're checking
	url = $F('url_' + thisFeedNum);

	// Looks like a URL?	
	if (url != 'http://' && url != '') {
		// Change "feed:" requests to "http:" and add the http if it was left off
		url = url.replace(/feed:/i, 'http:');
		if (url.substring(0, 7) != 'http://') {
			url = 'http://' + url;
		}
		url = escape(url); // Always encode the URL
		if (force) {
			url = url + '?fvforce=true';
		}
		new Ajax.Request('fvcore/api/feeds/' + url, {method:'get', asynchronous:true, onSuccess:handleFeedSuccess, onFailure:handleFeedFailed});
	}
	else {
		// Reset indicators
		$('spinner_' + thisFeedNum).src  = 'media/spinner_ph.gif';
		$('status_' + thisFeedNum).value = 'true';
		checkForBadFeeds();
	}
}

// Deal with the response from the AJAX check
function handleFeedSuccess(t) {
	if (t.responseText == 'FALSE') {
		handleFeedFailed(t);
	}
	else {
		if (t.responseText.match(/http:\/\/([\w-]+\.?)+(\/[\w\.\/\?%&=@\$-]*)?/)) {
			$('spinner_' + thisFeedNum).src  = 'media/confirmed.gif';
			$('status_' + thisFeedNum).value = 'true';
			$('url_' + thisFeedNum).value    = t.responseText;
			checkForBadFeeds();
		}
		else {
			handleFeedFailed(t);
		}
	}
}

function handleFeedFailed(t) {
	// $('spinner_' + thisFeedNum).src   = 'media/failed.gif';
	$('status_' + thisFeedNum).value  = 'false';
	Element.update('spinner_cont_' + thisFeedNum, '<a href="javascript:checkFeed(' + thisFeedNum + ', true);" onfocus="blur();" title="Click to check URL again">' + spinnerImg(thisFeedNum, -1) + '</a>');
	updateMsg('feeds');
}

// Get the code for a spinner image
function spinnerImg(num, state) {
	if (state > 0) {
		state = 'media/confirmed.gif';
	}
	else if (state < 0) {
		state = 'media/failed.gif';
	}
	else {
		state = 'media/spinner_ph.gif';
	}
	return '<span id="spinner_cont_' + num + '"><img src="' + state + '" width="16" height="16" class="spinner" alt="" border="0" id="spinner_' + num + '" /></span>';
}

// Handle the submission (check AJAX failures etc)
function blend() {
	// Set up
	var bad_feeds = false;
	var bad_opml  = false;
	var feeds     = false;
	
	// Set status to "doing stuff"
	$('blend_spinner').src = 'media/spinner.gif';
	
	if ($F('type') == 'feeds') {
		// Check all status_ inputs to see if there are any "false" ones, if so - we'll warn
		// We'll also remove them from the list because we don't want to re-process them
		for (s = 1; s < feedNum; s++) {
			if ($('status_' + s) && $F('status_' + s) == 'false') {
				$('url_' + s).value = 'http://';
				bad_feeds = true;
			}
			else {
				if ($F('url_' + s) != 'http://' && $F('url_' + s) != '') {
					feeds = true;
				}
			}
		}
	}
	else {
		// If we're on the OPML 'tab' then something has to be filled in
		if ($('opml_file').value == '' && $F('opml_url') == '') {
			updateMsg('opml');
			$('blend_spinner').src = 'media/spinner_ph.gif';
			return false;
		}
		else {
			feeds = true;
		}
	}
	
	// Final check to make sure there was something to blend
	if (feeds || $F('push')) {
		// Disable some stuff to prevent the user messing with submissions
		return true;
	}
	else {
		updateMsg('something');
		$('blend_spinner').src = 'media/spinner_ph.gif';
		return false;
	}
}

function checkForBadFeeds() {
	for (s = 1; s < feedNum; s++) {
		if ($('status_' + s) && $F('status_' + s) == 'false') {
			updateMsg('feeds');
			return;
		}
	}
	updateMsg('clear');
}

function updateMsg(type) {
	if (type == 'something') {
		msg = 'I need at least one valid feed above to blend.';
	}
	else if (type == 'opml') {
		msg = 'I\'ll need either an OPML file on your computer or a URL to blend.';
	}
	else if (type == 'feeds') {
		msg = 'Feeds marked with a red dot above will NOT be included in your blend!';
	}
	else {
		msg = '';
	}
	Element.update('feed_warning', msg);
}

function showAllFeeds(shown, total) {
	Element.hide('show_all');
	for (f = shown; f < total; f++) {
		$('feed-' + f).className = 'show';
	}
}
