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

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

function hide_block(id)
{
    $(id).style.display = 'none';
}

function show_block(id)
{
    $(id).style.display = 'block';
}

function zshk2(prt1, prt2)
{
    var s25 = '@';
    var k232 = prt1 + s25 + prt2;
    document.write('<' + 'a ' + 'hre' + 'f="m' + 'ail' + 't' + 'o:' + k232 + '">' + k232 + '</a>');
}

function go_catalog(element)
{
    value = (element == null) ? $F('s_catalog') : $F(element);
    if (value == 'all')
    {
        window.location = '/catalog/';
    }
    else
    {
        window.location = '/catalog/' + value + '/';
    }
    return false;
}

function go_afisha()
{
    window.location = '/afisha/' + $F('s_afisha') + '/?date=' + $F('s_afisha_day');
    return false;
}

function go_search()
{
    var value = trim($F('s_search'));

    if (value == 'Поиск...' || value == '')
    {
        alert('Введите строку для поиска');
        $('s_search').focus();
        return false;
    }

    if (value.length <= 2)
    {
        alert('Поисковый запрос слишком короткий');
        return false;
    }

    window.location = '/search/?search=' + encodeURIComponent($F('s_search'));
    return false;
}

function go_search_form()
{
    var value = trim($F('s_key'));

    if (value == '')
    {
        alert('Введите строку для поиска');
        $('s_key').focus();
        return false;
    }

    if (value.length <= 2)
    {
        alert('Поисковый запрос слишком короткий');
        return false;
    }
}

function set_dates()
{
    var type = $F('s_afisha');
    var d = $('s_afisha_day');

    d.options.length = 0;

    if (type == 'movies')
    {
        d[0] = new Option('Сегодня', 'today');
        d[1] = new Option('Завтра', 'tomorrow');
        d[2] = new Option('На неделю', 'week');
    }
    else if (type == 'performances')
    {
        d[0] = new Option('На месяц', 'month');
        d[1] = new Option('На неделю', 'week');
        d[2] = new Option('На сегодня', 'today');
        d[3] = new Option('На завтра', 'tomorrow');
    }
    else
    {
        d[0] = new Option('Ближайшие', 'all');
        d[1] = new Option('На неделю', 'week');
        d[2] = new Option('На месяц', 'month');
        d[3] = new Option('Сегодня', 'today');
        d[4] = new Option('Завтра', 'tomorrow');
    }

    d.selectedIndex = 0;
    return true;
}

function go_catalog_filter()
{
    var url = '/catalog/'
    var i = 0;
    var parts = new Array();

    if ($F('f_category') != 'all')
    {
        url += $F('f_category') + '/';
    }
    else
    {
        window.location = url;
        return false;
    }

    if ($F('f_district') != 0)
    {
        parts[i++] = 'district=' + $F('f_district');
    }

    if ($F('f_subway') != 0)
    {
        parts[i++] = 'subway=' + $F('f_subway');
    }

    if (parts.length > 0)
    {
        url += '?' + parts.join('&');
    }

    window.location = url;
    return false;
}

function clear_search()
{
    if ($F('s_search') == 'Поиск...')
    {
        $('s_search').value = '';
    }
}

function set_search()
{
    if ($F('s_search') == '')
    {
        $('s_search').value = 'Поиск...';
    }
}

function clear_catalog_search()
{
    if ($F('catalog-search') == 'поиск заведения')
    {
        $('catalog-search').value = '';
        $('catalog-search').style.color = '#000000';
    }
}

function clear_database_search(text)
{
    if ($F('search-key') == text)
    {
        $('search-key').value = '';
        $('search-key').style.color = '#000000';
    }
}

function submit_database_search(text)
{
    var value = trim(($F('search-key')));

    if (value == '' || value == text)
    {
        alert('Необходимо ввести хотя бы часть названия фильма');
        return false;
    }

    return true;
}

function submit_search(element)
{
    var value = trim($F(element));

    if (value == 'искать заведение')
    {
        alert('Необходимо ввести название заведения.');
        return false;
    }
    if (value.length <= 2)
    {
        alert("Слишком короткое слово. Введите хотя бы 3 символа.");
        return false;
    }

    return true;
}

function trim(string)
{
    return string.replace(/^\s+|\s+$/g, "");
}

