var common_backend_url = '/ajax/ajax_backend.js.php';
var debug_level = 'dev';

function ajax_action(action, param) {
	param['action'] = action;
	var obj = gebi(param.dest_obj_id);
	if (obj) {
		obj.innerHTML = '<div align="center"><img src="images/ajax_light.gif"></div>';
	}
	var backend_url = param['backend_url'] || common_backend_url;
	$.ajax({
		type: "POST",
  url: backend_url,
  data: param,
  dataType: "json",
  success: function(response) {
	  if (response) {
		  if (!response.js.action) {
			  debug_message('Invalid response');
		  } else {
			  if(response.text) {
				  debug_message(response.text);
			  }
			  var func = response.js['response_func'] || 'action_'+action+'_response';
			  eval(func+'(response.js)');
		  }
	  }
  }
	});
}
function debug_message(message) {
	if (!message) return;
	if (debug_level == 'dev') alert(message);
	var obj = $("#debug").text(message);
}
function ajax_response(response) {
	var obj = $('#' + response.dest_obj_id);
	if (obj) obj.replaceWith(response.html);
}

/********************/
/* ??????? ???????????? */
function ajax_page(p, mode, submode, filter, dest_obj_id) {
	ajax_action('ajax_page', {'p': p, 'mode': mode, 'submode': submode, 'filter': filter, 'dest_obj_id': dest_obj_id, 'response_func': 'ajax_response'});
}

var realW = 0;
var wSaved = false;
function ajax_prevote(event, obj) {
	var x = event.clientX;
	var o=typeof(obj) == 'string' ? gebi(obj) : obj
	var tmp = getBounds(o);
	var relX = (x - tmp['left']);
	var onepercent = 10 / 7;
	var stars = gebi(obj);
	if (wSaved == false) {
		realW = stars.style.width;
		wSaved = true;
	}
	stars.style.width = (relX * onepercent) + '%';
}

function ajax_vote_restore(obj) {
	var o = gebi(obj);
	o.style.width = realW;
	wSaved = false;
}

function ajax_vote(event, obj, mode, object, dest_obj_id) {
	var x = event.clientX;
	var o=typeof(obj) == 'string' ? gebi(obj) : obj
	var tmp = getBounds(o);
	var relX = (x - tmp['left']);
	var onestar = 14;
	var stars = gebi(obj);
	star = Math.ceil(relX / 14);
	ajax_action('vote', {'mode': mode, 'object': object, 'star': star, 'dest_obj_id': dest_obj_id, 'response_func': 'ajax_response'});
}

function change_email(email, passwd, dest_obj_id) {
	email = gebi(email).value;
	passwd = gebi(passwd).value;
	ajax_action('change_email', {'email': email, 'passwd': passwd, 'dest_obj_id': dest_obj_id, 'response_func': 'ajax_response'});
}

function change_info(param, value, dest_obj_id) {
	value = gebi(value).value;
	ajax_action('change_info', {'param': param, 'value': value, 'dest_obj_id': dest_obj_id, 'response_func': 'ajax_response'});
}

function change_passwd(cpasswd, npasswd, dest_obj_id) {
	cpasswd = gebi(cpasswd).value;
	npasswd = gebi(npasswd).value;
	ajax_action('change_passwd', {'cpasswd': cpasswd, 'npasswd': npasswd, 'dest_obj_id': dest_obj_id, 'response_func': 'ajax_response'});
}

function change_ava(ava_comp, ava_url, dest_obj_id) {
	var req = new JsHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			var ava_small = gebi('ava_small');
			var ava_large = gebi('ava_large');
			ava_small.src = '';
			ava_large.src = '';
			var obj = gebi(req.responseJS.dest_obj_id);
			obj.innerHTML = req.responseJS.html;
			ava_small.src = req.responseJS.ava;
			ava_large.src = req.responseJS.ava;
		}
	}
	req.open(null, '/ajax/change_ava.php', true);
	req.send({'ava_comp': ava_comp, 'ava_url': ava_url.value, 'dest_obj_id': dest_obj_id});
}

function change_photo(photo_comp, photo_url, dest_obj_id) {
	var req = new JsHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			var photo = gebi('photo');
			photo.src = '';
			photo.src = req.responseJS.photo;
			photo.width = '265px';
			photo.style.width = '265px';
			var obj = gebi(req.responseJS.dest_obj_id);
			obj.innerHTML = req.responseJS.html;
		}
	}
	req.open(null, '/ajax/change_photo.php', true);
	req.send({'photo_comp': photo_comp, 'photo_url': photo_url.value, 'dest_obj_id': dest_obj_id});
}

