var ua = navigator.userAgent.toLowerCase();
var isStrict = document.compatMode == "CSS1Compat",
isOpera = ua.indexOf("opera") > -1,
isSafari = (/webkit|khtml/).test(ua),
isSafari3 = isSafari && ua.indexOf('webkit/5') != -1,
isIE = !isOpera && ua.indexOf("msie") > -1,
isIE7 = !isOpera && ua.indexOf("msie 7") > -1,
isGecko = !isSafari && ua.indexOf("gecko") > -1,
isBorderBox = isIE && !isStrict,
isWindows = (ua.indexOf("windows") != -1 || ua.indexOf("win32") != -1),
isMac = (ua.indexOf("macintosh") != -1 || ua.indexOf("mac os x") != -1),
isAir = (ua.indexOf("adobeair") != -1),
isLinux = (ua.indexOf("linux") != -1),
isSecure = window.location.href.toLowerCase().indexOf("https") === 0,
isIE6 = isIE && !isIE7;

if (!Array.indexOf) {
	Array.prototype.indexOf = function (obj) {
		for (var i = 0; i < this.length; i++) {
			if (this[i] == obj) {
				return i;
			}
		}
		return - 1;
	}
}

function mainGameOver(element) {
	$(element).children('.mainGame-back').css('background-position', '0 -120px');
	$(element).children('.mainGame-fog').css('display', 'block');
	return true;
}

function mainGameOut(element) {
	$(element).children('.mainGame-back').css('background-position', '0 0');
	$(element).children('.mainGame-fog').css('display', 'none');
	return true;
}

// Подгрузка картинок
images = [];
var images_src = ['../images/secondBackground-top.gif', '../images/secondBackground-center.jpg', '../images/secondText-right-input.gif', '../images/secondBackground-registr.gif', '../images/secondBackground-auth.gif', '../images/secondBackground-empty.gif', '../images/secondBackground-top-empty.gif'];
for (var i = 0, len = images_src.length; i < len; i++) {
	images.push(new Image());
	images[i].src = images_src[i];
}

/**
	 * Settings
	 **/
waitingMessage = '<div class="second"><div class="secondBackground-top-empty"></div><div class="secondBackground-center"><div class="secondText"><center>Пожалуйста, подождите...</center></div></div><div class="secondBackground-empty"></div></div>';
waitingMessageEn = '<div class="second"><div class="secondBackground-top-empty"></div><div class="secondBackground-center"><div class="secondText"><center>Wait please...</center></div></div><div class="secondBackground-empty"></div></div>';

formsBackendURL = {
	REGISTER_FORM: 'htdocs/popup-forms/show-registr-form.php',
	REGISTER_FORM_B: 'htdocs/popup-forms/show-registr-form_big.php',
	REGISTER_FORM_E: 'htdocs/popup-forms/show-registr-form_extended.php',
	REGISTER_FORM_SMT: 'htdocs/popup-forms/show-registr-form_send_money_to.php',
	AUTH_FORM: 'htdocs/popup-forms/show-auth-form.php',
	FORGOT_PASS_FORM: 'htdocs/popup-forms/show-forgot-password.php',
	ERROR_REG: 'htdocs/popup-forms/reg_error.php',
	SUCCESS_REG: 'htdocs/popup-forms/reg_success.php',
	RESTORE_PASS_FORM: 'htdocs/popup-forms/restore_sended.php',
	SELECT_CASH: 'htdocs/popup-forms/select_kassa_folder.php',
	MY_ACCOUNT: 'htdocs/popup-forms/my_account.php',
	SELECT_TYPE_GAME: 'htdocs/popup-forms/select_type_game.php',
	SET_DESKTOP_ICON: 'htdocs/popup-forms/create_desktop_link.php',
	ATTENTION_DESKTOP_LINK: 'htdocs/popup-forms/attention_desktop_link.php',
	CHECK_JVM: 'htdocs/popup-forms/check_jvm.php',
	MESSAGE_TYPE_GAME: 'htdocs/popup-forms/show_type_game_message.php',

	SMALL_DESC_GAME: 'htdocs/small_description_game.php',
	PAYMENT_FORM: 'htdocs/show-add-money.php',
	OUT_FORM: 'htdocs/show-out-money.php',
	UPDATE_DATE_SUCCESS: 'htdocs/popup-forms/upd_success.php',
	SHOW_CHANGE_REG: 'htdocs/popup-forms/show-registr-form_big.php',
	SHOW_CHANGE_REG2: 'htdocs/popup-forms/show-registr-form_big2.php'
};

actionURL = {
	AUTH: 'htdocs/script_auth.php',
	RESTORE_PASS: 'htdocs/ajax/send_restore_data.php',
	REGISTER_EMAIL: 'htdocs/ajax/send_reg_data.php',
	EXIST_DESKTOP_ICON: 'htdocs/ajax/exist_desktop_link.php'
};

/**
	 * Show page with sample game
	 **/
function openFullscreen(page) {
	window.location = page;
}

/**
	 * Show page for user add money
	 **/
function upBalance() {
	window.location = 'http://lasvilis.com/test/';
}

/**
	 * Show registration form
	 **/
function showRegisterForm(url, ctg) {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.REGISTER_FORM + '?url=' + url + '&ctg=' + ctg + (SITE_LNG == 3 ? '&lng=3': '&lng=1'), function () {
		$("input[name='login']").focus();
	});
}

function showRegisterFormB(url) {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.REGISTER_FORM_B + '?url=' + url + (SITE_LNG == 3 ? '&lng=3': '&lng=1'), function () {
		//$("input[name='login']").focus();
	});
}

function showMyAccountForm() {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.MY_ACCOUNT, function () {});
}

/**
	 * Show select cash
	 **/
function showSelectCash() {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.SELECT_CASH, function () {});
}
function showen_SelectCash() {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup('htdocs/select_en_kassa_folder.php', function () {});
}

/**
 * Set to desktop our icon
 **/
function showSetDesktopIcon(url) {
	$.ajax({
		type: 'POST',
		url: actionURL.EXIST_DESKTOP_ICON,
		success: function (res) {
			if (res == 1) {
				if (typeof $('#popup').togglePopup != 'function') {
					return;
				}
				$('#popup').togglePopup(formsBackendURL.SET_DESKTOP_ICON + '?url=' + url + (SITE_LNG == 3 ? '&lng=3': '&lng=1'), function () {},
				null, null, null, true);
			} else {
				showSelectTypeGame(url);
			}
		}
	});
}

/**
 * Attention for install Java
 **/
function showCheckJVM(url) {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.CHECK_JVM + '?url=' + url + (SITE_LNG == 3 ? '&lng=3': '&lng=1'), function () {},
	null, null, null, true);
}

/**
 * Attention for install Java
 **/
function showAttentionDesktopIcon(url) {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.ATTENTION_DESKTOP_LINK + '?url=' + url + (SITE_LNG == 3 ? '&lng=3': '&lng=1'), function () {},
	null, null, null, true);
}

/**
	 * Show select type game
	 **/
function showSelectTypeGame(url) {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.SELECT_TYPE_GAME + '?url=' + url, function () {},
	null, null, null, true);
}
function showen_SelectTypeGame(url) {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup('htdocs/popup-forms/select_en_type_game.php' + '?url=' + url, function () {});
}

