function onLoginFormSubmit () {
	try {
		var user = $('inp_username').value;
		var pass = $('inp_password').value;
		if (!user) {
			$('inp_username').focus();
			showErrorForInput('inp_username', "You can't log in if you don't give us your username");
			return false;
		}
		if (user.length < 3 || user.length > 20) {
			$('inp_username').focus();
			showErrorForInput('inp_username', 'The username is not valid. Please check and try again.<br />It should be between 3 and 20 charachers long!');
			return false;
		}
		if (!pass) {
			$('inp_password').focus();
			showErrorForInput('inp_password', "You can't log in if you don't give us your password");
			return false;
		}
		if (pass.length < 3) {
			$('inp_password').focus();
			showErrorForInput('inp_password', "This password is not valid. Please check and try again.<br />It should be at least 3 characters long");
			return false;
		}

		$('checking_account').style.display = 'block';
		var d = new Date();
		var t = d.getTimezoneOffset() / 60;
		var params = $H({user: user, pass:pass, t: t, keep: $('inp_remember').checked ? 'true' : 'false'});
		new Ajax.Request ('/check_login.php', {
			method: 'post',
			onSuccess: onLoginResponse,
			onFailure: onLoginError,
			parameters: params.toQueryString()
		});
	} catch (e) {}
	return false;
}
function onLoginResponse (ajaxRequest) {
	$('checking_account').style.display = 'none';
	var t = ajaxRequest.responseText;
	var jsonObj = null;
	try {
		eval ("jsonObj = " + t);
	} catch (e) { }
	if (jsonObj != null) {
		if (jsonObj.response = 'OK' && jsonObj.errorid == 0) {
			$('checking_account').style.display = 'block';
			document.location = '/download-youtube-videos-hq-hd.php';
			return;
		} else {
			//wrong account
			if (jsonObj.errorid == 2) {
				$('inp_username').focus();
				showErrorForInput('inp_username', "Username or password are wrong! Or both of them!");
			} if (jsonObj.errorid == 1) {
				$('inp_username').focus();
				showErrorForInput('inp_username', "Both username and password needed!");
			}
			if (jsonObj.errorid == 3) {
				if (confirm("Ok, account is correct but not activated. Didn't you receive the email? Even in the spam/junk box?\n" +
					"If not - do you want us to resend it to the email address " + jsonObj.email + "?")) {
					resendActivationEmail ($('login_user').value);
				}
			}
		}
	} else
		alert ("There was a problem checking your credentials on the server\nPlease, try again later");
}
function onLoginError () {
	alert ("There was a problem checking your credentials on the server.\n" +
		"Please, check your internet connection and try again!" );
}

