var domain = 'http://'+document.domain+'/';

function updateContent(nmup)
{
    if (document.location.href.indexOf('/rss') !== -1) {
        return;
    }

    window.runCheckURL();

    var sureg = new RegExp('^([^#]+)(write|writed|search|registration|adv|statistics|donate)(/?)$');
    if (sureg.test(document.location.href)) {
        arr = sureg.exec(document.location.href);
        window.showContentByMenuItem(arr[2]);
        return;
    }

    var reg = new RegExp('^'+domain+'#(author|keyword|user|favorites|quote)([0-9]+)(-quote)?([0-9]*)$');
    var qreg = new RegExp('^([^#]+)/(author|keyword|user|favorites|quote)/([0-9]+)/(#quote)?([0-9]*)$');

    if (reg.test(document.location.href)) {
        var arr = reg.exec(document.location.href);
        if (arr[3] && arr[4]) {
            var anc = '#quote'+arr[4];
        } else {
            var anc = '';
        }
        document.location.href = domain + arr[1]+'/'+arr[2]+'/' + anc;
        return;
    } else if (qreg.test(document.location.href)) {
        arr = qreg.exec(document.location.href);
        window.goToItem(arr[2], arr[3], false, arr[5]);
        return;
    }

    var qdreg = new RegExp('^'+domain+'#new([0-9]*)(-quote)?([0-9]*)$');
    var qdnreg = new RegExp('^'+domain+'new/([0-9]*)/?(#quote)?([0-9]*)$');

    if (qdreg.test(document.location.href)) {
        arr = qdreg.exec(document.location.href);
        if (arr[2] && arr[3]) {
            var danc = '#quote'+arr[3];
        } else {
            var danc = '';
        }
        document.location.href = domain + 'new/' + arr[1] + danc;
        return;
    } else if (qdnreg.test(document.location.href)) {
        arr = qdnreg.exec(document.location.href);
        window.getDaily(0, arr[3], arr[1]);
        return;
    }

    var bdreg = new RegExp('^'+domain+'#popular([0-9]*)(-quote)?([0-9]*)$');
    var bdnreg = new RegExp('^'+domain+'popular/([0-9]*)/?(#quote)?([0-9]*)$');

    if (bdreg.test(document.location.href)) {
        arr = bdreg.exec(document.location.href);
        if (arr[2] && arr[3]) {
            var danc = '#quote'+arr[3];
        } else {
            var danc = '';
        }
        document.location.href = domain + 'popular/' + arr[1] + danc;
        return;
    } else if (bdnreg.test(document.location.href)) {
        arr = bdnreg.exec(document.location.href);
        window.getBest(0, arr[3], arr[1]);
        return;
    }

    var rreg = new RegExp('^'+domain+'#random$');
    var rdreg = new RegExp('^'+domain+'random/?(#quote)?([0-9]*)$');

    if ((rreg.test(document.location.href))) {
        document.location.href = domain + 'random/';
    } else if (rdreg.test(document.location.href)) {
        window.getRandom();
        return;
    }

    var reg = new RegExp('^([^#]+)#(.*)$');
	if (!reg.test(document.location.href)) {
	    var rreg = new RegExp('^'+domain+'$');
	    if (rreg.test(document.location.href)) {
	        if (!nmup) {
	            document.location.href = domain + '#';
                showContentByMenuItem('');
                return;
	        } else {
	            $('load').style.display = 'none';
	            return;
	        }
        } else {
            window.notFound();
        }
		return;
    }

	$('load').style.display = 'block';
	$('content').innerHTML = '';

	JsHttpRequest.query(
		"/backend.php",
		{ "url": document.location.href },
		function(result) {
		    $('buttons').innerHTML = result['buttons'];
			$('content').innerHTML = result['content'];
            $('content').style.display = 'block';
            $('pult').innerHTML = result['pult'];
            if ($('smart')) $('smart').style.display = 'none';
			$('load').style.display = 'none';
		},
		false
	);
}

function showContentByMenuItem(menuitem)
{
    var breg = new RegExp('^'+domain+'([a-z]+)/');

    if (breg.test(document.location.href) && !menuitem) {
        document.location.href = domain;
        return false;
    }

    $('load').style.display = 'block';

    var reg = new RegExp('#'+menuitem+'$');

	if (!reg.test(document.location.href)) {
		if (menuitem)
			document.location.href = domain + '#' + menuitem;
		else
			document.location.href = domain + '#';
	}

    if ($('auth-form')) {
        $('auth-form').style.display = 'none';
    }

    window.clearPlayer();

	JsHttpRequest.query(
		"/backend.php",
		{ "go": menuitem },
		function(result) {
		    window.scroll(0, 0);
			$('buttons').innerHTML = result['buttons'];
			$('content').innerHTML = result['content'];
            $('content').style.display = 'block';
            $('pult').innerHTML = result['pult'];
            if ($('smart')) $('smart').style.display = 'none';
			$('load').style.display = 'none';
		},
		true
	);

    window.runCheckURL();

	return false;
}