function changeTypeGame(id_user, type, url) {
	closeRegisterForm();
	//$('#popup_WaitMess').html(SITE_LNG == 3 ? waitingMessageEn: waitingMessage).alignCenter().removeClass('hidden');
	//$('#opaco').height($(document).height()).removeClass('hidden')[$.browser.msie ? 'attr': 'fadeTo']('fast', 0.7);
	var logoutExp = /logout/i;
	if (logoutExp.test(url)) {
		url = '/';
	}
	var pereklyuchatel = 0;
	if (type > 1) {
		pereklyuchatel = 1;
		type = type - 2;
	}

	if (type) {
		// игра на деньги
		$.ajax({
			type: "POST",
			url: "htdocs/ajax/check_user_fill_field.php",
			data: "id_user=" + id_user,
			dataType: "json",
			success: function (data) {
				if (data['ok']) {
					changeTypeGameInner(id_user, type, url, pereklyuchatel);
				} else {
					showFillFieldForm(id_user, type, url);
				}
			}
		});
	} else {
		changeTypeGameInner(id_user, type, url, pereklyuchatel);
	}
}

function changeTypeGameInner(id_user, type, url, pereklyuchatel) {
	$.ajax({
		type: "POST",
		url: "htdocs/ajax/change_type_game.php",
		data: "id_user=" + id_user + "&tg=" + type,
		dataType: "json",
		success: function (data) {
			if (!data) {
				//$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
				//$('#popup_WaitMess').addClass('hidden');

				$('#popup').togglePopup(formsBackendURL.ERROR_REG, function () {
					$('div.errorInReg span.errorMsg').html(SITE_LNG == 3 ? 'Error change type game': 'Ошибка смены типа игры');
				});
			} else if (data['ok']) {
				//$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
				//$('#popup_WaitMess').addClass('hidden');

				if (type) {
					//$('#get_rate').html('<img src="images/get_rate' + (SITE_LNG == 3 ? '_en': '') + '.gif" alt=""/>');

					if (pereklyuchatel) {
						$('#popup').togglePopup(formsBackendURL.MESSAGE_TYPE_GAME, function () {
							window.setTimeout(function () {
								window.location = url;
							},
							2000);
						});
					} else {
						window.location = url;
					}
				} else {
					//$('#get_rate').html('<img src="images/get_rate' + (SITE_LNG == 3 ? '_en': '') + '2.gif" alt=""/>');

					if (pereklyuchatel) {
						$('#popup').togglePopup(formsBackendURL.MESSAGE_TYPE_GAME, function () {
							window.setTimeout(function () {
								window.location = url;
							},
							2000);
						});
					} else {
						window.location = url;
					}
				}

			} else if (data['success']) {
				//$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
				//$('#popup_WaitMess').addClass('hidden');

				if (pereklyuchatel) {
					$('#popup').togglePopup(formsBackendURL.MESSAGE_TYPE_GAME + '?no_change=1', function () {
						window.setTimeout(function () {
							if ($('#popup').hasClass('hidden')) return;

							$('#popup').togglePopup();
							$('#get_rate_btl').blur();
							$('#get_rate_btr').blur();
						},
						2000);
					});
				} else {
					window.location = url;
				}

			} else if (!data['ok']) {
				//$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
				//$('#popup_WaitMess').addClass('hidden');

				$('#popup').togglePopup(formsBackendURL.ERROR_REG, function () {
					$('div.errorInReg span.errorMsg').html(data['msg']);
				});
			}
		}
	});
}

function showFillFieldForm(id_user, type, url) {
	$('#popup').togglePopup(formsBackendURL.REGISTER_FORM_E + '?url=' + url + (SITE_LNG == 3 ? '&lng=3': '&lng=1') + '&type=' + type, function () {
		//$("input[name='login']").focus();
	},
	null, null, null, true);
}

/**
	 * Show auth form
	 **/
function showAuthForm(url, ctg) {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.AUTH_FORM + '?url=' + url + '&ctg=' + ctg + (SITE_LNG == 3 ? '&lng=3': '&lng=1'), function () {
		$("input[name='login']").focus();
		$("input[name='password']").keyup(function (event) {
			if (event.keyCode == 13) {
				sendAuthData(url, ctg);
			}
		});
	});
}

/**
	 * Show forgot password form
	 **/
function showForgotPasswordForm(url) {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.FORGOT_PASS_FORM, function () {
		$("input[name='login']").focus();
		$("input[name='email']").keyup(function (event) {
			if (event.keyCode == 13) {
				sendAuthData(url, ctg);
			}
		});
	});
}

/**
	Show game window
	 **/
function showGameWindow(id_game) {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.SMALL_DESC_GAME + '?idg=' + id_game);
}

/**
	 * Show payment form
	 **/
function showPaymentForm() {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.PAYMENT_FORM);
	window.setTimeout(function () {
		$("input[name='login']").focus();
	},
	250);
}

/**
	 * Show message in cash if user not logged
	 **/
function showNotLogged() {
	alert('Registration required!!!');
}

/**
	 * Show out form
	 **/
function showOutForm() {
	if (typeof $('#popup').togglePopup != 'function') {
		return;
	}
	$('#popup').togglePopup(formsBackendURL.OUT_FORM);
	window.setTimeout(function () {
		$("input[name='login']").focus();
	},
	250);
}

/**
	 * Get payment actions
	 **/
function getPaymentActions() {
	sumCont = $('div.headerBottom-account');
	sumCont.html('Loading...');
	$.ajax({
		type: 'POST',
		url: 'htdocs/get_credits.php',
		success: function (str) {
			sumCont.html(str);
		}
	});
}

/**
	 * Close registration form
	 **/
function closeRegisterForm() {
	$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
	$('#popup').addClass('hidden');
}

/**
	 * Close auth form
	 **/
function closeAuthForm() {
	$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
	$('#popup').addClass('hidden');
}

/**
	 * Close forgot password form
	 **/
function closeForgotPasswordForm() {
	$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
	$('#popup').addClass('hidden');
}

/**
	 * Close Payment form
	 **/
function closePaymentForm() {
	$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
	$('#popup').addClass('hidden');
}

function closePopup() {
	$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
	$('#popup').addClass('hidden');
}

/**
	 * Отправка регистрационной информации
	 **/
function sendRegData(tpe, url, ctg) {
	$("#regForm").ajaxSubmit({
		url: actionURL.AUTH,
		type: "POST",
		dataType: "json",
		success: function (data) {
			if (!data) {
				closeRegisterForm();
				$('#popup').togglePopup(formsBackendURL.ERROR_REG, function () {
					$('div.errorInReg span.errorMsg').html(SITE_LNG == 3 ? 'Error registration': 'Ошибка процедуры регистрации');
				});
			} else if (data['ok']) {
				closeRegisterForm();
				if (tpe) {
					window.location = url;
				} else {
					id_google_str = 'UA-12206503-' + (SITE_LNG == 3 ? '2' : '1');
					trackPV(id_google_str, '/registration_ok/');
					$("#regForm").ajaxSubmit({
						url: actionURL.REGISTER_EMAIL,
						type: "POST",
						dataType: "json",
						success: function (data) {
							showErrorMessage(data);

							$('#popup').togglePopup(formsBackendURL.REGISTER_FORM);
						}
					});
					$('#popup').togglePopup(formsBackendURL.SUCCESS_REG + '?url=' + url + '&ctg=' + ctg);
				}
			} else if (data['success']) {
				closeRegisterForm();
				if (tpe) {
					window.location = url;
				} else {
					$('#popup').togglePopup(formsBackendURL.UPDATE_DATE_SUCCESS);
				}
			} else if (!data['ok']) {
				showErrorMessage(data);
			}
		}
	});
}