function change_photos(photos_comp, photos_url, dest_obj_id) {
	var req = new JsHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			document.location = '/?mode=profile&submode=edit';
/*			var photo = gebi('photo');
			photo.src = '';
			photo.src = req.responseJS.photo;
			photo.width = '265px';
			photo.style.width = '265px';
			var obj = gebi(req.responseJS.dest_obj_id);
			obj.innerHTML = req.responseJS.html;*/
		}
	}
	req.open(null, '/ajax/change_photos.php', true);
	req.send({'photos_comp': photos_comp, 'photos_url': photos_url.value, 'dest_obj_id': dest_obj_id});
}

function save_char(f) {
	var req = new JsHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.responseJS.error) {
				gebi('charerror').innerHTML = req.responseJS.error;
			} else {
				gebi('charerror').innerHTML = '';
				if (req.responseJS.c.pic > 0) {
					gebi('pers_main').src = req.responseJS.c.pic_path;
				}
				gebi('game').value = req.responseJS.c.game;
				gebi('server').value = req.responseJS.c.server;
				gebi('name').value = req.responseJS.c.name;
				gebi('clan').value = req.responseJS.c.clan;
				gebi('race').value = req.responseJS.c.race;
				gebi('class').value = req.responseJS.c.cclass;
				gebi('level').value = req.responseJS.c.level;
				gebi('descr').value = req.responseJS.c.descr;
				gebi('charerror').innerHTML = req.responseJS.s;
				list_chars(req.responseJS.c.id);
			}
		}
	}
	req.open(null, '/ajax/save_char.php', true);
	req.send({'form': f});
}

function add_char(f) {
	for(i = 0; i < f.length; i++) {
		if (f.elements[i].type == 'text') {
			f.elements[i].value = '';
		}
		f.elements['id'].value = '0';
	}
	gebi('pers_main').src = 'images/no_pers.gif';
	gebi('chartitle').innerHTML = '&nbsp;';
	list_chars(0);
}

function switch_char(i, uid) {
	var req = new JsHttpRequest();
	if (!uid) uid = 0;
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.responseJS.error) {
				gebi('charerror').innerHTML = req.responseJS.error;
			} else {
				gebi('charerror').innerHTML = '';
				if (req.responseJS.c.pic > 0) {
					gebi('pers_main').src = req.responseJS.c.pic_path;
				}
				gebi('chartitle').innerHTML = req.responseJS.c.name;
				gebi('game').value = req.responseJS.c.game;
				gebi('server').value = req.responseJS.c.server;
				gebi('name').value = req.responseJS.c.name;
				gebi('clan').value = req.responseJS.c.clan;
				gebi('race').value = req.responseJS.c.race;
				gebi('class').value = req.responseJS.c.cclass;
				gebi('level').value = req.responseJS.c.level;
				gebi('descr').value = req.responseJS.c.descr;
				gebi('id').value = req.responseJS.c.id;
				list_chars(req.responseJS.c.id, uid);
			}
		}
	}
	req.open(null, '/ajax/switch_char.php', true);
	req.send({'id': i});
}

function list_chars(i, uid) {
	var req = new JsHttpRequest();
	if (!uid) uid = 0;
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.responseJS && req.responseJS.l) {
				l = req.responseJS.l;
				for (i = 0; i < 2; i++) {
					if (l[i]) {
						var path = '';
						var str = ''
						str = '<a href="javascript:void(0);" onclick="switch_char(' + l[i].id + ', ' + uid + ')"><img id="pers_add' + (i + 1) + '" width="65px" height="93px"';
						if (l[i].pic > 0) { 
//							gebi('pers_add' + (i + 1)).src = l[i].pic_path;
							path = l[i].pic_path;
						} else {
//							gebi('pers_add' + (i + 1)).src = 'images/no_pers.gif';
							path = 'images/no_pers.gif';
						}
						str = str + ' src="' + path + '"></a>';
						gebi('pers_small' + (i + 1)).innerHTML = str;
						gebi('charlevel' + (i + 1)).innerHTML = l[i].level + ' lvl';
					} else {
						gebi('pers_small' + (i + 1)).innerHTML = '<img id="pers_add' + (i + 1) + '" width="65px" height="93px" src="images/d.gif">'
//						gebi('pers_add' + (i + 1)).src = 'images/d.gif';
						gebi('charlevel' + (i + 1)).innerHTML = '&nbsp;';
					}
				}
			}
		}
	}
	req.open(null, '/ajax/list_char.php', true);
	req.send({'id': i, 'userid': uid});
}

function rem_char(i) {
	var ans = window.confirm('Вы уверены что хотите удалить персонажа "' + gebi('name').value + '" ?');
	if (ans == false) {
		return;
	}
	var req = new JsHttpRequest();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.responseJS.error) {
				gebi('charerror').innerHTML = req.responseJS.error;
			} else {
				gebi('charerror').innerHTML = '';
				if (req.responseJS.c.pic > 0) {
					gebi('pers_main').src = req.responseJS.c.pic_path;
				}
				gebi('chartitle').innerHTML = req.responseJS.c.name;
				gebi('game').value = req.responseJS.c.game;
				gebi('server').value = req.responseJS.c.server;
				gebi('name').value = req.responseJS.c.name;
				gebi('clan').value = req.responseJS.c.clan;
				gebi('race').value = req.responseJS.c.race;
				gebi('class').value = req.responseJS.c.cclass;
				gebi('level').value = req.responseJS.c.level;
				gebi('descr').value = req.responseJS.c.descr;
				gebi('id').value = req.responseJS.c.id;
				list_chars(req.responseJS.c.id);
			}
		}
	}
	req.open(null, '/ajax/rem_char.php', true);
	req.send({'id': i});
}