var interval;

function validateWriteQuote()
{
	if (!$('quote').value || !trim($('quote').value)) {
		$('submit').disabled = true;
	} else {
		$('submit').disabled = false;
	}
}

var errortimeout;

function checkEnabledSelectToYear()
{
	if (!$('year').value) {
		$('year-century').disabled = true;
		$('ad-bc').disabled = true;
	} else {
		var reg = new RegExp('^([0-9IVXLCDM]+)$');
		if (!reg.test($('year').value)) {
            if (!errortimeout) {
                window.showErrorsDiv('Используйте арабские или римские цифры.');
			    errortimeout = window.setTimeout('hideErrorsDiv();', 4000);
            }
			$('year-century').disabled = true;
			$('ad-bc').disabled = true;
		} else {
			$('year-century').disabled = false;
			$('ad-bc').disabled = false;
		}
	}
}

function writeWords()
{
	window.clearInterval(interval);

	$('load').style.display = 'block';

	var quote = $('quote').value;
	var author = $('author').value;
	var source = $('source').value;
	var year = $('year').value;
	var year_century = $('year-century').value;
	var ad_bc = $('ad-bc').value;
	var keywords = $('keywords').value;

    $('quote').disabled = true;
	$('author').disabled = true;
	$('source').disabled = true;
	$('year').disabled = true;
	$('year-century').disabled = true;
	$('ad-bc').disabled = true;
	$('keywords').disabled = true;
	$('submit').disabled = true;

	JsHttpRequest.query(
		"/backend.php",
		{ "go": "write", "do": true, "quote": quote, "author": author, "source": source, "year": year, "year-century": year_century, "ad-bc": ad_bc, "keywords": keywords },
		function(result) {
			if (result['ok']) {
			    $('quote').value = '';
				$('author').value = '';
				$('source').value = '';
				$('year').value = '';
				$('year-century').value = '';
				$('ad-bc').value = '';
				$('keywords').value = '';
				$('quote').disabled = false;
				$('author').disabled = false;
				$('source').disabled = false;
				$('year').disabled = false;
				$('year-century').disabled = false;
				$('ad-bc').disabled = false;
				$('keywords').disabled = false;
				$('submit').disabled = true;
                $('message').innerHTML = result['message'];
				$('message').style.display = 'block';
				$('load').style.display = 'none';
			} else {
                $('load').style.display = 'none';
                window.showErrorsDiv("Ошибка в передаче XML-данных.");
			    window.setTimeout('hideErrorsDiv();', 4000);
			}
		},
		false
	);

    return false;
}

function validateRegistration()
{
	if (window.vRL() && window.vRP() && window.vRC() && window.vRE()) {
		$('submit').disabled = false;
	} else {
		$('submit').disabled = true;
	}
}

function vRL()
{
	if (!$('login').value) {
		$('login').className = 'fourtyseven font14 block';
		return false;
	} else if (!trim($('login').value)) {
		$('login').className = 'fourtyseven font14 incorrect block';
		return false;
	} else {
		$('login').className = 'fourtyseven font14 correct block';
		return true;
	}
}

function vRP()
{
	if (!$('password').value) {
		$('password').className = 'max font14';
		return false;
	} else if (!trim($('password').value)) {
		$('password').className = 'max font14 incorrect';
		return false;
	} else {
		$('password').className = 'max font14 correct';
		return true;
	}
}

function vRC()
{
	if (!$('confirm').value) {
		$('confirm').className = 'max font14';
		return false;
	} else if (!trim($('confirm').value)) {
		$('confirm').className = 'max font14 incorrect';
		return false;
	} else if ($('confirm').value != $('password').value) {
		$('confirm').className = 'max font14 incorrect';
		return false;
	} else {
		$('confirm').className = 'max font14 correct';
		return true;
	}
}

function vRE()
{
	if (!$('email').value) {
		$('email').className = 'fourtyseven font14 ';
		return false;
	} else if (!trim($('email').value)) {
		$('email').className = 'fourtyseven font14 incorrect';
		return false;
	} else if (!validateEmail($('email').value)) {
		$('email').className = 'fourtyseven font14 incorrect';
		return false;
	} else {
		$('email').className = 'fourtyseven font14 correct';
		return true;
	}
}