/**
 * Дозаполнение регистрационной информации
 **/
function sendFullRegData(url, ctg, type, id_user) {
$("#regForm").ajaxSubmit({
	url: actionURL.AUTH,
	type: "POST",
	dataType: "json",
	success: function (data) {
		if (!data) {
			closeRegisterForm();
			$('#popup').togglePopup(formsBackendURL.ERROR_REG, function () {
				$('div.errorInReg span.errorMsg').html(SITE_LNG == 3 ? 'Error registration': 'Ошибка процедуры регистрации');
			});
		} else if (data['ok'] || data['success']) {
			closeRegisterForm();
			if (id_user) {
				changeTypeGame(id_user, type, url);
			}
		} else if (!data['ok']) {
			showErrorMessage(data);
		}
	}
});
}

/**
 * Дозаполнение регистрационной информации
 **/
function sendFullRegDataSMT(formID, id_user, to) {
$("#regForm").ajaxSubmit({
	url: actionURL.AUTH,
	type: "POST",
	dataType: "json",
	success: function (data) {
		if (!data) {
			closeRegisterForm();
			$('#popup').togglePopup(formsBackendURL.ERROR_REG, function () {
				$('div.errorInReg span.errorMsg').html(SITE_LNG == 3 ? 'Error registration': 'Ошибка процедуры регистрации');
			});
		} else if (data['ok'] || data['success']) {
			closeRegisterForm();
			if (id_user) {
				sendMoneyTo(formID, id_user, to);
			}
		} else if (!data['ok']) {
			showErrorMessage(data);
		}
	}
});
}

/**
 * Отправка аутентификационной информации
 **/
function sendAuthData(url, ctg) {
	if (!window.buzy) {
		buzy = true;
	} else {
		return;
	}

	closeAuthForm();

	$('#opaco').height($(document).height())[$.browser.msie ? 'attr': 'fadeTo']('fast', 0.7).removeClass('hidden');
	$("#authForm").ajaxSubmit({
		url: actionURL.AUTH,
		type: "POST",
		dataType: "json",
		beforeSubmit: function () {
			$('#popup').html(SITE_LNG == 3 ? waitingMessageEn: waitingMessage).alignCenter().removeClass('hidden');
		},
		success: function (data) {
			$('#popup').addClass('hidden');
			if (!data) {
				$('#popup').togglePopup(formsBackendURL.ERROR_REG);
			} else if (data['ok']) {
				if (data['msg']) {
					$('#popup').togglePopup(formsBackendURL.SHOW_CHANGE_REG2 + '?url=' + url + '&ctg=' + ctg, function () {
						$('div.errorInReg span.errorMsg').html('<span style="color:red; display:block; text-align:left; margin:20px; background-color:#fff; padding:10px; ">' + '- ' + data['msg'] + '</span>');
						$("input[name='login']").focus();
					},
					null, null, function () {},
					true);
				} else {
					$(document).trigger('LV_auth_getData', data);
					if (ctg) {
						if (ctg > 1) {
							switch (parseInt(ctg, 10)) {
							case 2:
								changeTypeGame(0, 1, url);
								break;
							case 3:
								changeTypeGame(0, 0, url);
								break;
							case 1000:
								// просто закрываем диалог
								closeRegisterForm();
								break;
							}
						} else {
							window.location = url;
						}
					} else {
	                	showSetDesktopIcon(url);
					}
				}
			} else if (!data['ok']) {
				window.errorstr = data['msg'] + '<br /><br />';
				$('#popup').togglePopup(formsBackendURL.AUTH_FORM + '?url=' + url + '&ctg=' + ctg + (SITE_LNG == 3 ? '&lng=3': '&lng=1'), function () {
					$('div.errorInReg span.errorMsg').html(errorstr);
					$("input[name='login']").focus();
					$("input[name='password']").keyup(function (event) {
						if (event.keyCode == 13) {
							sendAuthData(url, ctg);
						}
					});
				});
			}
			buzy = false;
		}
	});
}

/**
	 * Восстановление пароля
	 * @return {Boolean}
	 */
function sendRestorePassData() {
	$("#restoreForm").ajaxSubmit({
		url: 'htdocs/ajax/send_restore_data.php',
		type: "POST",
		dataType: "json",
		success: function (data) {
			closeForgotPasswordForm();

			$('#popup').togglePopup(formsBackendURL.RESTORE_PASS_FORM);
		}
	});

	return false;
}

/**
	 * Отправка письма с регистрацией
	 * @return {Boolean}
	 */
function runRegistration2() {
	$("#regForm").ajaxSubmit({
		url: actionURL.REGISTER_EMAIL,
		type: "POST",
		dataType: "json",
		success: function (data) {
			closeRegisterForm();

			$('#popup').togglePopup(formsBackendURL.REGISTER_FORM);
		}
	});

	return false;
}

/**
	 * Разлогирование пользователя
	 **/
function logOut() {
	$('#popup').html(SITE_LNG == 3 ? waitingMessageEn: waitingMessage).alignCenter().removeClass('hidden');
	$('#opaco').height($(document).height())[$.browser.msie ? 'attr': 'fadeTo']('fast', 0.7).removeClass('hidden');

	$.ajax({
		type: "POST",
		url: "htdocs/logout.php",
		success: function (msg) {
			window.location = '/';
		}
	});
}

function _en_logOut() {
	$('#popup').html(waitingMessageEn).alignCenter().removeClass('hidden');
	$('#opaco').height($(document).height())[$.browser.msie ? 'attr': 'fadeTo']('fast', 0.7).removeClass('hidden');

	$.ajax({
		type: "POST",
		url: "htdocs/logout.php",
		success: function (msg) {
			window.location = '/en/';
		}
	});
}

function getCookie(c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return "";
}

function setCookie(c_name, value, expiredays, path, domain, secure) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) + ((expiredays) ? ";expires=" + exdate.toGMTString() : "") + ((path) ? ";path=" + path + ";": "") + +((domain) ? ";domain=" + domain + ";": "") + +((secure) ? ";secure": "");
}

