// delay while typing
var delay = (function(){
	var timer = 0;
	return function(callback, ms){
		clearTimeout (timer);
		timer = setTimeout(callback, ms);
	};
})();

// edit username
$("#user_name").keyup(function ()
{
	delay(function()
	{
		var name = $("#user_name").val();

		$.cookie("who", name, { expires: 300, path: '/' });

		// change avatar
		$.post(PATH+'class/ajax/md5.php', 'text='+name, function(data)
		{
			$('#avatar').attr('src', 'http://www.gravatar.com/avatar/'+data+'?d=identicon&s=16.jpg');
		});

	}, 1000 );
})


// cookies
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


// search word
$("input#kw").keyup(function ()
{
	// word
	var word = $.trim($("input#kw").val());

	// if empty
	if ( word.length == 0 )
		return false;

	// if russian
	if ( word.match(/[а-яА-Я]/ ) && (word.indexOf(' ') < 0) )
		delay(function(){ajax_search_aux(word)}, 600);
	// engish - pinyin;
	else if ( word.match(/^[a-z ]+$/ ) && (word.length < 10) )
		delay(function(){ajax_search_aux(word)}, 600);
	// chinese
	else if ( !(/[a-z]/.test(word)) && (word.length < 6) )
		delay(function(){ajax_search_aux(word)}, 200);

})

// auxiliary for ajax search
function ajax_search_aux(word)
{
	// !!
	if ( IS_LOGGED )
	{
		// ajax search
		$.post(PATH+'class/ajax/ajax_word_search_a.php', 'word='+word+'&user_name='+user_name+'&is_logged='+IS_LOGGED+'&ip='+ip+'&fun=1', function(data)
		{
			// insert data
			$('div#ajax_search').html(data);
		});
	}
}

// get number
function intval (mixed_var, base) {
    var type = typeof(mixed_var);
    if (type === 'boolean') {        return (mixed_var) ? 1 : 0;
    } else if (type === 'string') {
        tmp = parseInt(mixed_var, base || 10);
        return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp;
    } else if (type === 'number' && isFinite(mixed_var)) {        return Math.floor(mixed_var);
    } else {
        return 0;
    }
}

// pinyin input
var ime = 0;
$('#py').click(function()
{
	if ( ime == 0 )
	{
		if(window.bdime)
		{
			bdime.open();
		}
		else
		{
			var s = document.createElement("script");
			s.src = "http://www.baidu.com/olime/bdime_open.js";
			document.getElementsByTagName("head")[0].appendChild(s);
		}
		document.getElementById("kw").focus();
		ime = 1;
	}
	else
	{
		bdime.close();
		ime = 0;
	}

	return false;
});

function onLoad() {
	kbd = new google.elements.keyboard.Keyboard(
	[google.elements.keyboard.LayoutCode.RUSSIAN],
	['kw']);
}
var ru_keyboard = 0;

$('a#ru_keyboard').click(function(e) {

	if ( typeof kbd == 'undefined' )
	$.getScript('https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22elements%22%2C%22version%22%3A%221%22%2C%22callback%22%3A%22onLoad%22%2C%22packages%22%3A%5B%22keyboard%22%5D%7D%5D%7D', function() { ru_keyboard = 1 });
	else if ( ru_keyboard == 1 ) {
		kbd.setVisible(false);
		ru_keyboard = 0;
	} else {
		kbd.setVisible(true);
		ru_keyboard = 1;
	}

	return false;
});

/*
// check that not from big letter
$("#submit").click(function()
{
	// check user
	// if ( ( USER_RATING < 5 || USER == 'baizulin' ) & $.cookie('o_bigletters') != 'shown' )
	if ( ( USER_RATING < 5 || USER == 'Aishalady' || USER == 'kumold' || USER == 'hunhuz' || USER == 'strelok-ac' || USER == 'Vetrenitsa' || USER == 'YiLi' || USER == 'svamed' || USER == 'baizulin' ) & $.cookie('o_bigletters') != 'shown5' )
	{
		var text = $('#ruf').val();

		if ( text != text.toLowerCase() &
						text.indexOf('имя') == -1 &
						text.indexOf('фамилия') == -1 &
						text.indexOf('собств') == -1 &
						text.indexOf('[ex]') == -1 &
						text.indexOf('г.') == -1
				 )
		{
			alert('同志！\nТолько имена собственные начинаются с большой буквы.\nПроверьте, что это так в данном переводе.');
			$.cookie("o_bigletters", 'shown5', { expires: 300, path: '/' });

			//console.log(text);

			return false;
		}
	}
	return true;
});
*/
