﻿/*
Author: Serge Neroznaque.
Page Type: Client-side Include.
Page Purpose: Contains client-side global routines. Mainly custom form field validators.
Warning: The code is closed and the page shall not be changed by anyone except author.
*/
// <script>
function invalidName(strSubj)
{
	return (strSubj.charAt(0) == " " || strSubj.charAt(strSubj.length - 1) == " ");
}

function checkText(txtRef, strLabel, iLen) // iLen -- is optional parameter. useful when you want to check textareas
{
	if (strLabel == null) strLabel = "TEXT field"
	if (txtRef.value.length == 0) {
		alert("Требуется ввести значение для \"" + strLabel + "\" перед продолжением.");
		txtRef.focus();
		return false;
	}
	else if (invalidName(txtRef.value)) {
		alert("\"" + strLabel + "\" не может содержать пробелы в начале, либо в конце.");
		txtRef.focus();
		txtRef.select();
		return false;
	}
	else if (iLen != null && txtRef.value.length > parseInt(iLen)) {
		alert("Поле \"" + strLabel + "\" слишком длинное (" + txtRef.value.length + " символов).\Пожалуйста уменьшите длину до " + iLen + " символов.");
		txtRef.focus();
		txtRef.select();
		return false;
	}
	return true;
}

function checkNumber(txtRef, strLabel, allowFloat)
{
	var i;
	if (allowFloat) {
		for (i = 0; i < txtRef.value.length; i++){
			var arra = txtRef.value.split(".");
			if (arra.length > 2) {
				alert("Extra decimal divider characters in \"" + strLabel + "\" detected.\nThis field should contain digits and/or dot only.");
				txtRef.focus();
				txtRef.select();
				return false;
			}
			else if (!( txtRef.value.charAt(i) >= "0" && txtRef.value.charAt(i) <= "9" || txtRef.value.charAt(i) == ".")) {
				alert("Invalid characters in \"" + strLabel + "\" detected.\nThis field should contain digits and/or dot only.");
				txtRef.focus();
				txtRef.select();
				return false;
			}
		}
	}
	else {
		for (i = 0; i < txtRef.value.length; i++){
			if (!(txtRef.value.charAt(i) >= "0" && txtRef.value.charAt(i) <= "9")) {
				alert("Invalid characters in \"" + strLabel + "\" detected.\nThis field should contain digits only.");
				txtRef.focus();
				txtRef.select();
				return false;
			}
		}
	}
	return true;
}

// expects string as first parameter
function checkNumberModA(strValue, strLabel, allowFloat)
{
	var i;
	if (strValue == "") return false;

	if (allowFloat) {
		for (i = 0; i < strValue.length; i++){
			var arra = strValue.split(".");
			if (arra.length > 2) {
				return false;
			}
			else if (!( strValue.charAt(i) >= "0" && strValue.charAt(i) <= "9" || strValue.charAt(i) == ".")) {
				return false;
			}
		}
	}
	else {
		for (i = 0; i < strValue.length; i++){
			if (!(strValue.charAt(i) >= "0" && strValue.charAt(i) <= "9")) {
				return false;
			}
		}
	}
	return true;
}

function checkEmail(strValue, strLabel) // expect data in format nnn@nnn.nnn
{
	var objRegExp = new RegExp("^[A-Za-z0-9_.-]+@[A-Za-z0-9_.-]+[.][A-Za-z]+$");
	 
	if (objRegExp.test(strValue))
		return true;
	alert("Обнаружен некорректный формат электронного адреса в поле \"" + strLabel + "\".");
	return false;
}


function validateForm(frmRef)
{
	for (var i = 0; i < frmRef.elements.length; i++)
		if (frmRef.elements[i].required && !checkText(frmRef.elements[i], frmRef.elements[i].required, frmRef.elements[i].maxlength))
			return false;
	if (frmRef.datIsCool)
		frmRef.datIsCool.value = "Yes";
	return true;
}

function validateFormEx(frmRef) // extends validateForm. also checks required <select>
{
	for (var i = 0; i < frmRef.elements.length; i++)
		if (frmRef.elements[i].required) {
			if (frmRef.elements[i].type.indexOf("select") != -1) {
				var valua = frmRef.elements[i].options[frmRef.elements[i].selectedIndex].value;
				if (valua == "" || valua == "0") {
					alert("Пожалуйста, выберите значение из \"" + frmRef.elements[i].required + "\".");
					frmRef.elements[i].focus();
					return false;
				}
			}
			else if (!checkText(frmRef.elements[i], frmRef.elements[i].required, frmRef.elements[i].maxlength))
				return false;
		}
	if (frmRef.datIsCool)
		frmRef.datIsCool.value = "Yes";
	return true;
}

