$(document).bind('ready', function() {
	height = $("body").height();
	$('#shadow').css("height",height+"px");

});

$(document).ready(function() {
	setInterval("get_time()", 1000);
    printGreet();
});

function printGreet(){
    $.ajax({
     url: "/phpBB2/_aj_login.php",
     beforeSend: function(){
       $("#greet").css("display","inline")
                    .text("загрузка...");
     },
     success: function(answer){
       $("#greet").html(answer);
     }
  });
}

function vote_send() {
	uid = $('#uid').val();
	vid = $('#vid').val();
	aid = $('#aid').val();

	if(aid == 0) return $('#error_vote').html('Выберете вариант!');
	if(uid == 0) return $('#error_vote').html('Для голосования вам необходимо авторизоваться!');

	$.ajax({
		url: '/vote/send/',
		type: 'POST',
		data: 'uid='+uid+'&vid='+vid+'&aid='+aid,
		cache: false,
		success: function(response) {
			if(response == 'error')
				$('#error_vote').html('Неверно указаны данные!');
			else if(response == 'already')
				$('#error_vote').html('Вы уже голосовали!');
			else
				$('#vote').html(response);
		}
	});
}

function vote_result() {
	vid = $('#vid').val();

	$.ajax({
		url: '/vote/result/',
		type: 'POST',
		data: 'vid='+vid,
		cache: false,
		success: function(response) {
			if(response == 'error')
				$('#error_vote').html('Ошибка при получении данных!');
			else
				$('#vote').html(response);
		}
	});
}

function check_login_form() {
	return true;
}

function auth() {
  if($('#username').val() == '' || $('#password').val() == '' )
  {  	alert('Для входа необходимо  ввести логин и пароль');
    return false;
  }
  else $('#auth_form').ajaxSubmit({  	success: function(answer) {
       $("#login_res").html(answer);
       }
  });
}

function login_form(mode) {
	if(mode == 'close') {
		$('#auth').fadeOut('slow');
		$('#shadow').fadeOut('slow');
	} else {
		$('#shadow').fadeIn('slow').css('filter','progid:DXImageTransform.Microsoft.Alpha(Opacity=73)');
		$('#auth').fadeIn('slow');
	}
}

function get_time(){
	x = new Date();
	hours = x.getHours();
	minutes = x.getMinutes();
	seconds = x.getSeconds();

	if(minutes < 10) minutes = '0'+minutes;
	if(seconds < 10) seconds = '0'+seconds;

	$('#time').html(hours+":"+minutes);
}

function trade_time(value) {
	if(value==1) {
		$('#date_limit').removeAttr('disabled');
		$('#cost').attr('disabled','disabled');
		$('#donate').attr('disabled','disabled');
		}
	else if (value=='0000-00-00') {
		$('#donate').removeAttr('disabled');
		$('#date_limit').attr('disabled','disabled');
		}
	else {
		$('#date_limit').attr('disabled','disabled');
		$('#donate').attr('disabled','disabled');
	}
}

function donate_cash(value) {
	if(value==1) $('#cost').removeAttr('disabled');
	else $('#cost').attr('disabled','disabled');
}

function win(left,top,word) {
	$('#search_exchange #sort').val(word);
	$('#search_exchange div').show();
	$('#search_exchange div').css('left',left+'px');
	$('#search_exchange div').css('top',top+'px');
}
function write_attr(pos,field){
	$('#position').val(pos);
	$('#field').val(field);
}
function ajax_exchange() {
	word = $('#sort').val();
	position = $('#position').val();
	top = $('#top').val();
	field = $('#field').val();
	table = $('#table').val();
	$.ajax({
		url: '/trade/ajax_exchange/',
		type: 'POST',
		data: 'word='+word+'&field='+field+'&position='+position+'&table='+table,
		cache: false,
		success: function(response) {
				$('#search_exchange').html(response);
				win(position,top,word);
		}
	});
}

function get_cities(country_id) {
	$('#cities').attr('disabled','disabled');
	$.ajax({
		url: '/user/ajax_cities/',
		type: 'POST',
		data: 'country_id='+country_id,
		cache: false,
		success: function(response) {
				$('#cities').remove();
				$('#city_corner').next().html(response);
				$('#cities').removeAttr('disabled');
		}
	});
}

function add_city(id,name,country_id) {
	if(id == 0) $('#add_city').html('<span>&nbsp;</span><input type="text" id="new_city" /><span class="r">&nbsp;</span><a href="javascript:void(0)" onclick=\'add_city(-2,$("#new_city").val(),'+country_id+')\'>Добавить</a><br/>');
	else if (id == -1) return alert('Вы не выбрали город');
	else if(id == -2) {
		$.ajax({
			url: '/user/ajax_cities/',
			type: 'POST',
			data: 'country_id='+country_id+'&name='+name,
			cache: false,
			success: function(response) {
					$('#cities').remove();
					$('#city_corner').next().html(response);
					$('#add_city').html('Город успешно добавлен');
			}
		});
	} else return false;
}

// denvor
function delMsg(id){

 $.ajax({
    url: '/admin/ajax.php',
    dataType : "script",
    data: 'mode=message_delete&id=' + id,
    type: 'post'
   });

 $('#msg_' + id).css({display: 'none'});

}

function regAgreement(){

  if( $('#i_agree').attr("checked") == true ){
    $('#reg_form').css({display: 'block'});

    $.ajax({
      url: 'http://obmenigr.ru/phpBB2/reg/ucp.php?mode=register',
      beforeSend: function(){
       $("#reg_form").css("display","inline")
                     .text("загрузка...");
     },
     success: function(answer){       ans = replace_string(answer, './ucp', '/phpBB2/reg/ucp');
       $("#reg_form").html(ans);
     }
    });

  }
 // else 	$('#reg_form').css({display: 'none'});


}

// замена строк
function replace_string(txt,cut_str,paste_str){
    var f=0;
    var ht='';
    ht = ht + txt;
    f=ht.indexOf(cut_str);

    //цикл для вырезания всех имеющихся подстрок
    while (f!=-1){
        f=ht.indexOf(cut_str);
        if (f>0){
        ht = ht.substr(0,f) + paste_str + ht.substr(f+cut_str.length);
        };
    };
    return ht;
};

// регистрация
function registerPhpBB3(){
	var err = '';

	if($('#username').val() == '')         err+= '- не заполнено поле Имя пользователя\n';
	if($('#email').val() == '')            err+= '- не заполнено поле e-mail\n';
	if($('#email_confirm').val() == '')    err+= '- не заполнено поле Подтверждение e-mail\n';
	if($('#new_password').val() == '')     err+= '- не заполнено поле Пароль\n';
	if($('#password_confirm').val() == '') err+= '- не заполнено поле Подтверждение пароля\n';
	if($('#confirm_code').val() == '')     err+= '- не заполнено поле Антиспам-код\n';

	if(err != '') {	  alert('Обнаружены следующие ошибки: \n' + err);
	  return false;
	} else {
		$("#register").ajaxSubmit({
		   success: function(answer){
               ans = replace_string(answer, './ucp', '/phpBB2/reg/ucp');
               $("#reg_form").html(ans);
             }
		});
	}



}