function resendActivationEmail (user) {
	$('checking_account').style.display = 'block';
	var params = $H({user: user, resend_conf: 'y'});
	new Ajax.Request ('/register_account.php', {
		method:'post',
		onSuccess: resendActivationEmail_handler,
		parameters: params.toQueryString()
	});
}
function resendActivationEmail_handler (ajaxResponse) {
	$('checking_account').style.display = 'none';
	var t = ajaxResponse.responseText;
	var jsonObj = null;
	try {
		eval ("jsonObj = " + t);
	} catch (e) {};
	if (jsonObj != null) {
		if (jsonObj.error == 0) {
			alert ('New confirmation email has been sent to ' + jsonObj.email);
		} else
			alert (jsonObj.response);
	} else
		alert ('Error sending the email')
}
function initForms () {
	var inps = $('login_box').getElementsByTagName('input');
	for (var i = 0; i < inps.length; i ++)
		if (inps[i].type == 'text' || inps[i].type == 'password')  {
			inps[i].onkeydown = onInputChange;
			inps[i].onchange = onInputChange;
		}
	$('inp_username').focus();

	var dl = new String(document.location.href);
	var hash = dl.replace(/.*#/, '');
	if (hash) {
		switch (hash) {
			case 'forgotten-password':
				showFP(); break;
			case 'forgotten-username':
				showFU(); break;
		}
	}
}
Event.observe(window, 'load', initForms);

function showLF () {
	$('login_content').style.display = 'block';
	$('fp_content').style.display = 'none';
	$('fu_content').style.display = 'none';
	$('inp_username').focus();
	hideInputError();
}
function showFP () {
	$('login_content').style.display = 'none';
	$('fp_content').style.display = 'block';
	$('fu_content').style.display = 'none';
	$('inp_fp_email').focus();
	hideInputError();
}

function showFU () {
	$('login_content').style.display = 'none';
	$('fp_content').style.display = 'none';
	$('fu_content').style.display = 'block';
	$('inp_fu_email').focus();
	hideInputError();
}

function onForgottenPasswordSubmit () {
	try {
		var email = $('inp_fp_email').value;
		if (!email) {
			$('inp_fp_email').focus();
			showErrorForInput('inp_fp_email', 'Please, enter your email address');
			return false;
		}
		if (!email_filter.test(email)) {
			$('inp_fp_email').focus();
			showErrorForInput('inp_fp_email', 'Please, enter a valid email address');
			return false;
		}
		new Ajax.Request ('/forgotten_password.php', {
			method: 'post',
			onSuccess: onForgottenPasswordSuccess,
			onFailure: onForgottenPasswordError,
			parameters: $H( {email: email} ).toQueryString()
		});
		$('checking_account').style.display = 'block';
	} catch (e) {}
	return false;
}

function onForgottenPasswordSuccess (ajaxRequest) {
	$('checking_account').style.display = 'none';
	var t = ajaxRequest.responseText;
	var jsonObj;
	try {
		eval ('jsonObj = ' + t);
	} catch (e) { }
	if (!jsonObj) {
		alert ("There was an error checking the email.\nPlease, try again later!");
		return;
	}
	if (jsonObj.errorid) {
		$('inp_fp_email').focus();
		showErrorForInput('inp_fp_email', "The provided email is not registered!<br />Please, check it and try again");
	} else {
		alert ('An email was sent to the provided address with a new password!');
		showLF();
	}
}

function onForgottenPasswordError () {
	$('checking_account').style.display = 'none';
	alert ("There was an error checking the email.\nPlease, check your internet connection and try again!");
}
// ---
function onForgottenUsernameSubmit () {
	try {
		var email = $('inp_fu_email').value;
		if (!email) {
			$('inp_fu_email').focus();
			showErrorForInput('inp_fu_email', 'Please, enter your email address');
			return false;
		}
		if (!email_filter.test(email)) {
			$('inp_fu_email').focus();
			showErrorForInput('inp_fu_email', 'Please, enter a valid email address');
			return false;
		}
		new Ajax.Request ('/forgotten_username.php', {
			method: 'post',
			onSuccess: onForgottenUsernameSuccess,
			onFailure: onForgottenUsernameError,
			parameters: $H( {email: email} ).toQueryString()
		});
		$('checking_account').style.display = 'block';
	} catch (e) {}
	return false;
}
function onForgottenUsernameSuccess (ajaxRequest) {
	$('checking_account').style.display = 'none';
	var t = ajaxRequest.responseText;
	var jsonObj;
	try {
		eval ('jsonObj = ' + t);
	} catch (e) { }
	if (!jsonObj) {
		alert ("There was an error checking the email.\nPlease, try again later!");
		return;
	}
	if (jsonObj.errorid) {
		$('inp_fu_email').focus();
		showErrorForInput('inp_fu_email', "The provided email is not registered!<br />Please, check it and try again");
	} else {
		alert ('An email was sent to the provided address with your username!');
		showLF();
	}
}
function onForgottenUsernameError () {
	$('checking_account').style.display = 'none';
	alert ("There was an error checking the email.\nPlease, check your internet connection and try again!");
}

// ---
function onInputChange (inp) {
	if (!window.lastErrorInputShown) return;
	if (arguments.length < 1 || !inp.tagName) {
		var event = (arguments.length > 0 ? arguments[0] : window.event);
		inp = event.target || event.srcElement;
	}
	if (inp.id == window.lastErrorInputShown || inp.id == window.lastErrorInputShown.id)
		hideInputError();
}

/*
 * Banners scripts
 */

var FPBanners = {
	animationDelay: 5000,
	animationStepDuration: 40,
	animationDuration: 800,
	
	mouseOutDelay: 1000,
	
	initialize: function () {
		this.container = $('banners');
		//Event.observe(this.container, 'mouseover', this.mouseOverBanner.bind(this));
		//Event.observe(this.container, 'mouseout', this.mouseOutBanner.bind(this));
		
		this.bannersLinks = $('pagers').getElementsByTagName('a');
		this.bannersCount = this.bannersLinks.length;
		this.banners = [];
		
		for (var i = 1; i <= this.bannersCount; i ++) {
			this.banners.push($('banner_b' + i));
			this.bannersLinks[i-1].onclick = this.onLinkClick.bind(this, i-1);
		}
		
		this.currentBanner = 0;
		
		this._timerTick = this.timerTick.bind(this);
		this._bannerAnimationTimerTick = this.bannerAnimationTimerTick.bind(this);
		this.totalAnimationSteps = this.animationDuration / this.animationStepDuration;
		
		this.startTimer();
	},
	
	onLinkClick: function (index) {
		this.showBanner(index, false);
		
	},
	
	mouseOverBanner: function () {
		this.cancelTimer();
		if (this._mouseOutBannerTimer) {
			clearTimeout(this._mouseOutBannerTimer);
			this._mouseOutBannerTimer = 0;
		}
	},
	mouseOutBanner: function () {
		if (!this._mouseOutBannerTimerTick)
			this._mouseOutBannerTimerTick = this.mouseOutBannerTimerTick.bind(this);
		if (!this._mouseOutBannerTimer)
			this._mouseOutBannerTimer = setTimeout(this._mouseOutBannerTimerTick, this.mouseOutDelay);
	},
	mouseOutBannerTimerTick: function () {
		this.startTimer(-this.mouseOutDelay);
	},
	
	showBanner: function (index, animated) {
		if (this.bannerAnimationTimer) {
			this.bannerAnimationOver();
		}
		this.cancelTimer();
		if (animated) {
			this.animatingToBanner = index;
			this.banners[this.animatingToBanner].style.display = 'block';
			Element.setOpacity(this.banners[this.animatingToBanner], 0);
			this.currentAnimationStep = 1;
			this.bannerAnimationTimer = setInterval(this._bannerAnimationTimerTick, this.animationStepDuration);
		} else {
			this.bannersLinks[this.currentBanner].className = '';
			Element.setOpacity(this.banners[this.currentBanner], 0);
			this.currentBanner = index;
			this.bannersLinks[this.currentBanner].className = 'current';
			this.banners[this.currentBanner].style.display = 'block';
			Element.setOpacity(this.banners[this.currentBanner], 1);
			//this.startTimer();
		}
	},
	
	bannerAnimationTimerTick: function () {
		Element.setOpacity(this.banners[this.currentBanner], 1.0 - this.currentAnimationStep / this.totalAnimationSteps);
		Element.setOpacity(this.banners[this.animatingToBanner], this.currentAnimationStep / this.totalAnimationSteps);
		this.currentAnimationStep ++;
		if (this.currentAnimationStep > this.totalAnimationSteps)
			this.bannerAnimationOver();
	},
	bannerAnimationOver: function () {
		this.bannersLinks[this.currentBanner].className = '';
		clearInterval(this.bannerAnimationTimer);
		this.bannerAnimationTimer = 0;
		this.currentBanner = this.animatingToBanner;
		this.bannersLinks[this.currentBanner].className = 'current';
		this.startTimer();
	},
	
	cancelTimer: function () {
		if (this.mainTimer)
			clearTimeout(this.mainTimer);
		this.mainTimer = 0;
	},
	startTimer: function (correction) {
		if (arguments.length == 0) correction = 0;
		if (this.mainTimer) return;
		this.mainTimer = setTimeout(this._timerTick, this.animationDelay + correction);
	},
	timerTick: function () {
		this.mainTimer = 0;
		var b = this.currentBanner + 1;
		if (b >= this.bannersCount) b = 0;
		this.showBanner(b, true);
	}
}
Event.observe(window, 'load', FPBanners.initialize.bind(FPBanners));

Element.setOpacity = function(element, value) {
    if (Prototype.Browser.IE)
    	element.style.filter = 'alpha(opacity=' + (value * 100) + ')';
    element.style.opacity = value;
};
