/*
 * Webisoder
 * Copyright (C) 2006-2010 Stefan Ott. All rights reserved.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

function editProfile()
{
	showMailForm();
	showDaysBackForm();
	showDateOffsetForm();
	showProviderForm();
	showNewsForm();

	$('editProfile').hide();
	$('saveProfile').show();
}

function showProfile()
{
	$('mailForm').hide();
	$('daysBackForm').hide();
	$('dateOffsetForm').hide();
	$('providerForm').hide();
	$('saveProfile').hide();

	$('mailText').show();
	$('providerName').show();
	$('daysBackText').show();
	$('dateOffsetText').show();
	$('editProfile').show();

	$('siteNewsBox').disable();
}

function submitProfile()
{
	var data = $H({
		'mail': 	$F($('mailInput')),
		'days': 	$F($('daysBack')),
		'offset':	$F($('dateOffset')),
		'provider':	$F($('linkProvider')),
		'siteNews':	$('siteNewsBox').checked
	});

	new Ajax.Request('profile',
	{
		method: 'post',
		postBody: data.toJSON(),
		on200: function(transport)
		{
			var response = transport.responseText;
			var data = response.evalJSON();

			$('mailAddress').update(data.mail);
			$('daysBackNum').update(data.days);
			$('dateOffsetNum').update(data.offset);
			$('providerName').update(data.provider);
			showProfile();
		},
		on500: function(transport)
		{

			alert('Something went terribly, terribly wrong');
		}
	});
}

function markNewsRead(id)
{
	var time = new Date().getTime();

	new Ajax.Request(SITE_BASE_URL + 'news/' + id + '/mark?ms=' + time,
	{
		method: 'get',
		onSuccess: function(transport)
		{
			$('news').hide();
		},
		onFailure: function(transport) {
			var response = transport.responseText;

			if (response)
				alert(response);
			else
				alert('Something bad happened');
		}
	});
}

function recoverPassword()
{
	var user = $F($('user'));
	if (user.empty())
	{
		$('userNameWarning').hide();
		$('userNameEmptyWarning').show();
	}
	else
	{
		$('userNameWarning').hide()
		$('userNameEmptyWarning').hide();

		var data = $H({'user' : user });

		new Ajax.Request(SITE_BASE_URL + 'recover/password',
		{
			method: 'post',
			postBody: data.toJSON(),
			on202: function(transport)
			{
				$('recovery').update('An e-mail message with a link to change your password has been sent to the e-mail address associated with the user "' + user + '".');
			},
			on400: function(transport)
			{

				alert(transport.responseText);
			},
			on404: function(transport)
			{
				alert("This user doesn't exist");
			}
		});
	}
}

function setNewPassword()
{
	$('noMatchWarning').hide();
	$('emptyWarning').hide();

	var password = $F($('password'));

	if (password != $F($('passvrfy')))
	{
		$('noMatchWarning').show();
		return false;
	}
	if (password.empty())
	{
		$('emptyWarning').show();
		return false;
	}

	var data = $H({
		'user'	: $F($('user')),
		'pass'	: $F($('password')),
		'token'	: $F($('token'))
	});

	new Ajax.Request(SITE_BASE_URL + 'recover/password',
	{
		method: 'post',
		postBody: data.toJSON(),
		on204: function(transport)
		{
			$('recovery').update('Your password has successfully been updated.');
		},
		on400: function(transport)
		{

			alert(transport.responseText);
		},
		on404: function(transport)
		{
			alert("This user doesn't exist");
		}
	});
}

function recoverUserName()
{
	var mail = $F($('mail'));
	if (mail.empty())
	{
		$('mailWarning').show();
		return false;
	}

	$('mailWarning').hide();
	var data = $H({'mail' : mail});

	new Ajax.Request(SITE_BASE_URL + 'recover/username',
	{
		method: 'post',
		postBody: data.toJSON(),
		on202: function(transport)
		{
			$('recovery').update('An e-mail message with your user name has been sent to ' + mail + '.');
		},
		on400: function(transport)
		{

			alert(transport.responseText);
		},
		on404: function(transport)
		{
			alert('There is no user with that e-mail address');
		}
	});
}

function validateLoginForm()
{
	var name = $F($('name'));
	var password = $F($('password'));

	if (name.empty() || password.empty())
	{
		$('loginFormWarning').show();
		return false;
	} else {
		$('loginFormWarning').hide();
		return true;
	}
}

function verifySignupForm()
{
	var element;
	var out;
	var ok = true;

	out = $('warnName');
	regexp = /^[a-zA-Z0-9][-a-zA-Z0-9_]*[^-_]$/;

	if (!regexp.exec($F($('name'))))
	{
		out.update('Please enter a <a href="faq#acc-regexp">valid name</a>');
		ok = false;
	} else {
		out.update();
	}

	out = $('warnMail');

	if ($F($('mail')).empty())
	{
		out.update('Please enter an e-mail address');
		ok = false;
	} else {
		out.update();
	}

	out = $('warnCaptcha');

	if ($F($('captcha')).empty())
	{
		out.update('Please copy the security code from the image');
		ok = false;
	} else {
		out.update();
	}

	password = $F($('password'));
	out = $('warnPassword');

	if (password.empty())
	{
		out.update('Please enter a password');
		ok = false;
	}
	else if (password != $F($('passwordAgain')))
	{
		out.update('The passwords do not match');
		ok = false;
	} else {
		out.update();
	}

	return ok;
}

function showDaysBackForm()
{
	$('daysBackText').hide();
	$('daysBackForm').show();
}

function showDateOffsetForm()
{
	$('dateOffsetText').hide();
	$('dateOffsetForm').show();
}

function showProviderForm()
{
	$('providerName').hide();
	$('providerForm').show();
}

function showNewsForm()
{
	$('siteNewsBox').enable();
}

function showMailForm()
{
	$('mailText').hide();
	$('mailForm').show();
}

function showPasswordForm()
{
	$('passwordText').hide();
	$('passwordForm').show();
}

function hidePasswordForm()
{
	$('passwordForm').hide();
	$('passwordMessageContainer').hide();
	$('passwordText').show();
	$('passwarn').update();
}

function submitPasswordForm()
{
	var password = $F($('password'));
	var passvrfy = $F($('passvrfy'));
	var warnspan = $('passwarn');

	if (password.empty())
	{
		warnspan.update('It seems you forgot to type a password');
	}
	else if (password != passvrfy)
	{
		warnspan.update('The passwords do not match');
	}
	else
	{
		warnspan.update();

		var data = $H({'password': password});

		new Ajax.Request('profile',
		{
			method: 'post',
			postBody: data.toJSON(),
			on204: function(transport)
			{
				$('passwordMessageContainer').show();
				$('passwordMessage').update(
					'Password sucessfully changed');
				$('passwordForm').hide();
			},
			on500: function(transport)
			{
				alert('There was an error changing your password');
			}
		});
	}
}

function showShowList()
{
	$('addShow').show();
	$('addShowLink').hide();
}

function addShow(showID)
{
	var data = $H({'showID': showID});

	new Ajax.Request('addshow',
	{
		method: 'post',
		postBody: data.toJSON(),
		on204: function(transport)
		{
			$('noShows').hide();

			var li = document.createElement('li');
			Element.extend(li);

			li.update($('addShow' + showID).innerHTML);
			li.id = 'show' + showID;
			$('addShow' + showID).hide();

			var a = li.select('a');
			a[0].onclick = function onclick(event) {
				javascript:removeShow(showID);
				return false;
			}

			var img = a[0].childNodes[0];
			img.src = img.src.replace('add', 'remove');

			var div = $('selectedShowList');
			var ul = div.firstDescendant();
			ul.appendChild(li);
		},
		on400: function(transport)
		{
			var message = transport.responseText;
			alert(message);
		},
		on401: function(transport)
		{
			alert('Unauthorized.');
		}
	});
}

function removeShow(showID)
{
	var data = $H({'showID': showID});

	new Ajax.Request('removeshow',
	{
		method: 'post',
		postBody: data.toJSON(),
		on204: function(transport)
		{
			$('show' + showID).remove();
			$('addShow' + showID).show();
			var div = $('selectedShowList');
			var ul = div.firstDescendant();

			if (ul.select('li').length < 2)
				$('noShows').show();
		},
		on400: function(transport)
		{
			alert('An error occurred, sorry.');
		},
		on401: function(transport)
		{
			alert('Unauthorized.');
		}
	});
}

function hideShowList()
{
	$('addShow').hide();
	$('addShowLink').show();
}

function clearSearch()
{
	var search = $('search');

	if ($F(search) == 'search')
	{
		search.clear();
		search.className = 'active';
	}
}

function resetSearch()
{
	var search = $('search');

	if ($F(search).empty())
	{
		search.value = 'search';
		search.className = 'inactive';
	}
}

function searchKeyEvent(event)
{
	if (event.keyCode == 27)
	{
		var search = $('search');
		search.clear();
		refineSearch();
		resetSearch();
		search.blur();
	}
	else
	{
		refineSearch();
	}
}

function refineSearch()
{
	var items = $('shows');
	var regex = new RegExp($F($('search')), "i");

	var shows = items.select('li');

	for (i=0; i < shows.length; i++)
	{
		var show = shows[i];

		if (show.firstChild.id.match(regex))
			$(show.id).show();
		else
			$(show.id).hide();
	}
}