function doRegistration()
{
	$('load').style.display = 'block';

	var login = $('login').value;
	var password = $('password').value;
	var confirm = $('confirm').value;
	var email = $('email').value;

    $('login').disabled = true;
	$('password').disabled = true;
	$('confirm').disabled = true;
	$('email').disabled = true;
	$('submit').disabled = true;

	JsHttpRequest.query(
		"/backend.php",
		{ "go": "registration", "do": true, "login": login, "password": password, "confirm": confirm, "email": email},
		function(result) {
			if (result['ok']) {
			    $('auth-form').innerHTML = '';
                $('reset-form').innerHTML = '';
			    $('buttons').innerHTML = '';
			    $('buttons').className = 'user buttons';
				window.showContentByMenuItem('');
			} else {
				$('login').disabled = false;
				$('password').disabled = false;
				$('confirm').disabled = false;
				$('email').disabled = false;
				$('submit').disabled = false;

				window.validateRegistration();

                if (result['error_code'] == 'login') {
                    $('login').className = 'fourtyseven font14 incorrect block';
                }

                if (result['error_code'] == 'email') {
                    $('email').className = 'fourtyseven font14 incorrect';
                }

				$('load').style.display = 'none';
	            window.showErrorsDiv(result['error']);
				window.setTimeout('hideErrorsDiv();', 4000);
			}
		},
		false
	);

    return false;
}

function showAuthorizationForm()
{
    if ($('auth-form').style.display == 'block') {
		$('auth-form').style.display = 'none';
        $('auth-button').className = 'button';
	} else {
	    $('auth-button').className = 'button-pushed';
	    $('auth-form').style.display = 'block';
        $('reset-form').style.display = 'none';
	}

	return false;
}

function doAuthorization()
{
    var login = $('auth-login').value;
    var password = $('auth-password').value;

    if (!login || !trim(login)) {
        window.showErrorsDiv('Вы не ввели логин.');
		window.setTimeout('hideErrorsDiv();', 4000);
        return false;
    }

    if (!password || !trim(password)) {
        window.showErrorsDiv('Вы не ввели пароль.');
		window.setTimeout('hideErrorsDiv();', 4000);
        return false;
    }

    $('load').style.display = 'block';

    $('auth-login').disabled = true;
    $('auth-password').disabled = true;
    $('auth-submit').disabled = true;

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "authorization", "login": login, "password": password},
		function(result) {
			if (result['ok']) {
                $('auth-form').style.display = 'none';
                $('auth-form').innerHTML = '';
                $('reset-form').innerHTML = '';
                $('buttons').innerHTML = '';
                $('buttons').className = 'user buttons';
				window.showContentByMenuItem('');
			} else {
				$('auth-login').disabled = false;
				$('auth-password').disabled = false;
                $('auth-submit').disabled = false;
				$('load').style.display = 'none';
	            window.showErrorsDiv(result['error']);
				window.setTimeout('hideErrorsDiv();', 4000);
			}
		},
		false
	);

    return false;
}

var thisquote;

function goToAuthor(author, play, another)
{
    $('load').style.display = 'block';

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "author", "author": author },
		function(result) {
		    if (result['ok']) {
		        window.goToResult(result);
                if (another) {
                    window.showAnotherQuoteByThisAuthor(another, author);
                }
            } else {
                window.notFound();
            }
		},
		true
	);

    return false;
}

function goToKeyword(keyword, play, another)
{
    $('load').style.display = 'block';

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "keyword", "keyword": keyword },
		function(result) {
		    if (result['ok']) {
		        window.goToResult(result);
                if (another) {
                    window.showAnotherQuoteByThisKeyword(another, keyword);
                }
            } else {
                window.notFound();
            }
		},
		true
	);

    return false;
}

function showAnotherQuoteByThisAuthor(quote, author)
{
    $('load').style.display = 'block';

    document.location.href = domain + 'author/'+author + '/#quote'+quote;

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "another_quote_by_this_author", "quote": quote, "author": author, "thisquote": thisquote },
		function(result) {
		    window.getAnotherResult(result, quote);
		},
		false
	);

    return false;
}

function showAnotherQuoteByThisKeyword(quote, keyword)
{
    $('load').style.display = 'block';

    document.location.href = domain + 'keyword/'+keyword + '/#quote'+quote;

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "another_quote_by_this_keyword", "quote": quote, "keyword": keyword, "thisquote": thisquote },
		function(result) {
		    window.getAnotherResult(result, quote);
		},
		false
	);

    return false;
}

function showQuotesByUser(user, play, another)
{
    $('load').style.display = 'block';

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "user_quotes", "user": user },
		function(result) {
		    if (result['ok']) {
		        window.goToResult(result);
                if (another) {
                    window.showAnotherQuoteByThisUser(another, user);
                }
            } else {
                window.notFound();
            }
		},
		true
	);

    return false;
}