function check_comment_form()
{
    var message = '',
		trimmedBody = trim($F('ta_body')),
	    MIN_SYMBOLS = 6,
	    MAX_SYMBOLS = 3000;
	if (!trimmedBody.length)
    {
        message = 'Необходимо ввести текст комментария';
        $('ta_body').focus();
    } else if (trimmedBody.length < MIN_SYMBOLS) {
		message = 'Текст комментария должен быть не менее ' + MIN_SYMBOLS + ' символов.';
        $('ta_body').focus();
	} else if (trimmedBody.length > MAX_SYMBOLS) {
		message = 'Текст комментария должен быть не более ' + MAX_SYMBOLS  +' символов.';
        $('ta_body').focus();
	}

    if (message != '')
    {
        alert(message);
        return false;
    }

    return true;
}

function check_contact_form()
{
    var email_regexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/i;
    var message = '';

    if (trim($F('tb_name')) == '')
    {
        message = 'Укажите ваше имя';
        $('tb_name').focus();
    }
    else if (!email_regexp.test($F('tb_email')))
    {
        message = 'Укажите правильный адрес электронной почты';
        $('tb_email').focus();
    }
    else if (trim($F('tb_subject')) == '')
    {
        message = 'Укажите тему сообщения';
        $('tb_subject').focus();
    }
    else if (trim($F('ta_message')) == '')
    {
        message = 'Введите текст сообщения';
        $('ta_message').focus();
    }

    if (message != '')
    {
        alert(message);
        return false;
    }

    return true;
}

function check_object_form(mode)
{
    var email_regexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/i;
    var message = '';

    if (trim($F('obj_name')) == '')
    {
        message = 'Укажите название';
        if (mode == 0) $('obj_name').focus();
    }
    else if (trim($F('obj_address')) == '')
    {
        message = 'Укажите адрес';
        if (mode == 0) $('obj_address').focus();
    }
    else if (trim($F('obj_district')) == '')
    {
        message = 'Укажите район';
        if (mode == 0) $('obj_district').focus();
    }
    else if (trim($F('obj_guides')) == '')
    {
        message = 'Укажите ориентир';
        if (mode == 0) $('obj_guides').focus();
    }
    else if (trim($F('obj_phone')) == '')
    {
        message = 'Укажите номер телефона';
        if (mode == 0) $('obj_phone').focus();
    }
    else if (!email_regexp.test($F('obj_email')))
    {
        message = 'Укажите правильный адрес электронной почты';
        if (mode == 0) $('obj_email').focus();
    }
    else if (trim($F('obj_person')) == '')
    {
        message = 'Укажите контактное лицо';
        if (mode == 0) $('obj_person').focus();
    }
    else if (trim($F('obj_comments')) == '')
    {
        message = 'Введите текст комментария';
        if (mode == 0) $('obj_comments').focus();
    }
    else if (trim($F('obj_word')) == '')
    {
        message = 'Введите защитный код';
        if (mode == 0) $('obj_word').focus();
    }

    if (message != '' && mode == 0)
    {
        alert(message);
        return false;
    }
    else if (message == '' && mode == 1)
    {
        $('send').disabled = false;
    }
    else
    {
        $('send').disabled = true;
    }

    return true;
}

function check_material_form(mode)
{
    var email_regexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,})+$/i;
    var message = '';

    if (trim($F('m_person')) == '')
    {
        message = 'Укажите контактное лицо';
        if (mode == 0) $('m_person').focus();
    }
    else if (!email_regexp.test($F('m_email')))
    {
        message = 'Укажите правильный адрес электронной почты';
        if (mode == 0) $('m_email').focus();
    }
    else if (trim($F('m_contents')) == '')
    {
        message = 'Введите текст новости/пресс-релиза';
        if (mode == 0) $('m_contents').focus();
    }
    else if (trim($F('m_word')) == '')
    {
        message = 'Введите защитный код';
        if (mode == 0) $('m_word').focus();
    }

    if (message != '' && mode == 0)
    {
        alert(message);
        return false;
    }
    else if (message == '' && mode == 1)
    {
        $('send2').disabled = false;
    }
    else
    {
        $('send2').disabled = true;
    }

    return true;
}