function validateFormExModA(frmRef)
// extends validateFormEx. also invokes custom validator specified by "validator" expando
// custom validator must comply with format:
// function customValidator(strValue, strFieldLabel) { return true/false; }
{
	for (var i = 0; i < frmRef.elements.length; i++)
		if (frmRef.elements[i].required || (frmRef.elements[i].value && frmRef.elements[i].value.length > 0)) {
			if (frmRef.elements[i].validator) {
				if (!eval(frmRef.elements[i].validator + "(frmRef.elements[i].value, frmRef.elements[i].required)")) {
					frmRef.elements[i].focus();
					if (frmRef.elements[i].select)
						frmRef.elements[i].select();
					return false;
				}
			}
			else if (frmRef.elements[i].type.indexOf("select") != -1 && frmRef.elements[i].required != null) {
				var valua;
				var iInd = frmRef.elements[i].selectedIndex;

				if (iInd < 0)
					valua = "";
				else
					valua = frmRef.elements[i].options[iInd].value;

				if (valua == "" || valua == "0") {
					alert("Пожалуйста, выберите значение из \"" + frmRef.elements[i].required + "\".");
					frmRef.elements[i].focus();
					return false;
				}
			}
			else if (!checkText(frmRef.elements[i], frmRef.elements[i].required, frmRef.elements[i].maxlength))
				return false;
		}
	if (frmRef.datIsCool)
		frmRef.datIsCool.value = "Yes";
	return true;
}

// proxy for usage in expando denoting custom form field validator
function customDateValidator(strValue, strFieldLabel)
{
	if (strFieldLabel == null)
		strFieldLabel = "Поле с датой";
	if (!validateDate(strValue)) {
		alert("Неверный формат даты в поле: " + strFieldLabel + ".\nТребуемый формат dd.mm.yyyy.");
		return false;
	}
	return true
}

// proxy for usage in expando denoting custom form field validator
function customIntegerValidator(strValue, strFieldLabel)
{
	if (strFieldLabel == null)
		strFieldLabel = "Целочисленное поле";
	if (!checkNumberModA(strValue, strFieldLabel, false)) {
		alert("Неверное целочисленное значение в поле: " + strFieldLabel + ".");
		return false;
	}
	return true
}

// proxy for usage in expando denoting custom form field validator
function customFloatValidator(strValue, strFieldLabel)
{
	if (strFieldLabel == null)
		strFieldLabel = "Float field";
	if (!checkNumberModA(strValue, strFieldLabel, true)) {
		alert("Error validating float at field: " + strFieldLabel + ".");
		return false;
	}
	return true
}

function validateDate(strValue) // expect data in format dd.mm.yyyy
{
	if ((/^\d{1,2}(\.)\d{1,2}\1\d{4}$/).test(strValue)) {
		var aDate = strValue.split(".");
		var iYear = parseInt(aDate[2], 10);
		var iMonth = parseInt(aDate[1], 10);
		var iDay = parseInt(aDate[0], 10);

		var days = {'1' : 31, '2' : function (){return (iYear % 4 == 0 ? 29 : 28);}, '3' : 31, '4' : 30, '5' : 31, '6' : 30, '7' : 31,
			'8' : 31, '9' : 30, '10' : 31, '11' : 30, '12' : 31};

		if(iDay <= eval("days[iMonth]" + (iMonth == 2 ? "()" : "")) && iDay > 0) return true;
	}
	return false;
}

function timeValidator(strValue, strLabel)
{
	if (/^(([0-1][0-9])|(2[0-3])):[0-5][0-9]$/.test(strValue))
		return true;
	alert("Invalid time value in \"" + (strLabel == null || strLabel == '' ? 'Time' : strLabel) + "\" detected.\nRequired format: hh:mm.");
	return false;
}

function priceChecker(strValue, strLabel)
{
	if (/^\d+(,\d{2})?$/.test(strValue))
		return true;
	alert("Неверное значение цены в поле \"" + (strLabel == null || strLabel == '' ? 'Цена' : strLabel) + "\".\nПравильный пример: 19,99 или 28,00.");
	return false;
}