function showAnotherQuoteByThisUser(quote, user)
{
    $('load').style.display = 'block';

    document.location.href = domain + 'user/'+user + '/#quote'+quote;

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "another_quote_by_this_user", "quote": quote, "user": user, "thisquote": thisquote },
		function(result) {
		    window.getAnotherResult(result, quote);
		},
		false
	);

    return false;
}

function anotherQuote(type, id, quote)
{
    if (type == 'author') {
        window.showAnotherQuoteByThisAuthor(quote, id);
        return false;
    }
    if (type == 'keyword') {
        window.showAnotherQuoteByThisKeyword(quote, id);
        return false;
    }
    if (type == 'user') {
        window.showAnotherQuoteByThisUser(quote, id);
        return false;
    }
    if (type == 'favorites') {
        window.showAnotherQuoteByThisUserFavorites(quote, id);
        return false;
    }
    if (type == 'new') {
        window.showAnotherDayliQuote(quote, id);
        return false;
    }
    if (type == 'random') {
        window.showAnotherRandomQuote(quote);
        return false;
    }
    if (type == 'best') {
        window.showAnotherBestQuote(quote, id);
        return false;
    }
    return true;
}

var playtimeout;

function notFound()
{
    $('load').style.display = 'block';
	$('content').innerHTML = '';

    window.runCheckURL();

	JsHttpRequest.query(
		"/backend.php",
		{ "url": "/#notfound" },
		function(result) {
		    $('buttons').innerHTML = result['buttons'];
			$('content').innerHTML = result['content'];
            $('content').style.display = 'block';
			$('load').style.display = 'none';
		},
		false
	);
}

function showDirectLink()
{
    $('direct-link').className = 'hidden';
    $('direct-input').className = 'inline';
    $('direct-input').focus();
    $('direct-input').select();

    return false;
}

function addToFavorites(quote)
{
    $('load').style.display = 'block';

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "add_to_favorites", "quote": quote, cache: Math.random() },
		function(result) {
		    if (result['ok']) {
                $('favorites-link').innerHTML = 'Удалить&nbsp;из&nbsp;избранного';
                $('favorites-link').setAttribute("onclick", "return deleteFromFavorites("+quote+");");
		        $('load').style.display = 'none';
		        $('fdone').innerHTML = 'Цитата добавлена в&nbsp;список избранных.<br />Вы&nbsp;также можете поделиться ей.';
                $('fdone').style.display = 'block';
                window.setTimeout("$('fdone').style.display = 'none';", 4000);
		    } else {
		        $('load').style.display = 'none';
                window.showErrorsDiv(result['error']);
			    window.setTimeout('hideErrorsDiv();', 4000);
            }
		},
		false
	);

    return false;
}

function deleteFromFavorites(quote)
{
    $('load').style.display = 'block';

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "delete_from_favorites", "quote": quote, cache: Math.random() },
		function(result) {
		    if (result['ok']) {
                $('favorites-link').innerHTML = 'Добавить&nbsp;в&nbsp;избранное';
                $('favorites-link').setAttribute("onclick", "return addToFavorites("+quote+");");
		        $('load').style.display = 'none';
		        $('fdone').innerHTML = 'Цитата удалена из&nbsp;списка&nbsp;избранных.';
                $('fdone').style.display = 'block';
                window.setTimeout("$('fdone').style.display = 'none';", 4000);
		    } else {
		        $('load').style.display = 'none';
                window.showErrorsDiv(result['error']);
			    window.setTimeout('hideErrorsDiv();', 4000);
            }
		},
		false
	);

    return false;
}

function showUserFavorites(user, play, another)
{
    $('load').style.display = 'block';

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "user_favorites", "user": user },
		function(result) {
		    if (result['ok']) {
		        window.goToResult(result);
                if (another) {
                    window.showAnotherQuoteByThisUserFavorites(another, user);
                }
            } else {
                window.notFound();
            }
		},
		true
	);

    return false;
}

function showAnotherQuoteByThisUserFavorites(quote, user)
{
    $('load').style.display = 'block';

    document.location.href = domain + 'favorites/'+user + '/#quote'+quote;

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "another_quote_by_this_user_favorites", "quote": quote, "user": user, "thisquote": thisquote },
		function(result) {
		    window.getAnotherResult(result, quote);
		},
		false
	);

    return false;
}

var global_delta;

