gc = {};
gc.ajax = {
	validation_key: validation_key,
	sequences: {}
};
/**
 * Обработать запрос, показать сообщения
 * @param string action имя выполняемого запроса
 * @param object params параметры запроса
 * @param function success функция вывываемая после удачного выполнения запроса
 * 		(Function(result), если возвращает true, то сообщение не выводится, дальнейшая обработка обрывается)
 * @param object extra опционально, дополнительные параметры:
 * 		notify - параметры для показа сообщений, object
 * 		error - функция вызываемая при ошибке (Function(result), если возвращает true, то сообщение не выводится, дальнейшая обработка обрывается)
 *  	replace - замещает предыдушие запросы c таким id, результат по ним будет отброшен, string
 */
gc.ajax.handle = function (action, params, success, extra) {
	params['action'] = action;
	params['validation_key'] = gc.ajax.validation_key;

	if (extra == null) {
		extra = {};
	}

	var notify_params = {};
	if (extra['notify'] != null) {
		notify_params = extra['notify'];
	} else {
		notify_params['group'] = action;
	}
	if (notify_params['group'] != null) {
		notify_messages.removeGroup(notify_params['group']);
	}

	var sequence_number = null;
	if (extra['replace'] != null) {
		if (gc.ajax.sequences[extra['replace']] == null) {
			gc.ajax.sequences[extra['replace']] = 0;
		}
		sequence_number = ++gc.ajax.sequences[extra['replace']];
	}

	$.ajax({
		url: '/ajax/handler.php',
		type: 'POST',
		data: params,
		dataType: 'json',
		success: function (data, textStatus, req) {
			if ((extra['replace'] != null) && (sequence_number != gc.ajax.sequences[extra['replace']])) {
				return;
			}
			var result = data[action];
			if (result['success']) {
				if (success != null) {
					if (success(result)) {
						return;
					}
				}
				if (result['message'] != null) {
					notify_messages.add(result['message'], 'success', notify_params);
				}
			} else {
				if (extra['error'] != null) {
					if (extra['error'](result)) {
						return;
					}
				}
				notify_messages.add(result['error'], 'error', notify_params);
			}
		},
		error: function (req, textStatus, errorThrown) {
			if ((extra['replace'] != null) && (sequence_number != gc.ajax.sequences[extra['replace']])) {
				return;
			}
			if (extra['error'] != null) {
				var result = {
					success: false,
					error: 'Ошибка выполнения запроса, пожалуйста попробуйте позже',
					error_code: 'request_fail',
					status: textStatus
				};
				if (extra['error'](result)) {
					return;
				}
			}
			notify_messages.add('Ошибка выполнения запроса, пожалуйста попробуйте позже', 'error', notify_params);
		}
	});
};

function gc_populate_select(select_id, params, selected_key, add_empty){
    path = ajaxlink+"ajax/select.php?callback=?";
    $.getJSON(path, params, function(j){
      var options = '';
      if(add_empty){
		if (select_id == 'country') {
			options += '<option value="0">Выбрать</option>';
		} else {
			options += '<option value="0"></option>';
		}
      }
      var count = 0
      for (var i in j){
        options += '<option value="' + i + '"';
        if(selected_key == i){
    	    options += ' selected';
        }
        options += '>' + j[i] + '</option>';
        count ++;
      }
      $("select#"+select_id).html(options);
      if(count == 0){
        $("#container_"+select_id).css({display:'none'});
      }
      else{
        $("#container_"+select_id).css({display:'inline'});
      }
    });
}

var action;
function mark_spam(mid,id,sname,obj){

	$('#message_div').css({'display':'block'})
	//var mouse=getBounds(obj);
	var mouse=getPageEventCoords(obj);
	document.getElementById('message_div').style.left=(mouse.left-110)+'px';
	document.getElementById('message_div').style.top=(mouse.top-70)+'px';
	var name_field=document.getElementsByName('spammer_name');
	var ua = navigator.userAgent.toLowerCase();
	document.getElementById("spammer_id").value=id;
	document.getElementById("spam_message").value=mid;

	if(ua.indexOf("msie") == -1){
		name_field[0].innerHTML=sname;
		name_field[1].innerHTML=sname;
	}

}