/* ??????? ????? */
function change_video(videonum, domain) {
	ajax_action('change_video', {'videonum': videonum, 'domain': domain, 'response_func': 'ajax_response'});
}

/* ??????? ???????? */
function change_image(imagenum, domain, dest_obj_id) {
	ajax_action('change_image', {'imagenum': imagenum, 'domain': domain, 'dest_obj_id': dest_obj_id, 'response_func': 'ajax_change_image_response'});
}

function ajax_change_image_response(response) {
	var $imgobj = gebi('image');
	var $imgcont = gebi('image_content');
	if ($imgobj) $imgobj.innerHTML = response.imghtml;
	if ($imgcont) $imgcont.innerHTML = response.html;
}

/* ??????????? */
function polling_answer(polling_id, answer_id, dest_obj_id) {
	ajax_action('polling_answer', {'polling_id': polling_id, 'answer_id': answer_id, 'dest_obj_id' : dest_obj_id, 'response_func': 'ajax_response'});
}

function polling_display(polling_id, view, dest_obj_id) {
	ajax_action('polling_display', {'polling_id': polling_id, 'view': view, 'dest_obj_id' : dest_obj_id, 'response_func': 'ajax_response'});
}

/* ???????? ?????? */
function login_check(login, dest_obj_id) {
	ajax_action('login_check', {'login': login, 'dest_obj_id': dest_obj_id});
}

function action_login_check_response(response) {
	var obj = $('#' + response.dest_obj_id);
	if (obj) obj.html(response.html);	
}

function filter_block(mode, filter, dest_obj_id) {
	var addc = !$(this).hasClass('selected');
	$('#' + dest_obj_id + ' > .nav-second > a').removeClass('selected');
	$(this).toggleClass('selected', addc);
	ajax_action('filter_block', {'mode': mode, 'get': filter, 'dest_obj_id': dest_obj_id, 'response_func': 'filter_response'});
}

function filter_response (resp) {
	$('#' + resp.dest_obj_id).replaceWith(resp.html);
}

function media_get(id, mode, dest_obj_id) {
	ajax_action('media_get', {'id': id, 'mode': mode, 'dest_obj_id': dest_obj_id, 'response_func': 'ajax_response'});
}

function forget_user(forget, dest_obj_id) {
	ajax_action('forget_user', {'forget': forget, 'dest_obj_id': dest_obj_id, 'response_func': 'ajax_response'}); 
}

/* ????????? ??????????? ??? ?????????????? */
function GetComment(object_class, object_id, id) {
	ajax_action('comment', {
		'object_class': object_class,
  'object_id': object_id,
  'comment_id': id,
  'response_func': 'comment_response'
	});	
}
function comment_response(response) {
	if (response.status == 0) {
		var elm = gebi('other_error');
		if(elm)elm.innerHTML = response.error;
	} else {
		document.comments.elements['form[text]'].value = response.text;
		document.comments.elements['form[title]'].value = response.title;
	}
}

/* ?????????, ????? ?????? */
function cal_month_change(year, month, curday, dest_obj_id) {
	ajax_action('cal_month_change', {
		'year': year,
  'month': month,
  'curday': curday,
  'response_func': 'ajax_response',
  'dest_obj_id': dest_obj_id
	});
}

/* ????? ?????? ??????? ? ?????? */
function cities_by_country(country) {
	if (!country) return;
//	var ajax_loading = gebi("ajax_loading");
	var form_city = gebi("form_city");
//	ajax_loading.style.display = "inline";
	var len = form_city.options.length;
	for (var i = len - 1; i >= 0; i--) {
		form_city.remove(i);
	}
//	form_city.options[0] = new Option("Другое", "");
//	form_city.options[0].selected = true;
//	form_city.disabled = false;
	ajax_action("cities", {"country": country});
	ajax_loading.style.display = "none";
}

function action_cities_response(response) {
	if (!response.status) return false;
	var obj = gebi(response.dest_obj_id || "form_city");
	var cities = eval(response.html); // JSON in response.html
	var len = cities.length;
	for (var i = 0; i < len; i++) {
		obj.options[i] = new Option(cities[i], cities[i]);
	}
	obj.disabled = '';
}

function alds_rating(oid, val) {
	ajax_action('alds_rating', {'oid': oid, 'val': val, 'response_func': 'ajax_response'});
}