function goToResult(result)
{
    $('buttons').innerHTML = result['buttons'];
	$('content').innerHTML = result['content'];
    $('content').style.display = 'block';
    $('player').innerHTML = result['player'];
    $('player').style.width = '20%';
    $('pult').innerHTML = result['pult'];
    $('player').style.display = 'block';

    if (result['first_quote_id']) {
        thisquote = result['first_quote_id'];
    }

    if ($('player').clientHeight) {
        var ph = Math.round($('player').clientHeight);
    } else {
        var ph = result['player-height']*gCPTP();
    }

    global_delta = result['player-height']*gCPTP();

    if (Math.round(global_delta) < ph) {
	    $('playlist').style.height = Math.round(result['player-height']) + 'pt';
        $('scroll').style.display = 'none';
    } else {
	    $('playlist').style.height = ph + 'px';
        $('scroll').style.height = parseInt(((ph*ph) / (global_delta))) + 'px';
        $('playlist-body').style.marginTop = '0px';
    }

    if ($('player').addEventListener) {
        $('player').addEventListener('DOMMouseScroll', wheel, false);
    }

    $('player').onmousewheel = wheel;

    $('load').style.display = 'none';
}

function getAnotherResult(result, quote)
{
    if (result['ok']) {
        if (result['need_update_playlist']) {
            window.updateContent();
        }
	    $('buttons').innerHTML = result['buttons'];
    	$('content').innerHTML = result['content'];
        $('pquote-'+thisquote).className = 'playlist-item';
        $('pquote-'+thisquote).innerHTML = result['thisquote_content'];
        $('pquote-'+result['quote_playing']).className = 'playlist-item playing';
        $('pquote-'+result['quote_playing']).innerHTML = result['quote_playing_content'];
        $('pult').innerHTML = result['pult'];
        $('player').style.display = 'block';

        if ($('player').clientHeight) {
            var ph = Math.round($('player').clientHeight);
        } else {
            var ph = result['player-height']*gCPTP();
            window.scroll(0,0);
        }

        global_delta = result['player-height']*gCPTP();

        if (Math.round(global_delta) < ph) {
	        $('playlist').style.height = Math.round(result['player-height']) + 'pt';
            $('scroll').style.display = 'none';
        } else {
	        $('playlist').style.height = ph + 'px';
            var sh = parseInt((ph*ph) / global_delta);
            $('scroll').style.height = sh + 'px';

            var count_visible = Math.round(((ph / gCPTP()) - 8) / 18) - 1;

            var now_first = Math.ceil(((-parseInt($('playlist-body').style.marginTop) / gCPTP()) - 8) / 18);

            var dif = result['selected_number'] - now_first;

            if (dif >= 0) {
                if (dif > count_visible) {
                    var pos = Math.round((((result['selected_number'] - count_visible) * 18 + 4) * gCPTP()) / (global_delta/ph));
                    setPosition(pos);
                }
            } else {
                var pos = Math.round(((result['selected_number'] * 18 + 4) * gCPTP()) / (global_delta/ph));
                setPosition(pos);
            }
        }

        if ($('player').addEventListener) {
            $('player').addEventListener('DOMMouseScroll', wheel, false);
        }

        $('player').onmousewheel = wheel;

        $('load').style.display = 'none';
        thisquote = quote;
    } else {
        window.notFound();
    }
}

function goToItem(type, id, play, quote)
{
    if (type == 'author') {
        window.goToAuthor(id, play, quote);
        return;
    }
    if (type == 'keyword') {
        window.goToKeyword(id, play, quote);
        return;
    }
    if (type == 'user') {
        window.showQuotesByUser(id, play, quote);
        return;
    }
    if (type == 'favorites') {
        window.showUserFavorites(id, play, quote);
        return;
    }
    if (type == 'quote') {
        window.goToQuote(id);
        return;
    }
}

function checkEnabledSearch()
{
    if ($('query').value != '') {
        $('submit').disabled = false;
    } else {
        $('submit').disabled = true;
    }
}

function doSearch()
{
    var query = $('query').value;

    if (query.length < 3) {
        window.showErrorsDiv('Вы ввели слишком короткий запрос.');
		window.setTimeout('hideErrorsDiv();', 4000);
        return false;
    }

    $('load').style.display = 'block';

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "do_search", "query": query, "type": $('type').value },
		function(result) {
            $('searchresults').innerHTML = result['content'];
            $('load').style.display = 'none';
		},
		true
	);

    return false;
}

function goToQuote(quote)
{
    $('load').style.display = 'block';

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "quote", "quote": quote },
		function(result) {
		    if (result['ok']) {
		        window.goToResult(result);
            } else {
                window.notFound();
            }
		},
		false
	);

    return false;
}

