/*
*/
function register() {
	var obj = {};
	obj['cmd'] = 'validate_register_form';
	
	errors_title = $('.errors_title');
	errors_title.hide();
	
	$.post("/booking/system/modules/com.gridnine.opencms.modules.myreis/pages/ajax_provider_account.jsp", getAllFormInputs(obj, 'register_form'), function(data) {
		if (data.status == 'error') {
			var errors_area = $('.errors_area');
			errors_area.empty();
			for (i = 0; i < data.errors.length; i++) {
				var error = data.errors[i];
				errors_area.append('<li>' + error.message + '</li>');
			}
			errors_title.show();
		} else {
			if (data.action == 'registered') {
				location.href='/booking/ru/common/account/register.html?registered=true';
			}
		}
	}, 'json');
}

function checkLogin(login, outputArea) {
	var obj = {};
	obj['cmd'] = 'check_login';
	obj['login'] = login;
	
	$.post("/booking/system/modules/com.gridnine.opencms.modules.myreis/pages/ajax_provider_account.jsp", obj, function(data) {
		outputArea.empty();
		if (data.status == 'error') {
			outputArea.append(data.message);
		}
	}, 'json');
}

function doLogin() {
	var obj = {};
	obj['cmd'] = 'user_authorization';
	obj['profile.login'] = $('input[name=profile.login]').val();
	obj['profile.password'] = $('input[name=profile.password]').val();
	obj['requestParameter'] = $('input[name=requestParameter]').val();
	
	$.post("/booking/system/modules/com.gridnine.opencms.modules.myreis/pages/ajax_provider_account.jsp", obj, function(data) {
		if (data.status == 'error') {
			var errors = 'Ошибки::';
			for (i = 0; i < data.errors.length; i++) {
				var error = data.errors[i];
				errors += '\r\n' + error.message;
			}
			alert(errors);
		} else {
			location.href = obj['requestParameter'];
		}
	}, 'json');
}

function logOff(redirectUrl) {
	var obj = {};
	obj['cmd'] = 'user_logout';
	obj['action'] = 'logout';
	
	$.post("/booking/system/modules/com.gridnine.opencms.modules.myreis/pages/ajax_provider_account.jsp", obj, function(data) {
		if (data.status == 'success') {
			location.href = redirectUrl;
		} else {
			alert('Ошибки:!');
		}
	}, 'json');
}

function saveProfile(category, uid) {
	var obj = {};
	if (category == 'delivery' || category == 'profile') {
		obj['cmd'] = 'save_profile_data';
	} else if (category == 'contacts') {
		obj['cmd'] = 'validate_documents_form';
	} else if (category == 'delete_document') {
		obj['cmd'] = 'delete_document';
	}
	obj['category'] = category;

	var $pea = $('.profile_errors_area');
	var $psa = $('.profile_success_area');
	var $pdata = $('.profile_data');
	
	$.post("/booking/system/modules/com.gridnine.opencms.modules.myreis/pages/ajax_provider_account.jsp", getAllFormInputs(obj, 'register_form'), function(data) {
		if (data.status == 'error') {
			var errors = '<ul><strong>Ошибки:</strong>';
			for (i = 0; i < data.errors.length; i++) {
				var error = data.errors[i];
				errors += '<li>' + error.message;
			}
			errors += '</ul><br><br>';
			$psa.hide();
			$pea.empty();
			$pea.append(errors);
			$pea.show();
			
		} else {
			if (category == 'profile') {
				$('input[name=oldPassword]').val('');
				$('input[name=password]').val('');
				$('input[name=rePassword]').val('');
			}
			$pea.hide();
			$psa.show();
			$pdata.hide();
		}
	}, 'json');
	
	return false;
}


function hideMiddleName(obj) {
	obj.parents('#newPassport').each(function() {
		var middleName = $('input[name=ProfileForm.pspt.middleName.' + $(this).attr('pass_id') + ']'); 
		if (obj.val() == 'INTERNAL' || obj.val() == 'BIRTHDAY_NOTIFICATION') {
			middleName.show();
			middleName.parent('div').show();
			middleName.attr('disabled', false);
		} else {
			middleName.hide();
			middleName.parent('div').hide();
			middleName.attr('disabled', true);
		}
	});
	updateExpired(obj);
}

function updateExpired(obj) {
	obj.parents('#newPassport').each(function() {
		var passId = $(this).attr('pass_id');
		var currentDate = new Date();
		var birthDate = $('input[name=ProfileForm.pspt.birthday.' + passId + ']');
		var expireDate = $('input[name=ProfileForm.pspt.passportExpired.' + passId + ']'); 
		
		expireDate.get(0).readOnly = false;
		expireDate.unmask();
		
		if (obj.val() == 'INTERNAL') {
			expireDate.get(0).readOnly = true;
			if (birthDate.val() != '') {
				var birthday = parseDate(birthDate.val());
				var age = getAge(birthday, currentDate);
				if (age >= 14 && age < 20) {
					birthday.setFullYear(birthday.getFullYear() + 20);
					expireDate.val(dateFormat(birthday));
				} else if (age >= 20 && age <= 45) {
					birthday.setFullYear(birthday.getFullYear() + 45);
					expireDate.val(dateFormat(birthday));
				} else if (age >= 46) {
					birthday.setFullYear(birthday.getFullYear() + 70);
					expireDate.val(dateFormat(birthday));
				} else {
					expireDate.val('дд.мм.гггг');
				}
			}
		} else if (obj.val() == 'BIRTHDAY_NOTIFICATION') {
			expireDate.get(0).readOnly = true;
			if (birthDate.val() != '') {
				var birthday = parseDate(birthDate.val());
				var age = getAge(birthday, currentDate);
				if (age >= 0 && age < 14) {
					birthday.setFullYear(birthday.getFullYear() + 14);
					expireDate.val(dateFormat(birthday));
				} else {
					expireDate.val('дд.мм.гггг');
				}
			}
		} else {
			expireDate.mask("99.99.9999");
		}
	});
}