function getPageEventCoords(evt) {
var coords = {left:0, top:0};
if (evt.pageX) {
coords.left = evt.pageX;
coords.top = evt.pageY;
} else if (evt.clientX) {
coords.left =
evt.clientX + document.body.scrollLeft - document.body.clientLeft;
coords.top =
evt.clientY + document.body.scrollTop - document.body.clientTop;
// include html element space, if applicable
if (document.body.parentElement && document.body.parentElement.clientLeft) {
var bodParent = document.body.parentElement;
coords.left += bodParent.scrollLeft - bodParent.clientLeft;
coords.top += bodParent.scrollTop - bodParent.clientTop;
}
}
return coords;
}


function n2br(text) {
   return text.split('\n').join('<br>');
}

function ctrlEnter(event, uid){
    if((event.ctrlKey) && ((event.keyCode == 0xA)||(event.keyCode == 0xD)))
        {
			send_quick_answer(uid);
        }
}


function send_pm(uid) {

	if (typeof send_pm_disable == 'undefined') {
		send_pm_disable = {}
	}
	if (typeof send_pm_disable[uid] != 'undefined' && send_pm_disable[uid]) {
		return true
	}
	send_pm_disable[uid] = true

		t = $(this);
		path = ajaxlink+"ajax/action.php";

		var text = $('#pm_text_'+uid).val();

		params = {action:'send_pm', uid_to:uid, pm_text:text, validation_key: validation_key};
		if ($('input[name=captcha]', '#pm_captcha_' + uid).length) {
			params['captcha'] = $('input[name=captcha]', '#pm_captcha_' + uid).attr('value')
		}

		$.post(path, params, function(j) {
			send_pm_disable[uid] = false
			if(j['send_pm']['success'] == 1) {
				notify_messages.add('Сообщение отправлено', 'success');
					success_message = "<span id='send_second_pm' class='button arrow_button' onclick='send_second_pm("+uid+");'>Еще одно</span>";
					$('#result_pm_to_'+uid).html(success_message);
					$('#result_pm_to_'+uid).siblings('form').css('display', 'none');

					$('#pmconmessages').prepend("<ul class='pmconversation' uid='"+uid+"'><li><p><b>Я</b></p><div class='text'>"+j['send_pm']['data']['message']+"</div><div class='dashedborder'></div></li></ul>");

					$('.ie #send_second_pm').css('width',$('.ie #send_second_pm').width()+'px').css('display','inline-block');
					$('.no-border-radius #result_pm_to_'+uid).find('span#send_second_pm').corner("5px");
					$('.pm_captcha').html('')

			} else {
				if (j['send_pm']['error'] == 'wrong_captcha') {
					pmShowCaptcha($('#pm_captcha_' + uid), {'error': 'wrong_captcha'})
				} else if (j['send_pm']['error'] == 'need_captcha') {
					pmShowCaptcha($('#pm_captcha_' + uid))
				} else {
					notify_messages.add(j['send_pm']['error'], 'error');
				}
			}
		}, "json");


    return false;
}

function pmShowCaptcha(obj, param) {
	param = typeof param == 'object' ? param : new Object
	objData = {}
	objData['action'] = 'check_captcha'

	html =""
	html+= "<span id='captcha_message'></span><br>\n"
	html+= "Введите символы с картинки:<br>\n"
	html+= "<img src='/img/captcha.php?rand=" + Math.random() + "' id='captcha_img' style='margin-top: 10px;' width='120' height='72'>&nbsp;&nbsp;\n"
	html+= "<span id='reload_captcha'>обновить картинку</span><br>\n"
	html+= "<input type='text' value='' name='captcha' style='margin-top: 10px; width: 116px;'>\n"
	$('.pm_captcha').html('')
	obj.html(html)

	$('#reload_captcha').click(function(){
		$('img#captcha_img').attr('src', "/img/captcha.php?rand=" + Math.random())
	})

	if  (typeof param['error'] != 'undefined') {
		if (param['error'] == 'wrong_captcha') {
			$('#reload_captcha').click()
			$('#captcha_message').addClass('error').removeClass('success').html('неправильные символы')
		}
	}
}