function logout()
{
    $('load').style.display = 'block';

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "logout" },
		function(result) {
            if (result['ok']) {
                $('buttons').innerHTML = '';
                $('buttons').className = 'nouser buttons';
                $('auth-form').innerHTML = result['auth-content'];
                $('reset-form').innerHTML = result['reset-content'];
			    window.showContentByMenuItem('');
            } else {
                $('load').style.display = 'none';
                window.showErrorsDiv("Ошибка в передаче XML-данных.");
			    window.setTimeout('hideErrorsDiv();', 4000);
            }
		},
		false
	);

    return false;
}

function showResetForm()
{
    if ($('reset-form').style.display == 'block') {
		$('reset-form').style.display = 'none';
        $('auth-button').className = 'button';
	} else {
	    $('auth-button').className = 'button';
	    $('reset-form').style.display = 'block';
        $('auth-form').style.display = 'none';
	}

	return false;
}

function doResetPassword()
{
    var login = $('reset-login').value;
    var email = $('reset-email').value;

    if ((!login || !trim(login)) && (!email && !trim(email))) {
        window.showErrorsDiv('Вы не&nbsp;ввели ни&nbsp;логин, ни&nbsp;почту.');
		window.setTimeout('hideErrorsDiv();', 4000);
        return false;
    }

    $('load').style.display = 'block';

    $('reset-login').disabled = true;
    $('reset-email').disabled = true;
    $('reset-submit').disabled = true;

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "reset_password", "login": login, "email": email},
		function(result) {
			if (result['ok']) {
                $('reset-form').style.display = 'none';
                $('reset-login').disabled = false;
				$('reset-email').disabled = false;
                $('reset-submit').disabled = false;
                $('load').style.display = 'none';
                $('fdone').innerHTML = result['message'];
                $('fdone').style.display = 'block';
                window.setTimeout("$('fdone').style.display = 'none';", 4000);
			} else {
				$('reset-login').disabled = false;
				$('reset-email').disabled = false;
                $('reset-submit').disabled = false;
				$('load').style.display = 'none';
	            window.showErrorsDiv(result['error']);
				window.setTimeout('hideErrorsDiv();', 4000);
			}
		},
		false
	);

    return false;
}

function getDaily(play, another, limit)
{
    if (typeof limit == 'undefined') {
        limit = 0;
    }

    $('load').style.display = 'block';

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "daily", "limit": limit },
		function(result) {
		    if (result['ok']) {
		        window.goToResult(result);
                if (another) {
                    window.showAnotherDayliQuote(another, limit);
                }
            } else {
                window.notFound();
            }
		},
		true
	);

    return false;
}

function getBest(play, another, limit)
{
    if (typeof limit == 'undefined') {
        limit = 0;
    }

    $('load').style.display = 'block';

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "best", "limit": limit },
		function(result) {
		    if (result['ok']) {
		        window.goToResult(result);
                if (another) {
                    window.showAnotherBestQuote(another, limit);
                }
            } else {
                window.notFound();
            }
		},
		true
	);

    return false;
}

function getRandom(play, another)
{
    if (document.location.href != domain + 'random/') {
        document.location.href = domain + 'random/';
    }

    $('load').style.display = 'block';

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "random" },
		function(result) {
		    if (result['ok']) {
		        window.goToResult(result);
                if (another) {
                    window.showAnotherDayliQuote(another);
                }
            } else {
                window.notFound();
            }
		},
		true
	);

    return false;
}

function showAnotherDayliQuote(quote, limit)
{
    if (typeof limit == 'undefined') {
        limit = 0;
        var str_limit = '';
    } else if (!limit) {
        var str_limit = '';
    } else {
        var str_limit = limit + '/';
    }

    $('load').style.display = 'block';

    document.location.href = domain + 'new/' + str_limit + '#quote'+quote;

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "another_daily_quote", "quote": quote, "thisquote": thisquote, "limit": limit },
		function(result) {
		    window.getAnotherResult(result, quote);
		},
		true
	);

    return false;
}

function showAnotherBestQuote(quote, limit)
{
    if (typeof limit == 'undefined') {
        limit = 0;
        var str_limit = '';
    } else if (!limit) {
        var str_limit = '';
    } else {
        var str_limit = limit + '/';
    }

    $('load').style.display = 'block';

    document.location.href = domain + 'popular/' + str_limit + '#quote'+quote;

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "another_best_quote", "quote": quote, "thisquote": thisquote, "limit": limit },
		function(result) {
		    window.getAnotherResult(result, quote);
		},
		true
	);

    return false;
}

function showAnotherRandomQuote(quote)
{
    $('load').style.display = 'block';

    document.location.href = domain + 'random/#quote'+quote;

    window.runCheckURL();

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "another_random_quote", "quote": quote, "thisquote": thisquote },
		function(result) {
		    window.getAnotherResult(result, quote);
		},
		true
	);

    return false;
}