function deleteCookie(c_name, path, domain) {
	if (getCookie(c_name)) document.cookie = name + "=" + ((path) ? ";path=" + path: "") + ((domain) ? ";domain=" + domain: "") + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/**
 * Google analitics
 *
 * @param trackerCode
 * @param url
 */
function trackPV(trackerCode, url) {
	if (typeof _gat === 'undefined') return;

	var tracker = _gat._getTracker(trackerCode);
	if (url) {
		tracker._trackPageview(url);
	} else {
		tracker._trackPageview();
	}
}

function SelectOperationFolder(id_top, lng_str) {
	$("#top_navigation_1").removeClass("cash_in_button" + lng_str + "_on");
	$("#top_navigation_1").removeClass("cash_in_button" + lng_str);
	$("#top_navigation_2").removeClass("cash_out_button" + lng_str + "_on");
	$("#top_navigation_2").removeClass("cash_out_button" + lng_str);
	$("#top_navigation_3").removeClass("history_button" + lng_str + "_on");
	$("#top_navigation_3").removeClass("history_button" + lng_str);
	switch (id_top) {
	case 1:
		$("#contform").removeClass("containerFormBig");
		$("#contform").addClass("containerForm");
		$("#top_navigation_1").addClass("cash_in_button" + lng_str + "_on");
		$("#top_navigation_2").addClass("cash_out_button" + lng_str);
		$("#top_navigation_3").addClass("history_button" + lng_str);
		break;
	case 2:
		$("#contform").removeClass("containerFormBig");
		$("#contform").addClass("containerForm");
		$("#top_navigation_1").addClass("cash_in_button" + lng_str);
		$("#top_navigation_2").addClass("cash_out_button" + lng_str + "_on");
		$("#top_navigation_3").addClass("history_button" + lng_str);
		break;
	case 3:
		$("#contform").removeClass("containerForm");
		$("#contform").addClass("containerFormBig");
		$("#top_navigation_1").addClass("cash_in_button" + lng_str);
		$("#top_navigation_2").addClass("cash_out_button" + lng_str);
		$("#top_navigation_3").addClass("history_button" + lng_str + "_on");
		break;
	}
}

function showPaymentSystemPage(idOper, idPSystem, idLng, params) {
	if (idLng == '_') {
		if ($("#top_navigation_1").hasClass("cash_in_button") || $("#top_navigation_1").hasClass("cash_in_button_on")) {
			idLng = 1;
			lng_str = '';
		} else {
			idLng = 3;
			lng_str = '_en';
		}
	} else {
		if (idLng == 1) {
			lng_str = '';
		} else {
			lng_str = '_en';
		}
	}

	var params = params || {},
	dataStr = "id_operation=" + idOper + "&id_pay_system=" + idPSystem + "&lng=" + idLng;

	for (var k in params) {
		dataStr += "&" + k + "=" + params[k];
	}

	$("#contform").html('<div class="form"><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>&nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; &nbsp;&nbsp; </div>');

	SelectOperationFolder(idOper, lng_str);

	setCookie('payment_form_top', idOper, 7, '/', '', '');
	setCookie('payment_form_left', idPSystem, 7, '/', '', '');

	$.ajax({
		type: "GET",
		url: "htdocs/ajax/get_payment_system_page_serv.php",
		data: dataStr,
		success: function (html) {
			$("#servform").html(html);
			setHidPic('#servform', true);
		}
	});

	$.ajax({
		type: "GET",
		url: "htdocs/ajax/get_payment_system_page_serv_right.php",
		data: dataStr,
		success: function (html) {
			$("#services_right").html(html);
			setHidPic('#services_right', false);
		}
	});

	$.ajax({
		type: "GET",
		url: "htdocs/ajax/get_payment_system_page_cont.php",
		data: dataStr,
		success: function (html) {
			$("#contform").html(html);
		}
	});
}

function showHistoryPage(idTypeGame, idGame, idLng, params) {
	$("#hbform").html(idLng == 3 ? 'Loading. Please wait...': 'Данные загружаются. Пожалуйста, подождите...');

	var params = params || {},
	dataStr = "id_type_game=" + idTypeGame + "&id_game=" + idGame + "&lng=" + idLng;

	for (var k in params) {
		dataStr += "&" + k + "=" + params[k];
	}

	$.ajax({
		type: "GET",
		url: "htdocs/ajax/get_history_game.php",
		data: dataStr,
		success: function (html) {
			$("#hbform").html(html);
		}
	});
}

function gotoKassaFolder(id_top, id_left, lng) {
	if (id_left > 0) {
		setCookie('payment_form_left', id_left, 7, '/', '', '');
	} else {
		if (parseInt(getCookie('payment_form_top')) != id_top) {
			setCookie('payment_form_left', 1, 7, '/', '', '');
		}
	}
	setCookie('payment_form_top', id_top, 7, '/', '', '');
	window.location = (lng ? '/' + lng: '') + '/cash/#rol';
}

/**
	 * For non logged users
	 */
function payForNotLogged(method, formID) {
	$(document).one('LV_auth_getData', function (e, data) {
		if (!isNaN(parseInt(data.uID, 10)) && parseInt(data.uID, 10) !== 0) {
			window[method](formID, data.uID);
		}
	});

	$(document).one('LV_sumError', function () {
		window.location.reload(true);
	});
	showAuthForm("", 0);
}

/**
	 * sendMoneyTo
	 *
	 * @param {string} formID
	 * @param {int} id_user
	 * @param (string) to
	 */
function sendMoneyTo(formID, id_user, to) {
	// игра на деньги
	$.ajax({
		type: "POST",
		url: "htdocs/ajax/check_user_fill_field.php",
		data: "id_user=" + id_user,
		dataType: "json",
		success: function (data) {
			if (data['ok']) {
				switch(to) {
					case 'INTERKASSA':
						sendMoneyToINTERKASSA(formID, id_user);
						break;
					case 'WEBMONEY':
						sendMoneyToWEBMONEY(formID, id_user);
						break;
					case 'MONETA':
						sendMoneyToMONETA(formID, id_user);
						break;
					case 'SOFORT':
						sendMoneyToSOFORT(formID, id_user);
						break;
					case 'MONEYBOOKERS':
						sendMoneyToMONEYBOOKERS(formID, id_user);
						break;
					case 'LIQPAY':
						sendMoneyToLIQPAY(formID, id_user);
						break;
					case 'VIRTUPAY':
						sendMoneyToVIRTUPAY(formID, id_user);
						break;
					case 'BALTICBILL':
						sendMoneyToBALTICBILL(formID, id_user);
						break;
					case 'UKASH':
						sendMoneyToUKASH(formID, id_user);
						break;
					case 'NETELLER':
						sendMoneyToNETELLER(formID, id_user);
						break;
					case 'ROBOKASSA':
						sendMoneyToROBOKASSA(formID, id_user);
						break;
					case 'NETPAY':
						sendMoneyToNETPAY(formID, id_user);
						break;
					case 'CLICK2PAY':
						sendMoneyToCLICK2PAY(formID, id_user);
						break;
					case 'ECOCARD':
						sendMoneyToECOCARD(formID, id_user);
						break;
				}
			} else {
				showFillFieldFormSMT(formID, id_user, to);
			}
		}
	});
}

function showFillFieldFormSMT(formID, id_user, to) {
	$('#popup').togglePopup(formsBackendURL.REGISTER_FORM_SMT + '?to=' + to + (SITE_LNG == 3 ? '&lng=3': '&lng=1') + '&formid=' + formID, function () {
		//$("input[name='login']").focus();
	},
	null, null, null, true);
}

/**
	 * sendMoneyToINTERKASSA
	 *
	 * @param {string} formID
	 * @param {int} id_user
	 */
function sendMoneyToINTERKASSA(formID, id_user) {
	var sum = $("#" + formID + " input[name='ik_payment_amount']").val(),
	psum = parseFloat(sum);

	if (isNaN(psum) || psum < 1) {
		alert(SITE_LNG == 3 ? "The minimum amount of input is $1!": "Минимальная сумма для ввода составляет $1!");
		$(document).trigger("LV_sumError");
		return;
	} else if (psum >= 5000) {
		alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
		$(document).trigger("LV_sumError");
		return;
	}

	$.ajax({
		type: "POST",
		url: "htdocs/ajax/create_new_order.php",
		data: "id_user=" + id_user + "&sum=" + sum + "&ps=interkassa_int",
		success: function (msg) {
			$("#" + formID + " input[name='ik_payment_id']").val(parseInt(msg, 10));
			$("#" + formID + " input[name='ik_payment_desc']").val("Payment by sum " + psum);

			$("#" + formID).get(0).submit();
		}
	});

}

/**
	 * sendMoneyToWEBMONEY
	 *
	 * @param {string} formID
	 * @param {int} id_user
	 */
function sendMoneyToWEBMONEY(formID, id_user) {
	var sum = $("#" + formID + " input[name='LMI_PAYMENT_AMOUNT']").val(),
	psum = parseFloat(sum);

	if (isNaN(psum) || psum < 1) {
		alert(SITE_LNG == 3 ? "The minimum amount of input is $1!": "Минимальная сумма для ввода составляет $1!");
		$(document).trigger("LV_sumError");
		return;
	} else if (psum >= 5000) {
		alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
		$(document).trigger("LV_sumError");
		return;
	}
	
	$.ajax({
		type: "POST",
		url: "htdocs/ajax/create_new_order.php",
		data: "id_user=" + id_user + "&sum=" + sum + "&ps=web_money_int",
		success: function (msg) {
			$("#" + formID + " input[name='LMI_PAYMENT_NO']").val(parseInt(msg, 10));
			$("#" + formID + " input[name='LMI_PAYMENT_DESC']").val("Payment by sum $" + psum + " order_id:" + parseInt(msg, 10) + " account_id:" + id_user);

			$("#" + formID).get(0).submit();
		}
	});

}

/**
	 * sendMoneyToMONETA
	 *
	 * @param {string} formID
	 * @param {int} id_user
	 */
function sendMoneyToMONETA(formID, id_user) {
	var sum = $("#" + formID + " input[name='MNT_AMOUNT']").val(),
	psum = parseFloat(sum);

	if (isNaN(psum) || psum < 1) {
		alert(SITE_LNG == 3 ? "The minimum amount of input is $1!": "Минимальная сумма для ввода составляет $1!");
		$(document).trigger("LV_sumError");
		return;
	} else if (psum >= 5000) {
		alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
		$(document).trigger("LV_sumError");
		return;
	}

	$.ajax({
		type: "POST",
		url: "htdocs/ajax/create_new_order.php",
		data: "id_user=" + id_user + "&sum=" + sum + "&ps=moneta_int",
		success: function (msg) {
			$("#" + formID + " input[name='MNT_TRANSACTION_ID']").val(parseInt(msg, 10));
			$("#" + formID + " input[name='MNT_DESCRIPTION']").val("Payment by sum $" + psum + " order_id:" + parseInt(msg, 10) + " account_id:" + id_user);

			$("#" + formID).get(0).submit();
		}
	});

}

function sendMoneyToSOFORT(formID, id_user) {
	var sum = $("#" + formID + " input[name='amount']").val(),
	psum = parseFloat(sum);

	if (isNaN(psum) || psum < 1) {
		alert(SITE_LNG == 3 ? "The minimum amount of input is $1!": "Минимальная сумма для ввода составляет $1!");
		$(document).trigger("LV_sumError");
		return;
	} else if (psum >= 5000) {
		alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
		$(document).trigger("LV_sumError");
		return;
	}

	$.ajax({
		type: "POST",
		url: "htdocs/ajax/create_new_order.php",
		data: "id_user=" + id_user + "&sum=" + sum + "&ps=sofort_int",
		success: function (msg) {
//		alert('transaktionId='+parseInt(msg, 10)+', '+'desc:'+"Payment by sum $" + psum + " order_id:" + parseInt(msg, 10) + " account_id:" + id_user);
			$("#" + formID + " input[name='user_variable_0']").val(parseInt(msg, 10));
			$("#" + formID + " input[name='user_variable_1']").val("Payment by sum $" + psum + " order_id:" + parseInt(msg, 10) + " account_id:" + id_user);

			$("#" + formID).get(0).submit();
		}
	});

}

/**
 * sendMoneyToROBOKASSA
 *
 * @param {string} formID
 * @param {int} id_user
 */
function sendMoneyToROBOKASSA(formID, id_user) {
var sum = $("#" + formID + " input[name='OutSum']").val(),
psum = parseFloat(sum);

if (isNaN(psum) || psum < 1) {
	alert(SITE_LNG == 3 ? "The minimum amount of input is $1!": "Минимальная сумма для ввода составляет $1!");
	$(document).trigger("LV_sumError");
	return;
} else if (psum >= 5000) {
	alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
	$(document).trigger("LV_sumError");
	return;
}

$.ajax({
	type: "POST",
	url: "htdocs/ajax/create_new_order_rk.php",
	data: "id_user=" + id_user + "&sum=" + sum + "&ps=robokassa_int",
	success: function (msg) {
		window.location = msg;
	}
});

}

/**
 * sendMoneyToNETPAY
 *
 * @param {string} formID
 * @param {int} id_user
 */
function sendMoneyToNETPAY(formID, id_user) {
var sum = $("#" + formID + " input[name='trans_amount']").val(),
psum = parseFloat(sum);

if (isNaN(psum) || psum < 10) {
	alert(SITE_LNG == 3 ? "The minimum amount of input is $10!": "Минимальная сумма для ввода составляет $10!");
	$(document).trigger("LV_sumError");
	return;
} else if (psum >= 5000) {
	alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
	$(document).trigger("LV_sumError");
	return;
}

$.ajax({
	type: "POST",
	url: "htdocs/ajax/create_new_order_np.php",
	data: "id_user=" + id_user + "&sum=" + sum + "&ps=netpay_int",
	success: function (msg) {
		window.location = msg;
	}
});

}

/**
	 * sendMoneyToWEBMONEY
	 *
	 * @param {string} formID
	 * @param {int} id_user
	 */
function sendMoneyToMONEYBOOKERS(formID, id_user) {
	var sum = $("#" + formID + " input[name='amount']").val(),
	psum = parseFloat(sum);

	if (isNaN(psum) || psum < 10) {
		alert(SITE_LNG == 3 ? "The minimum amount of input is $10!": "Минимальная сумма для ввода составляет $10!");
		$(document).trigger("LV_sumError");
		return;
	} else if (psum >= 5000) {
		alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
		$(document).trigger("LV_sumError");
		return;
	}

	$.ajax({
		type: "POST",
		url: "htdocs/ajax/create_new_order.php",
		data: "id_user=" + id_user + "&sum=" + sum + "&ps=moneybookers_int",
		success: function (msg) {
			$("#" + formID + " input[name='transaction_id']").val(parseInt(msg, 10));
			$("#" + formID + " input[name='detail1_text']").val(parseInt(msg, 10));
			$("#" + formID + " input[name='detail1_description']").val("Payment by sum $" + psum + " order_id:" + parseInt(msg, 10) + " account_id:" + id_user);

			$("#" + formID).get(0).submit();
		}
	});

}

/**
	 * sendMoneyToLIQPAY
	 *
	 * @param {string} formID
	 * @param {int} id_user
	 */
function sendMoneyToLIQPAY(formID, id_user) {
	var sum = $("#" + formID + " input[name='amount']").val(),
	domen = $("#" + formID + " input[name='domen']").val(),
	psum = parseFloat(sum);

	if (isNaN(psum) || psum < 1) {
		alert(SITE_LNG == 3 ? "The minimum amount of input is $1!": "Минимальная сумма для ввода составляет $1!");
		$(document).trigger("LV_sumError");
		return;
	} else if (psum >= 5000) {
		alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
		$(document).trigger("LV_sumError");
		return;
	}

	$.ajax({
		type: "POST",
		url: "htdocs/ajax/create_new_order_lp.php",
		data: "id_user=" + id_user + "&dom=" + domen + "&sum=" + psum + "&ps=liqpay_int",
		dataType: "json",
		success: function (data) {
			$("#" + formID + " input[name='operation_xml']").val(data['xml']);
			$("#" + formID + " input[name='signature']").val(data['sign']);

			$("#" + formID).get(0).submit();
		}
	});

}

/**
	 * sendMoneyToUKASH
	 *
	 * @param {string} formID
	 * @param {int} id_user
	 */
function sendMoneyToUKASH(formID, id_user) {
	var voucher_amount = $("#" + formID + " input[name='voucher_amount']").val(),
	voucher_number = $("#" + formID + " input[name='voucher_number']").val(),
	psum = parseFloat(voucher_amount);

	if (isNaN(psum) || psum < 5) {
		alert(SITE_LNG == 3 ? "The minimum amount of voucher amount is $5!": "Минимальная сумма для ввода ваучера составляет $5!");
		$(document).trigger("LV_sumError");
		return;
	} else if (psum >= 750) {
		alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $750!": "Сумма для ввода не должна превышать $750!");
		$(document).trigger("LV_sumError");
		return;
	}

	$('#opaco').height($(document).height()).removeClass('hidden')[$.browser.msie ? 'attr': 'fadeTo']('fast', 0.7);
	$('#popup_WaitMess').html(SITE_LNG == 3 ? waitingMessageEn: waitingMessage).alignCenter().removeClass('hidden');

	$.ajax({
		type: "POST",
		url: "htdocs/ajax/create_new_order_uk.php",
		data: "id_user=" + id_user + "&sum=" + psum + "&number=" + voucher_number + "&ps=ukash_int",
		dataType: "json",
		success: function (data) {

			$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
			$('#popup_WaitMess').addClass('hidden');

			if (!data) {
				$('#popup').togglePopup(formsBackendURL.ERROR_REG);
			} else if (data['ok']) {
				window.location = data['url'];
			} else {
				$('#error'+(SITE_LNG == 3 ? '_en' : '')+'_uk_message').html(SITE_LNG == 3 ? 'Payment will not  be held. Reason: ' + data['message'] : 'Платеж не проводен. Причина: ' + data['message']).removeClass('hidden');
			}
		}
	});

}

/**
	 * sendMoneyToECOCARD
	 *
	 * @param {string} formID
	 * @param {int} id_user
	 */
function sendMoneyToECOCARD(formID, id_user) {
	var amount = $("#" + formID + " input[name='Amount']").val(),
	    accountnumber = $("#" + formID + " input[name='ClientAccountNumberAtMerchant']").val(),
	psum = parseFloat(amount);

	if (isNaN(psum) || psum < 5) {
		alert(SITE_LNG == 3 ? "The minimum amount of voucher amount is $5!": "Минимальная сумма для ввода ваучера составляет $5!");
		$(document).trigger("LV_sumError");
		return;
	} else if (psum >= 750) {
		alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $750!": "Сумма для ввода не должна превышать $750!");
		$(document).trigger("LV_sumError");
		return;
	}

	$('#opaco').height($(document).height()).removeClass('hidden')[$.browser.msie ? 'attr': 'fadeTo']('fast', 0.7);
	$('#popup_WaitMess').html(SITE_LNG == 3 ? waitingMessageEn: waitingMessage).alignCenter().removeClass('hidden');

	$.ajax({
		type: "POST",
		url: "htdocs/ajax/create_new_order_eco.php",
		data: "id_user=" + id_user + "&sum=" + psum + "&number=" + accountnumber + "&ps=ecocard_int",
		dataType: "json",
		success: function (data) {

			$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
			$('#popup_WaitMess').addClass('hidden');

			if (!data) {
				$('#popup').togglePopup(formsBackendURL.ERROR_REG);
			} else if (data['ok']) {
				window.location = data['url'];
			} else {
				$('#error'+(SITE_LNG == 3 ? '_en' : '')+'_uk_message').html(SITE_LNG == 3 ? 'Payment will not  be held. Reason: ' + data['message'] : 'Платеж не проводен. Причина: ' + data['message']).removeClass('hidden');
			}
		}
	});

}

/**
 * sendMoneyToCLICK2PAY
 *
 * @param {string} formID
 * @param {int} id_user
 */
function sendMoneyToCLICK2PAY(formID, id_user) {
var amount = $("#" + formID + " input[name='amount']").val(),
    accid = $("#" + formID + " input[name='net_account']").val(),
    pan = $("#" + formID + " input[name='pan']").val(),
    psum = parseFloat(amount);

if (isNaN(psum) || psum < 10) {
	alert(SITE_LNG == 3 ? "The minimum amount deposit amount is $10!": "Минимальная сумма пополнения счета составляет $10!");
	$(document).trigger("LV_sumError");
	return;
} else if (psum >= 5000) {
	alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
	$(document).trigger("LV_sumError");
	return;
}

$('#opaco').height($(document).height()).removeClass('hidden')[$.browser.msie ? 'attr': 'fadeTo']('fast', 0.7);
$('#popup_WaitMess').html(SITE_LNG == 3 ? waitingMessageEn: waitingMessage).alignCenter().removeClass('hidden');

$.ajax({
	type: "POST",
	url: "htdocs/ajax/create_new_order_cp.php",
	data: "id_user=" + id_user + "&sum=" + psum + "&accid=" + accid + "&pan=" + pan + "&ps=click2pay_int",
	dataType: "json",
	success: function (data) {

		$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
		$('#popup_WaitMess').addClass('hidden');

		if (!data) {
			$('#popup').togglePopup(formsBackendURL.ERROR_REG);
		} else if (data['ok']) {
			window.location = data['url'];
		} else {
			$('#error'+(SITE_LNG == 3 ? '_en' : '')+'_cp_message').html(SITE_LNG == 3 ? 'Payment will not  be held. Reason: ' + data['message'] : 'Платеж не проведен. Причина: ' + data['message']).removeClass('hidden');
		}
	}
});

}

/**
 * sendMoneyToLIQPAY
 *
 * @param {string} formID
 * @param {int} id_user
 */
function sendMoneyToNETELLER(formID, id_user) {
var  sum     = $("#" + formID + " input[name='amount']").val(),
     net_acc = $("#" + formID + " input[name='net_account']").val(),
     sec_id  = $("#" + formID + " input[name='secure_id']").val(),
     psum    = parseFloat(sum);

if (isNaN(psum) || psum < 10) {
	alert(SITE_LNG == 3 ? "The minimum amount of input is $10!": "Минимальная сумма для ввода составляет $10!");
	$(document).trigger("LV_sumError");
	return;
} else if (psum >= 5000) {
	alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
	$(document).trigger("LV_sumError");
	return;
}

$.ajax({
	type: "POST",
	url: "htdocs/ajax/create_new_order_nl.php",
	data: "id_user=" + id_user + "&acc=" + net_acc + "&sum=" + psum + "&sec=" + sec_id + "&ps=neteller_int",
	dataType: "json",
	success: function (data) {
		///alert(data['message']);
		$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
		$('#popup_WaitMess').addClass('hidden');

		if (!data) {
			$('#popup').togglePopup(formsBackendURL.ERROR_REG);
		} else if (data['ok']) {
			window.location = data['url'];
		} else {
			$('#error'+(SITE_LNG == 3 ? '_en' : '')+'_nl_message').html(SITE_LNG == 3 ? 'Payment will not  be held. Reason: ' + data['message'] : 'Платеж не проводен. Причина: ' + data['message']).removeClass('hidden');
		}
	}
});

}

/**
	 * sendMoneyToVIRTUPAY
	 *
	 * @param {string} formID
	 * @param {int} id_user
	 */
function sendMoneyToVIRTUPAY(formID, id_user) {
	var sum = $("#" + formID + " input[name='inner_amount']").val(),
	psum = parseFloat(sum);

	if (isNaN(psum) || psum < 1) {
		alert(SITE_LNG == 3 ? "The minimum amount of input is $1!": "Минимальная сумма для ввода составляет $1!");
		$(document).trigger("LV_sumError");
		return;
	} else if (psum >= 5000) {
		alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
		$(document).trigger("LV_sumError");
		return;
	}

	$.ajax({
		type: "POST",
		url: "htdocs/ajax/create_new_order_vp.php",
		data: "id_user=" + id_user + "&sum=" + sum + "&ps=virtupay_int",
		success: function (msg) {
			var res = eval("(" + msg + ")");
			$("#" + formID + " input[name='transaction_id']").val(parseInt(res.id_order, 10));
			$("#" + formID + " input[name='description']").val("Payment by sum " + parseFloat(sum));
			$("#" + formID + " input[name='amount']").val(parseFloat(sum * 100));
			$("#" + formID + " input[name='token']").val(res.token);

			$("#" + formID).get(0).submit();
		}
	});

}

/**
	 * sendMoneyToBALTICBILL
	 *
	 * @param {string} formID
	 * @param {int} id_user
	 */
function sendMoneyToBALTICBILL(formID, id_user) {
	var sum = $("#" + formID + " input[name='inner_amount']").val(),
	psum = parseFloat(sum);

	if (isNaN(psum) || psum < 10) {
		alert(SITE_LNG == 3 ? "The minimum amount of input is $10!": "Минимальная сумма для ввода составляет $10!");
		$(document).trigger("LV_sumError");
		return;
	} else if (psum >= 5000) {
		alert(SITE_LNG == 3 ? "The maximum amount of input must not exceed $5000!": "Сумма для ввода не должна превышать $5000!");
		$(document).trigger("LV_sumError");
		return;
	}

	$.ajax({
		type: "POST",
		url: "htdocs/ajax/create_new_order_bb.php",
		data: "id_user=" + id_user + "&sum=" + sum + "&ps=baltic_bill_int",
		success: function (msg) {
			var res = eval("(" + msg + ")");
			$("#" + formID + " input[name='MerchantReference']").val(parseInt(res.id_order, 10));
			$("#" + formID + " input[name='ItemDesc[0]']").val("Payment by sum " + parseFloat(sum));
			$("#" + formID + " input[name='AmountTotal']").val(parseFloat(sum));
			$("#" + formID + " input[name='ItemAmount[0]']").val(parseFloat(sum));

			$("#" + formID).get(0).submit();
		}
	});

}

/**
	 * For non logged users
	 */
function outMoneyForNotLogged(formID, SITE_URL, type_pay_system) {
	$(document).one('LV_auth_getData', function (e, data) {
		if (!isNaN(parseInt(data.uID, 10)) && parseInt(data.uID, 10) !== 0) {
			requestOutMoney(formID, data.uID, SITE_URL, type_pay_system)
		}
	});

	$(document).one('LV_sumError', function () {
		window.location.reload(true);
	});
	showAuthForm("", 1000);
}

/**
	 * requestOutMoney
	 *
	 * @param {string} formID
	 * @param {int} id_user
	 * @param {string} SITE_URL
	 */
function requestOutMoney(formID, id_user, SITE_URL, type_pay_system) {
	var sum = $("#" + formID + " input[name='payment_amount']").val(),
	account_info = $("#" + formID + " input[name='account_info']").val(),
	balance = $("#" + formID + " input[name='balance']").val();

	if (isNaN(parseFloat(sum)) || (parseFloat(sum) < 10 && !(type_pay_system == 14 || type_pay_system == 21 || type_pay_system == 29))) {
		$('#disp_error_data').html(SITE_LNG == 3 ? "The minimum amount for withdrawal is $10!": "Минимальная сумма для снятия составляет $10!");
		//alert(SITE_LNG == 3 ? "The minimum amount for withdrawal is $10!": "Минимальная сумма для снятия составляет $10!");
		$(document).trigger("LV_sumError");
		return;
	} else if (parseFloat(sum) < 100 && type_pay_system == 14) {
			$('#disp_error_data').html(SITE_LNG == 3 ? "The minimum amount for withdrawal is $100!": "Минимальная сумма для снятия составляет $100!");
			//alert(SITE_LNG == 3 ? "The minimum amount for withdrawal is $10!": "Минимальная сумма для снятия составляет $10!");
			$(document).trigger("LV_sumError");
			return;
	} else if (parseFloat(sum) < 20 && (type_pay_system == 21 || type_pay_system == 29)) {
		$('#disp_error_data').html(SITE_LNG == 3 ? "The minimum amount for withdrawal is $20!": "Минимальная сумма для снятия составляет $20!");
		//alert(SITE_LNG == 3 ? "The minimum amount for withdrawal is $10!": "Минимальная сумма для снятия составляет $10!");
		$(document).trigger("LV_sumError");
		return;
	}
	if (parseFloat(balance) < parseFloat(sum)) {
		$('#disp_error_data').html(SITE_LNG == 3 ? "The amount for the withdrawal exceeds the available!": "Сумма для снятия превышает доступную!");
		//alert(SITE_LNG == 3 ? "The amount for the withdrawal exceeds the available!": "Сумма для снятия превышает доступную!");
		$(document).trigger("LV_sumError");
		return;
	}
	
	if (type_pay_system == 29) {
		if (parseFloat(sum) > 2500) {
			$('#disp_error_data').html(SITE_LNG == 3 ? "The maximum amount for withdrawal is $2500!": "Максимальная сумма для снятия составляет $2500!");
			//alert(SITE_LNG == 3 ? "The minimum amount for withdrawal is $10!": "Минимальная сумма для снятия составляет $10!");
			$(document).trigger("LV_sumError");
			return;
		}
		var reg = /^(\d){16}$/;
		if (!reg.test(account_info)) {	
			$('#disp_error_data').html(SITE_LNG == 3 ? "Enter 16 digit number of the card!": "Введите 16-ти значный номер, указанный на лицевой стороне карты!");
			//alert(SITE_LNG == 3 ? "The format of the purse is not valid!": "Формат кошелька не верен!");
			$(document).trigger("LV_sumError");
			return;
		}
	}

	if (type_pay_system == 1) {
		var reg = /[zZ]*(\d){12}/;
		if (!reg.test(account_info)) {	
			$('#disp_error_data').html(SITE_LNG == 3 ? "The format of the purse is not valid!": "Формат кошелька не верен!");
			//alert(SITE_LNG == 3 ? "The format of the purse is not valid!": "Формат кошелька не верен!");
			$(document).trigger("LV_sumError");
			return;
		}
	}

	if (type_pay_system == 11) {
		var reg = /^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i;
		if (!reg.test(account_info)) {	
			$('#disp_error_data').html(SITE_LNG == 3 ? "Not a true format email addresses!": "Не верный формат email адреса!");
			//alert(SITE_LNG == 3 ? "The format of the purse is not valid!": "Формат кошелька не верен!");
			$(document).trigger("LV_sumError");
			return;
		}
	}

	if (type_pay_system == 14) {
		name_user_score = $("#" + formID + " input[name='name_user_score']").val();
		country = $("#" + formID + " input[name='country']").val();
		bank_name = $("#" + formID + " input[name='bank_name']").val();
		adress_bank = $("#" + formID + " input[name='adress_bank']").val();
		swift = $("#" + formID + " input[name='swift']").val();
		iban = $("#" + formID + " input[name='iban']").val();

		if (name_user_score === "" || name_user_score === null || country === "" || country === null || bank_name === "" || bank_name === null || adress_bank === "" || adress_bank === null || swift === "" || swift === null || iban === "" || iban === null) {
			$('#disp_error_data').html(SITE_LNG == 3 ? "Fill all fields!": "Заполните все поля!");
			//alert(SITE_LNG == 3 ? "Fill all fields!": "Заполните все поля!");
			return;
		}

		ext_url = "&nus=" + name_user_score + "&country=" + country + "&bank_name=" + bank_name + "&adress_bank=" + adress_bank + "&swift=" + swift + "&iban=" + iban;
	} else {
		ext_url = "";
	}

	$.ajax({
		type: "POST",
		url: "htdocs/ajax/request_out_money.php",
		data: "id_user=" + id_user + "&sum=" + sum + "&lng=" + SITE_LNG + "&type_pay_system=" + type_pay_system + "&account_info=" + account_info + ext_url,
		success: function (msg) {
			if (parseInt(msg, 10) == 2) {
				$('#disp_error_data').html(SITE_LNG == 3 ? "The conclusion of means is in this respect impossible, as from it the deposit hasn't been made" : "Вывод средств на этот счет невозможен, так как с него не был сделан депозит");
			}
			if (parseInt(msg, 10) == 11) {
				window.location = SITE_URL + "/info_page/";
			}
		}
	});

}

/**
	 * Поле ввода суммы
	 * @param {jQuery Object} jq_el
	 */
function setSumFieldBehavior(jq_el) {
	if (jq_el.length) {
		jq_el.bind('keypress', function (e) {
			var code = e.charCode || e.keyCode || e.which;

			if ((code < 48 || code > 57) && (code != 9 && code != 13 && code != 8 && code != 44 && code != 46)) {
				return false;
			}

			return true;
		}).bind('keyup blur', _replaceDot);
	}
}

function _replaceDot(e) {
	var target = e.target,
	val = target.value + '',
	new_val = "";

	val = val.replace(",", ".");

	// уберем дубляжи точек
	for (var i = 0, len = val.length, f = false; i < len; i++) {
		var curval = val.substring(i, i + 1);
		if (!f && curval === '.') {
			f = true;
			new_val += curval;
		} else if (curval === '.') {

} else {
			new_val += curval;
		}
	}

	target.value = new_val;
}

/**
	 * Запуск по загрузке страницы
	 */

$(document).ready(function () {

	/**
		 * Расширение jQuery для всплывающих окошек
		 */
	$.fn.alignCenter = function (width, height) {
		var marginLeft = width ? ( - width / 2 + 'px') : ( - $(this).width() / 2 + 'px');
		var marginTop = height ? ( - height / 2 + 'px') : ( - $(this).height() / 2 + 'px');

		return $(this).css({
			'margin-left': marginLeft,
			'margin-top': '-10000px'
		}).animate({
			marginTop: marginTop
		},
		500);
	};

	$.fn.togglePopup = function (element, callback, width, height, afterCloseAction, blockHide) {
		if ($('#popup').hasClass('hidden')) {
			$('#opaco').height($(document).height()).removeClass('hidden')[$.browser.msie ? 'attr': 'fadeTo']('fast', 0.7);

			if (!blockHide) {
				$('#opaco').click(function () {
					$(this).togglePopup(null, null, null, null, afterCloseAction);
				});
			}

			//$('#popup_WaitMess').html(SITE_LNG == 3 ? waitingMessageEn: waitingMessage).alignCenter().removeClass('hidden');

			$('#popup').css({
				'dispay': 'none'
			}).html('').load(element, [], function () {
				// подключим обработчики для линков
				if (typeof __unbindClickOnPage !== 'undefined') {
					__unbindClickOnPage();
					__bindClickOnPage();
				}

				if (typeof callback == 'function') {
					callback.call(this);
				}
				$('#popup').alignCenter(width, height).removeClass('hidden');
				//$('#popup_WaitMess').addClass('hidden');
			});
		} else {
			$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
			$('#popup').addClass('hidden');

			if (typeof afterCloseAction == 'function') {
				afterCloseAction.call(this);
			}
		}
	};

	$(document).keyup(function (event) {
		if (event.keyCode == 27) {
			$('#opaco').addClass('hidden').removeAttr('style').unbind('click');
			$('#popup').addClass('hidden');
		}
	});

	// смена текущего баланса
	var radioCont = $("div.headerBottom-radio input[name='currency']")
	if (radioCont.length !== 0) {
		var sumCont = $("div.headerBottom-account");
		radioCont.click(function () {
			if (this.value) {
				sumCont.html('Loading...');
				$.ajax({
					type: 'POST',
					url: 'htdocs/set_active_currency.php',
					data: 'cur=' + this.value,
					success: function (str) {
						sumCont.html(str);
					}
				});
			}
		})
	}

	//

	id_top = (getCookie('payment_form_top')) ? parseInt(getCookie('payment_form_top')) : 1;
	id_left = (getCookie('payment_form_left')) ? parseInt(getCookie('payment_form_left')) : 1;
	if (id_top && id_left) {
		showPaymentSystemPage(id_top, id_left, '_');
	}

	// действие по загрузке
	var action = getCookie("afterLoadAction");
	if (typeof afterLoadActionNow === 'undefined') {
		if (typeof window[action] === 'function') {
			setCookie("afterLoadAction", "", 1, "/");
			window[action]();
		}
	}

	//var game_info_float_block = $(".fixbox");
	//if (game_info_float_block.length) {
	//	game_info_float_block.css('left', ($('.main').position().left - 107) + 'px');
	//}

	//var game_info_float_block_map = $(".fixbox_map");
	//if (game_info_float_block_map.length) {
	//	game_info_float_block_map.css('left', ($('.main').position().left + 257) + 'px');
	//}
});


/**
 * Картинка, закрывающая полоску...
 *
 * @param {string} container
 * @param {boolean} is_right
 */
function setHidPic(container, is_right) {
	var cont = $(container),
		hid = cont.find('.hidPic');

	if (hid.length == 0) {
		cont.append('<div class="hidPic"></div>');
		hid = cont.find('.hidPic');
	}

	var currentEl = cont
		.find('a')
		.filter(function() {
			return (/^.*_on$/.test(this.className));
		});

	if (currentEl.length) {
		var top = currentEl.position().top;

		hid.css({
			'background-position': 'center -' + (top + 100) + 'px',
			'top': (top + 1) + 'px',
			'left': (is_right ? '145px' : '0px')
		});
	} else {
		hid.css({
			'top': '-2000px'
		});
	}
}