function updateLine(add, value, target) {
	var line = target.value.split(',');
	var newString = '';
	if (add) {
		target.value += (target.value != '' ? ',' + value : value);
	} else {
		for (var i = 0; i < line.length; i++) {
			if (value != line[i]) {
				newString += line[i] + (i < line.length ? ',' : '');
			}
		}
		target.value = newString;
	}
}

function updateNumber(input, more) {
	if (more) {
		input.value = new Number(input.value) + 1;
	} else {
		input.value = new Number(input.value) - 1;
	}
	return input.value;
}

function getNumber(className) {
	var input = $('.' + className).get(0);
	return (new Number(input.value));
}

function addPassport() {
	var $tpl = $('#docTemplate');
	var $result = $('#docsOutArea');
	var curNum = $('#current_passport').val();

	$tpl.find('#newPassport').attr('pass_id', curNum);
	$tpl.find('#del_button').attr('pass_id', curNum);
		
	
	$tpl.find('input,select,radio').each(function() {
		if ($(this).attr('name') != 'current_passport' && $(this).attr('name') != 'current_passport_line') {
			$(this).attr('name', $(this).attr('name_tpl') + '.' + curNum);
		}
	});
	$result.append($tpl.html());
	
	$('input[name=ProfileForm.pspt.birthday.' + curNum + ']').mask('99.99.9999');
	$('input[name=ProfileForm.pspt.passportExpired.' + curNum + ']').mask('99.99.9999');
	$('input[name=ProfileForm.pspt.birthday.' + curNum + ']').bind('change', function() {
		updateExpired($('select[name=ProfileForm.pspt.passportType.' + curNum + ']'));
	});
	updateLine(true, $('#current_passport').val(), $('#current_passport_line').get(0));
	updateNumber($('#current_passport').get(0), true);
}

function delPassport(obj) {
	var curNum = $(obj).attr('pass_id');
	$('#docsOutArea #newPassport').each(function() {
		if ($(this).attr('pass_id') == curNum) {
			$(this).remove();
			updateNumber($('#current_passport').get(0), false);
			updateLine(false, curNum, $('#current_passport_line').get(0));
		}
	});
}

function confirmDelete() {
    return confirm("Вы действительно хотите удалить этот документ?");
}

function deleteDocument(pid) {
	
	if (confirmDelete()) {
		$('#exists_passports tr').each(function() {
			if ($(this).attr('pass_id') == pid) {
				// update indexes line
				updateLine(false, pid, $('#current_passport_line').get(0));
				updateNumber($('#current_passport').get(0), false);

				// remove elements from the interface
				$('input[name=ProfileForm.pspt.lastName.' + pid + ']').remove();
				$('input[name=ProfileForm.pspt.firstName.' + pid + ']').remove();
				$('input[name=ProfileForm.pspt.middleName.' + pid + ']').remove();
				$('input[name=ProfileForm.pspt.gender.' + pid + ']').remove();
				$('input[name=ProfileForm.pspt.birthday.' + pid + ']').remove();
				$('input[name=ProfileForm.pspt.citizenship.' + pid + ']').remove();
				$('input[name=ProfileForm.pspt.passportExpired.' + pid + ']').remove();
				$('input[name=ProfileForm.pspt.passportType.' + pid + ']').remove();
				$('input[name=ProfileForm.pspt.passportNumber.' + pid + ']').remove();
				$(this).remove();
			}
		});
	}
}

function addDelivery() {
	var $tpl = $('#deliveryTemplate');
	var $result = $('#deliveryOutArea');
	var curNum = $('#current_delivery').val();

	$tpl.find('#newDelivery').attr('delivery_id', curNum);
	$tpl.find('#del_button').attr('delivery_id', curNum);
		
	$tpl.find('input,select,radio,textarea').each(function() {
		if ($(this).attr('name') != 'current_delivery' && $(this).attr('name') != 'current_delivery_line') {
			$(this).attr('name', $(this).attr('name_tpl') + '.' + curNum);
		}
	});
	$result.append($tpl.html());
	
	updateLine(true, $('#current_delivery').val(), $('#current_delivery_line').get(0));
	updateNumber($('#current_delivery').get(0), true);
}

function delDelivery(obj) {
	var curNum = $(obj).attr('delivery_id');
	$('#deliveryOutArea #newDelivery').each(function() {
		if ($(this).attr('delivery_id') == curNum) {
			$(this).remove();
			updateNumber($('#current_delivery').get(0), false);
			updateLine(false, curNum, $('#current_delivery_line').get(0));
		}
	});
}

function confirmDelete() {
    return confirm("Вы действительно хотите удалить этот адрес?");
}

function deleteDelivery(pid) {
	
	if (confirmDelete()) {
		$('#exists_delivery tr').each(function() {
			if ($(this).attr('delivery_id') == pid) {
				// update indexes line
				updateLine(false, pid, $('#current_delivery_line').get(0));
				updateNumber($('#current_delivery').get(0), false);

				// remove elements from the interface
				$('input[name=ProfileForm.deliveryCity.' + pid + ']').remove();
				$('input[name=ProfileForm.deliveryAddress.' + pid + ']').remove();
				$(this).remove();
			}
		});
	}
}