function delete_all_msg(uid) {
	if(!confirm("Вы действительно хотите удалить всю переписку?")){
		return;
	}

	$.ajax({
	   type: "GET",
	   url: ajaxlink+"ajax/action.php?action=delete_all_msg&validation_key=" + validation_key,
	   data: "uid="+uid,
	   success: function(result) {
			result=eval("("+result+")");
			if (result['delete_all_msg']['success']==1) {
				notify_messages.add('Сообщения удалены', 'success');
				//window.location.reload();
			} else {
				return;
			}
			//window.location.reload();
		}
	});
	return;
}

function show_quick_answer(uid){
	var obj = document.getElementById("quick_answer_"+uid);
	obj.style.display="block";
}

function hide_quick_answer(uid){
	var obj = document.getElementById("quick_answer_"+uid);
	obj.style.display="none";
}

function send_quick_answer(uid){

	if (typeof send_quick_answer_disable == 'undefined') {
		send_quick_answer_disable = {}
	}
	if (typeof send_quick_answer_disable[uid] != 'undefined' && send_quick_answer_disable[uid]) {
		return true
	}
	send_quick_answer_disable[uid] = true

	var text = document.getElementById("answer_"+uid).value;
	if(text == "" || text==" "){
		notify_messages.add('Не введен текст сообщения', 'error');
		return;
	}
	var no_html_text=text.replace(/<\/?[^>]+>/gi, '');
	if(no_html_text.length>30){
		no_html_text=no_html_text.substr(0,30)+"...";
	}

	var path = ajaxlink+"ajax/action.php?action=send_pm";
	params = {action:'send_pm', uid_to:uid, pm_text:text, validation_key: validation_key};
	if ($('input[name=captcha]', '#pm_captcha_' + uid).length) {
		params['captcha'] = $('input[name=captcha]', '#pm_captcha_' + uid).attr('value')
	}
	$.post(path, params, function(j) {
		send_quick_answer_disable[uid] = false
		if (j['send_pm']['success'] == 1) {
			document.getElementById("msg_"+uid).innerHTML="<b>Я</b>: <a style='color:#000;' href='/pm.php?uid="+uid+"'>"+n2br(no_html_text)+"</a>";
			document.getElementById("answer_"+uid).value="";
			hide_quick_answer(uid);
			$('.pm_captcha').html('')
		} else {
			if (j['send_pm']['error'] == 'wrong_captcha') {
				pmShowCaptcha($('#pm_captcha_' + uid), {'error': 'wrong_captcha'})
			} else if (j['send_pm']['error'] == 'need_captcha') {
				pmShowCaptcha($('#pm_captcha_' + uid))
			} else {
				notify_messages.add('Сообщение не отправлено', 'error');
			}
		}
    }, "json");

}
function spam_accept() {
	var sid=document.getElementById('spammer_id').value;
	var sm=document.getElementById('spam_message').value;
	var r_t=document.getElementsByName("radio_type");
	var r;
	for (var i=0;i<r_t.length;i++) {
		if(r_t[i].checked){
			r=r_t[i].value;
		}
	}
	$.ajax({
		type: "GET",
		url: ajaxlink+"ajax/action.php?action=spam_report",
		data: "spammer_id="+sid+"&spam_message_time="+sm+"&type_request="+r+"&validation_key="+validation_key,
		success: function(result) {
			result=eval("("+result+")");
			if(result['spam_report']['success']==1){
				notify_messages.add(result['spam_report']['message'], 'success');
				window.location.reload();
			} else {
				return;
			}
			window.location.reload();
		}
	});
	return;
}

function spam_decline() {
	document.getElementById('message_div').style.display="none";
}

function send_delete_message(mid,uid,type) {
	$.ajax({
		type: "GET",
		url: ajaxlink+"ajax/action.php?action=pm_delete",
		data: "mid="+mid+"&uid="+uid+"&t="+type+"&validation_key="+validation_key+"&callback=",
		success: function(result) {
			result=eval("("+result+")");
			if(result.error){
				notify_messages.add(result.msg, 'error');
				return;
			}
			window.location.reload();
		}
	});
}

function send_second_pm(uid){
    $("#result_pm_to_"+uid).siblings("form").children('textarea').val("");
    $("#result_pm_to_"+uid).siblings("form").css("display", "block");
    $("#result_pm_to_"+uid).siblings("form").children('textarea').focus();
    $("#result_pm_to_"+uid).children("span[onclick]").css('display', 'none');
}