function setDesign(type)
{
    if (type == 'white') {
        $('fog').innerHTML = '<div style="width: 100%; height: 100%; position: fixed; top: 0%; left: 0%; background: black; z-index: 1000; cursor: wait;"></div>';
    } else if (type == 'black') {
        $('fog').innerHTML = '<div style="width: 100%; height: 100%; position: fixed; top: 0%; left: 0%; background: #fcfcfc; z-index: 1000; cursor: wait;"></div>';
    } else {
        return false;
    }

    window.setTimeout("changeCSS('"+type+"');", 300);

    JsHttpRequest.query(
		"/backend.php",
		{ "go": "set_design", "type": type },
		function(result) {
		    $('design').innerHTML = result['content'];
            window.setTimeout("$('fog').innerHTML = '';", 300);
		},
		false
	);

    return false;
}

function changeCSS(type)
{
    if (type == 'white') {
        var prefics = 'white_';
        var aprefics = '';
    } else if (type == 'black') {
        var prefics = '';
        var aprefics = 'white_';
    } else {
        return false;
    }

    $('style-link').href = '/styles/' + prefics + 'style.css';

    for (i = 0; true; i++) {
        if (document.images[i]) {
            document.images[i].src = document.images[i].src.replace('/images/' + aprefics, '/images/' + prefics);
        } else {
           break;
        }
    }

    $('header').style.background = 'url(/images/' + prefics + 'bg_header.png) repeat-x';
    $('img-load').src = '/images/' + prefics + 'loading.gif';
}

var cuinterval;

function runCheckURL()
{
    if (cuinterval) {
        window.clearInterval(cuinterval);
    }

    cuinterval = window.setInterval("window.checkThisURL('"+document.location.href+"');", 100);
}

function checkThisURL(url)
{
    if (document.location.href != url) {
        window.clearInterval(cuinterval);
        window.clearPlayer();
        updateContent();
    }
}

function sclear()
{
    $('load').style.display = 'block';

    var qreg = new RegExp('^([^#]+)/(author|keyword|user|favorites|quote)/([0-9]+)/?$');

    if (!qreg.test(document.location.href) && document.location.href != domain) {
        $('content').style.display = 'none';
    }
}

function clear(prefics)
{
    $('load').style.display = 'block';

    var qreg = new RegExp('^([^#]+)/(author|keyword|user|favorites|quote)/([0-9]+)/?$');

    if (!qreg.test(document.location.href) && document.location.href != domain) {
        $('content').style.display = 'none';
        $('content').innerHTML = '';
        var nmup = false;
    } else {
        var nmup = true;
    }
    $('header').style.background = 'url(/images/' + prefics + 'bg_header.png) repeat-x';
    $('img-load').src = '/images/' + prefics + 'loading.gif';
    window.updateContent(nmup);
}

function clearPlayer()
{
    $('player').style.display = 'none';
    $('player').innerHTML = '';
}

function trim(str, charlist)
{
	charlist = !charlist ? ' \s\xA0' : charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
	var reg = new RegExp('^[' + charlist + ']+|[' + charlist + ']+$', 'g');
	return str.replace(reg, '');
}

function validateEmail(email)
{
	var reg = /^(\S+)@([a-z0-9-]+)(\.)([a-z]{2,4})(\.?)([a-z]*)+$/i;
	return reg.test(email);
}

function showErrorsDiv(error_text)
{
	$('errors').style.display = 'block';
	$('errors').innerHTML = error_text;
}

function hideErrorsDiv()
{
	$('errors').innerHTML = '';
	$('errors').style.display = 'none';
}

document.onkeydown = navigate;
function navigate(event)
{
    if (!document.getElementById) {
        return;
    }
    if (window.event) {
        event = window.event;
    }
	if (event.ctrlKey) {
		switch (event.keyCode ? event.keyCode : event.which ? event.which : null) {
			case 0x25: {
				if (!$('pult-previous') || ($('load').style.display == 'block')) {
				    return;
				} else {
				    $('pult-previous').onclick();
				}
			} break;
			case 0x27: {
                if (!$('pult-next') || ($('load').style.display == 'block')) {
				    return;
				} else {
				    $('pult-next').onclick();
				}
			} break;
		}
	} else if (event.keyCode == 32 || event.keyCode == 39) {
        if (!$('pult-next') || ($('load').style.display == 'block')) {
		    return;
		} else {
		    $('pult-next').onclick();
		}
	} else if (event.keyCode == 37) {
        if (!$('pult-previous') || ($('load').style.display == 'block')) {
		    return;
		} else {
		    $('pult-previous').onclick();
		}
	}
}