function add_material_picture(input){

	input.setAttribute('onchange', null);

	len = $('m_pics').childNodes.length;

	var new_file = document.createElement('input');
	var br = document.createElement('br');

	new_file.setAttribute('name', 'picture[]');
	new_file.setAttribute('type', 'file');
	new_file.setAttribute('class', 'text');
	new_file.setAttribute('className', 'text');

	if(len < 3){
		new_file.onchange = function(){add_material_picture(this)};
	};

	$('m_pics').appendChild(br);
	$('m_pics').appendChild(new_file);

}

function allow_comment_again()
{
    $('b_post').disabled = false;
}

function invoke_button(field, event)
{
    if (!event)
    {
        event = window.event;
    }
    if ((event.which && event.which == 13) ||  (event.keyCode && event.keyCode == 13))
    {
         $(field).onclick();
         return false;
    }
    return true;
}
var s=new Array();
s[1]=s[2]=0;

function choose_openid(id, loginMessage) {
	loginMessage = loginMessage || false;

	if (loginMessage) {
		$('choose_login_form').id.value = id;
		getElementsByClassName('loginMessage', $('choose_login_form'))[0].innerHTML = loginMessage;
		show_block('choose_login_form');
		$('choose_login_form').login.focus();
	} else {
		hide_block('choose_login_form');
		microAjax(location.pathname + '?id=' + id, function(response){
			if (response.indexOf('<form') === 0) {
				$('progress').innerHTML = 'Перенаправление на указанный сервис...';
				renderFormAndPost(response, 'openid_message');
			} else {
				$('progress').innerHTML = '';
				hide_block('progress');
				alert(response);
			}
		});

		show_block('progress');
		$('progress').innerHTML = 'Подождите, выполняется авторизация...';
	}
}

function askLogin(form) {
	var url = location.pathname + '?id=' + form.id.value + '&login=' + form.login.value;
	microAjax(url, function(response){
		if (response.indexOf('<form') === 0) {
			$('progress').innerHTML = 'Перенаправление на указанный сервис...';
			renderFormAndPost(response, 'openid_message');
		} else {
			$('progress').innerHTML = '';
			hide_block('progress');
			alert(response);
		}
	});

	show_block('progress');
	$('progress').innerHTML = 'Подождите, выполняется авторизация...';
	return false;
}

function renderFormAndPost(htmlForm, formId) {
	var div = document.createElement('DIV');
	div.style.display = 'none';
	div.innerHTML = htmlForm;
	document.body.appendChild(div);
	$(formId).submit();
}

function checkRadio(radio) {
	if (!radio.id) {
		return;
	}

	var labels = radio.parentNode.getElementsByTagName('LABEL');
	if (!labels.length) {
		return;
	}

	for(var i = 0, len = labels.length; i < len; i++) {
		var label = labels[i];
		label.className = radio.id == label.htmlFor ? 'selected' : '';
	}
}

function getElementsByClassName(className, root) {
	root = root || document;
	if (root.getElementsByClassName) {
		return root.getElementsByClassName(className);
	} else {
		var elements = root.getElementsByTagName('*'),
			collection = [];
		for (var i = 0, l = elements.length; i < l; i++) {
			var elem = elements[i], paddedClassName = ' ' + elem.className + ' ';
			if (paddedClassName.indexOf(' ' + className + ' ') > -1) {
				collection.push(elem);
			}
		}

		return collection;
	}
}


function toArray(object){
    var result = [];
    for (var i = 0, l = object.length; i < l; i++){
        result.push(object[i]);
    }
    return result;
};

// microAjax library

function microAjax(B,A){this.bindFunction=function(E,D){return function(){return E.apply(D,[D])}};this.stateChange=function(D){if(this.request.readyState==4){this.callbackFunction(this.request.responseText)}};this.getRequest=function(){if(window.ActiveXObject){return new ActiveXObject("Microsoft.XMLHTTP")}else{if(window.XMLHttpRequest){return new XMLHttpRequest()}}return false};this.postBody=(arguments[2]||"");this.callbackFunction=A;this.url=B;this.request=this.getRequest();if(this.request){var C=this.request;C.onreadystatechange=this.bindFunction(this.stateChange,this);if(this.postBody!==""){C.open("POST",B,true);C.setRequestHeader("X-Requested-With","XMLHttpRequest");C.setRequestHeader("Content-type","application/x-www-form-urlencoded");C.setRequestHeader("Connection","close")}else{C.open("GET",B,true)}C.send(this.postBody)}};