$(document).ready(function(){
    $('.ajax_button:not(.without_perversion)').live('click', ajax_button_click_handler)
})

function ajax_button_click_handler() {
	//if($(this).attr('click') == 1) return;
	//$(this).attr('click', 1);
	//alert($(this).attr('class'));
	//return false;
	var confirm_text = 'Вы уверены?';
	if ($(this).hasClass('request_friendship')) {
		confirm_text = 'Предложить дружбу?';
	}
	if ($(this).hasClass('break_friendship')) {
		confirm_text = 'Перестать дружить?';
	}
	if ($(this).hasClass('confirm_friendship')) {
		confirm_text = 'Согласиться дружить?';
	}
	if ($(this).hasClass('decline_friendship')) {
		confirm_text = 'Отказаться от предложения дружить?';
	}
//	if ($(this).hasClass('hobby_list_edit')) {
//		confirm_text = 'Редактировать список интересов?';
//	}
	if ($(this).hasClass('privacy_edit')) {
		confirm_text = 'Применить новые настройки?';
	}
	if ($(this).hasClass('statusmessage_edit')) {
		if (!status_message_editor.isChanged()) {
			status_message_editor.stopEdit(false);
			notify_messages.removeGroup('statusmessage_edit');
			notify_messages.add('Статус остался прежним', 'info', {group: 'statusmessage_edit'});
			return false;
		}
		confirm_text = null;
	}
	if ($(this).hasClass('charslist_edit')) {
		confirm_text = 'Изменить настройки видимости персонажей?';
	}


	if(!$(this).hasClass('spam_decline') && !$(this).hasClass('spam_accept')){

		if((confirm_text != null) && !confirm(confirm_text)){
			return false;
		}
	}

	t = $(this);
	uid = $(this).attr('uid');
	class_name = $(this).attr('class');
	params = false;
	var onsuccess = null;
	var onfail = null;
	if(class_name == 'ajax_button request_friendship'){
		params = {action:'request_friendship', uid_to:uid};
		action = "request_friendship";
		onsuccess = function (data) {
			if ((data['data'] != null) && (data['data']['friendship'] == 1)) {
				t.removeClass('request_friendship')
					.addClass('break_friendship')
					.html('Удалить из друзей');
			} else {
				t.removeClass('request_friendship')
					.addClass('remove_request_friendship')
					.html('Отозвать запрос');
			}
		}
	}
	else if(class_name == 'ajax_button break_friendship'){
		params = {action:'break_friendship', uid_to:uid};
		action = "break_friendship";
		onsuccess = function (data) {
			t.removeClass('break_friendship')
				.addClass('request_friendship')
				.html('Добавить в друзья');
		}
	}
	else if(class_name == 'ajax_button remove_request_friendship'){
		params = {action:'remove_request_friendship', uid_to:uid};
		action = "remove_request_friendship";
		onsuccess = function (data) {
			t.removeClass('remove_request_friendship')
				.addClass('request_friendship')
				.html('Добавить в друзья');
		}
	}
	else if(class_name == 'ajax_button confirm_friendship'){
	    params = {action:'confirm_friendship', uid_to:uid};
	    action='confirm_friendship';
		onsuccess = function (data) {
			t.removeClass('confirm_friendship')
				.addClass('break_friendship')
				.html('Удалить из друзей');
			t.closest('ul.actions').find('.decline_friendship').remove();
		}
	}
	else if(class_name == 'ajax_button decline_friendship'){
	    params = {action:'decline_friendship', uid_to:uid};
	    action = "decline_friendship";
		onsuccess = function (data) {
			t.removeClass('decline_friendship')
				.addClass('request_friendship')
				.html('Добавить в друзья');
			t.closest('ul.actions').find('.confirm_friendship').remove();
		}
	}
/*	else if($(this).hasClass('ajax_button') && $(this).hasClass('hobby_list_edit')){
	    form = t.parents('form');
	    formdata = form.formToArray();
	    params = {action:'hobby_list_edit'};
	    action = 'hobby_list_edit';
	    for( var i in formdata){
		params[formdata[i]['name']] = formdata[i]['value'];
	    }
	}*/
	else if(class_name == 'ajax_button privacy_edit') {
	    form = t.parents('form');
	    formdata = form.formToArray();
	    params = {action:'privacy_edit'};
		params['wall_event[]'] = []
	    action = 'privacy_edit'
	    for( var i in formdata) {
			if (formdata[i]['name'] == 'wall_event[]') {
				params[formdata[i]['name']].push(formdata[i]['value'])
			} else {
				params[formdata[i]['name']] = formdata[i]['value'];
			}
	    }
	}
	else if(class_name.indexOf('statusmessage_edit') >= 0){
		form = t.parents('form');
		formdata = form.formToArray();
		params = {action:'statusmessage_edit'};
		action = 'statusmessage_edit';
		for( var i in formdata){
			params[formdata[i]['name']] = formdata[i]['value'];
		}
		onsuccess = function (data) {
			status_message_editor.stopEdit(true);
		}
		onfail = function (data) {
			status_message_editor.stopEdit(false);
		}
	}
	else if(class_name == 'ajax_button charslist_edit'){
	    form = t.parents('form');
	    formdata = form.formToArray();
	    params = {action:'charslist_edit'};
	    action = 'charslist_edit';
	    for( var i in formdata){
		params[formdata[i]['name']] = formdata[i]['value'];
	    }
	}else if(class_name == 'ajax_button spam_decline input_focus'){
	document.getElementById('message_div').style.display="none";
	}else if(class_name == 'ajax_button spam_accept input_focus'){
		var sid=document.getElementById('spammer_id').value;
		var sm=document.getElementById('spam_message').value;
		var r_t=document.getElementsByName("radio_type");
		var r;
		for(var i=0;i<r_t.length;i++){
			if(r_t[i].checked){
			r=r_t[i].value;
		}
			}
		$.ajax({
			    type: "GET",
			    url: ajaxlink+"ajax/action.php?action=spam_report",
			    data: "spammer_id="+sid+"&spam_message_time="+sm+"&type_request="+r+"&validation_key="+validation_key,
			    success: function(result){
					result=eval("("+result+")");
					if(result.error){
						alert(result.msg);
					return;
				}
			     window.location.reload();
			   }
			 });
		return;

	}
	if (
		typeof params == 'object' &&
		typeof params['validation_key'] == 'undefined' &&
		typeof validation_key != 'undefined'
	) {
		params['validation_key'] = validation_key
	}
	if(params) {
	    path = ajaxlink+"ajax/action.php?callback=?";
	    $.getJSON(path, params, function(j) {
			if(j[action]['success'] == 1) {
				notify_messages.add(j[action]['message'], 'success', {group: action});
				if(j[action]['message'] == "Профиль создан") {
					window.location = window.location;
					if (typeof(params['redirect_url']) != 'undefined'){
						window.location = params['redirect_url'];
					}
					$('.setting_unregistered .er_unregistered').css('display','none');
				}
				if (j[action]['message'] == "GameXP профиль успешно создан"){
					window.location = window.location;
					$('.setting_unregistered .er_unregistered').css('display','none');
					if (typeof(params['redirect_url']) != 'undefined') {
						window.location = params['redirect_url'];
					}
				}
				if (onsuccess != null) {
					onsuccess(j[action]);
				}
			} else {
				notify_messages.add(j[action]['error'], 'error', {group: action});
				if(j[action]['error_field']){
					$("label[for="+j[action]['error_field']+"]").attr('class', 'error');
				}
				if (onfail != null) {
					onfail(j[action]);
				}
			}
	    });
	}
	return false;


	//alert($("span.ajax_button.request_friendship").attr('uid'));
}

function show_pm(withuid, gamexp_name, limit){
    var url = 'http://gc.gamexp.ru/ajax/show_pm.php?withuid='+withuid+'&limit='+limit+'&rand='+Math.random()+'&gamexp_name='+gamexp_name+'&validation_key='+validation_key;
    $('#pmconmessages[uid='+withuid+']').load(url);
    return false;
}

function htmlspecialchars(text)
{
  var chars = Array("&", "<", ">");
  var replacements = Array("&amp;", "&lt;", "&gt;");
  for(var i=0; i<chars.length; i++)
  {
     var re = new RegExp(chars[i], "gi");
     if(re.test(text))
     {
        text = text.replace(chars[i], replacements[i]);
     }
  }
  return text;
}