document.onmousedown = scrollDrag;
document.onmousemove = scrollMove;
document.onmouseup = scrollDrop;

var canDrag = false;

var shift_y;

function setCanDrag()
{
    canDrag = true;
}

function scrollDrag(event)
{
    if (canDrag) {
        if (!event) {
            event = window.event;
        }

        shift_y = event.clientY - parseInt($('scroll').style.marginTop);

        blockEvent(event);
    }
}

function scrollMove(event)
{
    if (!global_delta || (Math.round(global_delta) <= Math.round($('playlist').clientHeight))) {
        return false;
    }

    if (!event) {
        event = window.event;
    }

    if (canDrag) {
        setPosition(event.clientY - shift_y);
        blockEvent(event);
    }
}

function scrollDrop(event)
{
    canDrag = false;
}

function setPosition(newPosition)
{
    if ((newPosition <= $('playlist').clientHeight - $('scroll').clientHeight) && (newPosition >= 0)) {
        $('scroll').style.marginTop = newPosition + 'px';
    } else if (newPosition > $('playlist').clientHeight - $('scroll').clientHeight) {
        $('scroll').style.marginTop = $('playlist').clientHeight - $('scroll').clientHeight + "px";
    } else {
        $('scroll').style.marginTop = 0 + "px";
    }

    var delta = global_delta / $('playlist').clientHeight;

    $('playlist-body').style.marginTop = Math.round(parseInt($('scroll').style.marginTop) * delta * (-1)) + "px";
}

function blockEvent(event)
{
    if (!event) {
        event = window.event;
    }

    if (event.stopPropagation) {
        event.stopPropagation();
    } else {
        event.cancelBubble = true;
    }

    if (event.preventDefault) {
        event.preventDefault();
    } else {
        event.returnValue = false;
    }
}

function wheel(event)
{
    if (!global_delta || (Math.round(global_delta) <= Math.round($('playlist').clientHeight))) {
        return false;
    }

    var wheelDelta = 0;

    var step = 10;

    if (!event) {
        event = window.event;
    }

    if (event.wheelDelta) {
        wheelDelta = -event.wheelDelta/60;
    } else if (event.detail) {
        wheelDelta = event.detail/3;
    }

    if (wheelDelta) {
        var currentPosition = parseInt($('scroll').style.marginTop);
        var newPosition = wheelDelta * step + currentPosition;
        setPosition(newPosition);
    }

    if (event.preventDefault) {
        event.preventDefault();
    }

    event.returnValue = false;

    blockEvent(event);
}

function gCPTP()
{
    var ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf('opera') != -1) {
        return 1.333;
    } else if (ua.indexOf('firefox') != -1) {
        return 1.333;
    } else if (ua.indexOf('webkit') != -1) {
        return 1.277;
    } else {
        return 1.333;
    }
}

function openScreen(n)
{
    if (n == 1) {
        var height = 726;
    } else if (n == 2) {
        var height = 736;
    }

    var win = window.open('/images/screens/'+n+'.png', 'win', "width=1024,height="+height+",status=1;toolbar=0;menubar=0,location=0,resizable=1,scrollbars=1");
	win.focus();

	return false;
}

function $(id)
{
    return document.getElementById(id);
}

function toFavoritesNoUser()
{
    window.showErrorsDiv('<a href="#" onclick="return showAuthorizationForm();" style="color: black;">Войдите</a> или <a href="/#registration" onclick="return showContentByMenuItem(\'registration\');" style="color: black;">зарегистрируйтесь</a>,<br />чтобы добавить цитату в&nbsp;избранное.');
	errortimeout = window.setTimeout('hideErrorsDiv();', 4000);
    return false;
}

function quotesby(by)
{
    if(by == 'tags') {
      $('authors-con').style.display = 'none';
      $('tags-con').style.display = 'block';
      $('authors-ctrl').className = 'ctrl';
      $('tags-ctrl').className = '';
    } else {
      $('tags-con').style.display = 'none';
      $('authors-con').style.display = 'block';
      $('tags-ctrl').className = 'ctrl';
      $('authors-ctrl').className = '';
    }
}

smsDonateId = 405598;
smsDonateButton = 7;

function smsDonatePopup(language)
{
    if (!window.smsDonateId) return;
    var lang = (!!language)? '&language=' + language: '';
    var ls = (language == "english")? '_en': '';
    window.open('http://donate.smscoin.com/js/smsdonate/index' + ls +
        '.html?sid=' + smsDonateId + lang,
        'smsdonate_popup', 'height=500,left=' + (screen.width - 700 >> 1) +
        ',resizable=yes,scrollbars=yes,top=' + (screen.height - 500 >> 1) +
        ',width=700');
}