﻿function Validator(args)
{
	var containerElement;

	if( args.containerElement!=null )
		containerElement=Element.extend(args.containerElement);
	else if ( args.containerId!=null )
		containerElement=$('args.containerId');
	else if ( args.formName!=null )
		containerElement=Element.extend(document.forms[args.formName]);

	if( containerElement==null )
		return;

	var inputs={};

	this.addEntry=function(entrySpec)
	{
		var ar;

		ar=containerElement.select('[validateInput='+entrySpec.key+']');

		if( ar.length==0 )
			return false;

		entrySpec.input=ar[0];

		if( entrySpec.messageKey!=null )
			ar=containerElement.select('[validateMessage='+entrySpec.messageKey+']');
		else
			ar=containerElement.select('[validateMessage='+entrySpec.key+']');

		if( ar.length>0 )
			entrySpec.message=ar[0];

		if( entrySpec.type==null )
			entrySpec.type='string';

		inputs[entrySpec.key]=entrySpec;

		if( entrySpec.maxLength!=null && entrySpec.input.readAttribute('type')=='text' )
			entrySpec.input.writeAttribute('maxLength',entrySpec.maxLength);

		return true;
	}


	if( args.entries!=null )
	{
		for(var i=0;i<args.entries.length;i++)
			this.addEntry(args.entries[i]);
	}
	else if( containerElement!=null )
	{
		var tmp1=containerElement.select('[validateInput]');
		for(var i=0;i<tmp1.length;i++)
		{
			var entrySpec=new Object();
			entrySpec.key=tmp1[i].readAttribute('validateInput');
			entrySpec.type=tmp1[i].readAttribute('validateInputType');
			entrySpec.maxLength=tmp1[i].readAttribute('validateInputMaxLength');
			entrySpec.minLength=tmp1[i].readAttribute('validateInputMinLength');
			entrySpec.caption=tmp1[i].readAttribute('validateInputCaption');
			entrySpec.notEmpty=tmp1[i].readAttribute('validateInputNotEmpty')=='true';
			entrySpec.notZero=tmp1[i].readAttribute('validateInputNotZero')=='true';
			entrySpec.min=parseFloat(tmp1[i].readAttribute('validateInputMin'));
			entrySpec.max=parseFloat(tmp1[i].readAttribute('validateInputMax'));
			entrySpec.classNameInputError=tmp1[i].readAttribute('validateInputClassNameInputError');
			entrySpec.classNameInputOk=tmp1[i].readAttribute('validateInputClassNameInputOk');

			entrySpec.messageKey=tmp1[i].readAttribute('validateInputMessageKey');


			this.addEntry(entrySpec);
		}
	}


	var getValue=function(input)
	{
		if( input.tagName=='textarea' )
			return input.value;

		var type=input.readAttribute('type');

		if( type=='checkbox' )
			return input.checked;

		if( type=='text' )
			return input.value.trim();

		if( type=='radio' )
		{
			var ar=containerElement.select('[name='+input.readAttribute('type')+']');
			for(var i=0;i<ar.length;i++)
				if( ar[i].checked )
					return ar[i].readAttribute('value').trim();
			return "";
		}

		return input.value.trim();
	}

	var reportEntry=function(entry,msg) {
		clearWarningForEntry(entry);
		if( entry.valid )
		{
			if( entry.message!=null && msg!=null  )
				entry.message.update(msg);
		}
		else
		{
			if( entry.message!=null && msg!=null  )
				entry.message.update(msg);

			if( entry.message!=null ) {
				if( entry.classNameMessageError!=null )
					entry.message.addClassName(entry.classNameMessageError);
				if( entry.classNameMessageOk!=null )
					entry.message.removeClassName(entry.classNameMessageOk);
			}

			if( entry.classNameInputError!=null )
				entry.input.addClassName(entry.classNameInputError);
			if( entry.classNameInputOk!=null )
				entry.input.removeClassName(entry.classNameInputOk);

		}
	}

	this.reportEntryError=function(key,msg)
	{
		var entry=this.getEntry(key);
		if( entry==null )
			return;
		entry.valid=false;
		reportEntry(entry,msg);
	}

	this.reportEntryOk=function(key,msg)
	{
		var entry=this.getEntry(key);
		if( entry==null )
			return;
		entry.valid=true;
		reportEntry(entry,msg);
	}

	var validateEntryValue=function(entry) {


		var input=entry.input;
		var result=true;

		var value=getValue(input);

		var msg=null;

		if( input.callbackValidate!=null )
			result=input.callbackValidate(value);
		else {
			var isEmpty=false;

			if( typeof(value)=='boolean' )
				isEmpty=!value;
			else
				isEmpty=value.empty();

			if( entry.notEmpty && isEmpty ) {
				result=false;
				msg = "Pole "+entry.caption+" nie może być puste";
			}


			if( result && entry.type=='int' && !isEmpty ) {
				
				var valueOrig=value;
				
				if( !value.match(/^-?\d+([\.,]0+)?$/) )
				{
					result=false;
					msg = "Pole "+entry.caption+" nie jest liczbą";
				}

				value=parseInt(value);

				if( value.toString()=="NaN" ) {
					result=false;
					msg = "Pole "+entry.caption+" nie jest liczbą";
				}
				if( result && entry.min!=null ) {
					if( value<entry.min ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być mniejsz od "+entry.min;
					}
				}

				if( result && entry.max!=null ) {
					if( value>entry.max ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być większe od "+entry.max;
					}
				}
				if( result && entry.notZero ) {
					if( value==0 ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być zerem";
					}
				}
				
				
				if( result && entry.maxLength ) {
					if( valueOrig.length>entry.maxLength ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być dłuższe od "+entry.maxLength;
					}
				}
				if( result && entry.minLength ) {
					if( valueOrig.length<entry.minLength ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być krótsze od "+entry.minLength;
					}
				}				
			}

			if( result && entry.type=='string' && !isEmpty ) {
				if( result && entry.maxLength ) {
					if( value.length>entry.maxLength ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być dłuższe od "+entry.maxLength;
					}
				}
				if( result && entry.minLength ) {
					if( value.length<entry.minLength ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być krótsze od "+entry.minLength;
					}
				}
			}

			if( result && entry.type=='emailUser' && !isEmpty ) {
				if( !value.match(/^([\w-\.]+)$/) ) {
					result=false;
					msg = "Pole "+entry.caption+" nie jest prawidłowym użytkownikiem e-mail";
				}
			}

			if( result && entry.type=='email' && !isEmpty ) {
				if( !value.match(/^([\w-\.]+)@([\w-]+)(.[\w-]+)+$/) ) {
					result=false;
					msg = "Pole "+entry.caption+" nie jest prawidłowym adresem e-mail";
				}
			}

			if( result && entry.type=='float' && !isEmpty ) {
				if( !value.match(/^-?\d+([\.,]\d+)?$/) ) {
					result=false;
					msg = "Pole "+entry.caption+" nie jest liczbą";
				}
				value=value.gsub(',','.');
				value=parseFloat(value);
				if( value.toString()=="NaN" ) {
					result=false;
					msg = "Pole "+entry.caption+" nie jest liczbą";
				}
				if( result && entry.min ) {
					if( value<entry.min ) {
						alert('d2111:'+value);

						result=false;
						msg = "Pole "+entry.caption+" nie może być mniejsz od "+entry.min;
					}
				}
				if( result && entry.max ) {
					if( value>entry.max ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być większe od "+entry.max;
					}
				}
				if( result && entry.notZero ) {
					if( value==0 ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być zerem";
					}
				}
			}



			if( result && entry.type=='price' && !isEmpty ) {
				if( !value.match(/^-?\d+(\.\d\d?)?$/) )
				{
					result=false;
					msg = "Pole "+entry.caption+" nie jest ceną";
				}
				value=parseFloat(value);
				if( value.toString()=="NaN" ) {
					result=false;
					msg = "Pole "+entry.caption+" nie jest ceną";
				}
				if( value<0 ) {
					result=false;
					msg = "Pole "+entry.caption+" nie może być ujemne";
				}
				if( result && entry.min ) {
					if( value<entry.min ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być mniejsz od "+entry.min;
					}
				}
				if( result && entry.max ) {
					if( value<entry.max ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być większe od "+entry.max;
					}
				}
				if( result && entry.notZero ) {
					if( value==0 ) {
						result=false;
						msg = "Pole "+entry.caption+" nie może być zerem";
					}
				}
			}

			if( result && entry.type=='mobile' && !isEmpty ) {
				value=value.replace(' ','');
				if( !value.match(/^(00|\+)?(48)?\d{9}$/) ) {
					result=false;
					msg = "Pole "+entry.caption+" nie jest prawidłowym adresem e-mail";
				}
			}


		}

		if( result )
			return null;

		if( entry.msgError!=null )
			return entry.msgError;
		if( msg==null )
			return "";
		return msg;
	}

	var validateForEntry=function(entry)
	{
		var r=validateEntryValue(entry);
		if( r!=null )
		{
			entry.valid=false;
			if( entry.noReport )
				return;

			reportEntry(entry,r);
		}
		else
			entry.valid=true;
	}

	this.validateEntry=function(key)
	{
		var entry=this.getEntry(key);
		if( entry!=null );
			validateForEntry(entry);
	}

	this.validate=function()
	{
		this.clearWarnings();

		for(var i in inputs)
		{
			var entry=inputs[i];

			validateForEntry(entry);
		}

		var validOnlyReported=true;
		var validAll=true;
		for(var i in inputs)
		{
			if( inputs[i].valid )
				continue;
			validAll=false;
			if( inputs[i].noReport )
				continue;
			validOnlyReported=false;
		}
		return {validAll:validAll,validOnlyReported:validOnlyReported};
	}

	var clearWarningForEntry=function(entry)
	{
		if( entry.message!=null )
		{
			entry.message.update('');
			if( entry.classNameMessageError!=null )
				entry.message.removeClassName(entry.classNameMessageError);
			if( entry.classNameMessageOk!=null )
				entry.message.addClassName(entry.classNameMessageOk);

		}

		if( entry.classNameInputError!=null )
			entry.input.removeClassName(entry.classNameInputError);
		if( entry.classNameInputOk!=null )
			entry.input.addClassName(entry.classNameInputOk);
	}

	this.getEntry=function(key)
	{
		return inputs[key];
	}

	this.clearWarning=function(key)
	{
		var entry=this.getEntry(key);
		if( entry!=null )
			clearWarningForEntry(entry);
	}

	this.clearWarnings=function()
	{
		for(var i in inputs)
		{
			var entry=inputs[i];
			clearWarningForEntry(entry);
		}
	}

	this.focusFirstInvalid=function()
	{
		for(var key in inputs)
			if( !inputs[key].valid && (!inputs[key].noReport || inputs[key].noReport==null) )
			{
				inputs[key].input.focus();
				return;
			}

	}


	this.setErrorMsgOnly=function(key,msg)
	{
		this.clearWarning();
		this.reportEntryError(key,msg);
	}
}

function validateFloatValue(value) {
	if( !value.match(/^-?\d+([\.,]\d+){0,1}$/) )
		return false;
	return true;
}
function validateIntegerValue(value) {
	if( !value.match(/^-?\d+([\.,]0+)?$/) )
		return false;
	return true;
}
function validateIntValue(value) {
	if( !value.match(/^-?\d+([\.,]0+)?$/) )
		return false;
	return true;
}

function validatePriceValue(value) {
	if( !value.match(/^-?\d[ \d]*([\.,]\d{1,2}){0,1}$/) )
		return false;
	return true;
}

function validateEmailValue(value)
{

	if( !value.match(/^([\w-\.]+)@([\w-]+)(.[\w-]+)+$/) )
		return false;
	return true;
}

function validatePrice(name,obj,min,max,showMsg)
{
	if( obj==null )
	{
		if( showMsg )
			window.alert('Pole '+name+' musi być ceną');
		return 1;
	}
	var value=obj.value;

	if( !value.match(/^-?\d[ \d]*([\.,]\d{1,2}){0,1}$/) )
	{
		if( showMsg )
			window.alert('Pole '+name+' musi być ceną');
		return 1;
	}

	var valFloat=parseFloat(value);

	if( min!=null )
		if( valInt<min )
		{
			if( showMsg )
				window.alert('Wartość '+name+' nie może być mniejsza od '+min);
			return 2;
		}
	if( max!=null )
		if( valInt>max )
		{
			if( showMsg )
				window.alert('Wartość '+name+' nie może być większa od '+max);
			return 3;
		}
	return 0;
}


function validateFloat(name,obj,min,max,showMsg)
{
	if( obj==null )
	{
		if( showMsg )
			window.alert('Pole '+name+' musi być ceną');
		return 1;
	}
	var value=obj.value;

	if( !value.match(/^-?\d+([\.,]\d+){0,1}$/) )
	{
		if( showMsg )
			window.alert('Pole '+name+' musi być ceną');
		return 1;
	}

	var valFloat=parseFloat(value);

	if( min!=null )
		if( valInt<min )
		{
			if( showMsg )
				window.alert('Wartość '+name+' nie może być mniejsza od '+min);
			return 2;
		}
	if( max!=null )
		if( valInt>max )
		{
			if( showMsg )
				window.alert('Wartość '+name+' nie może być większa od '+max);
			return 3;
		}
	return 0;
}


function validateInteger(name,obj,min,max,showMsg)
{
	if( obj==null )
	{
		if( showMsg )
			window.alert('Pole '+name+' musi być liczbą');
		return 1;
	}
	var value=obj.value;

	if( !value.match(/^-?\d+([\.,]0+)?$/) )
	{
		if( showMsg )
			window.alert('Pole '+name+' musi być liczbą');
		return 1;
	}

	var valInt=parseInt(value);

	if( min!=null )
		if( valInt<min )
		{
			if( showMsg )
				window.alert('Wartość '+name+' nie może być mniejsza od '+min);
			return 2;
		}
	if( max!=null )
		if( valInt>max )
		{
			if( showMsg )
				window.alert('Wartość '+name+' nie może być większa od '+max);
			return 3;
		}
	return 0;
}

function validateString(name,obj,min,max,showMsg)
{
	if( obj==null )
	{
		if( showMsg )
			window.alert('Pole '+name+' nie może być puste');
		return 1;
	}


	if( min==null && max==null )
	{
		if(  obj.value.trim()!='' )
			return 0;
		if( showMsg )
			window.alert('Pole '+name+' nie może być puste');
		return 1;
	}
	else
	{
		if( min!=null )
			if( obj.value.length<min )
			{
				if( showMsg )
					window.alert('Pole '+name+' nie może być krótsze od '+min);
				return 2;
			}
		if( max!=null )
			if( obj.value.length>max )
			{
				if( showMsg )
					window.alert('Pole '+name+' nie może być dłuższe od '+max);
				return 3;
			}
		return 0;
	}
}

function validateMobile(name,obj,showMsg,retObj)
{
	if( obj==null )
	{
		if( showMsg )
			window.alert('Pole '+name+' nie może być puste');
		return 1;
	}
	var value=obj.value.trim();
	if( value.startsWith('+') )
		value=value.substring(1).trim();
	if( value.startsWith('00') )
		value=value.substring(2).trim();
	if( value.startsWith('48') )
		value=value.substring(2).trim();

	value=value.replace(' ','');

	if( !value.match(/^[0-9]{9}$/) )
	{
		if( showMsg )
			window.alert('Pole '+name+' jest nieprawidłowym numerem');
		return 2;
	}

	if( retObj!=null )
		reObj.returnValue=value;

	return 0;
}

function validateEmail(name,obj,showMsg)
{
	if( obj==null )
	{
		if( showMsg )
			window.alert('Pole '+name+' nie może być puste');
		return 1;
	}
	var value=obj.value;

	if( !value.match(/^([\w-\.]+)@([\w-]+)(.[\w-]+)+$/) )
	{
		if( showMsg )
			window.alert('Pole '+name+' jest nieprawidłowym adresem e-mail');
		return 2;
	}

	return 0;
}

function validateEmailUser(name,obj,min,max, showMsg)
{
	if( obj==null )
	{
		if( showMsg )
			window.alert('Pole '+name+' nie może być puste');
		return 1;
	}
	var value=obj.value;

	if( !value.match(/^([\w-\.]+)$/) )
	{
		if( showMsg )
			window.alert('Pole '+name+' jest nieprawidłową nazwą użytkownika');
		return 2;
	}

	return 0;
}

function confirmDelete(url)
{
	if( window.confirm('Napewno chcesz usunąć ?') )
	{
		if( url==null )
			return true;
		window.location=url;
	}
	else
	{
		if( url==null )
			return false;
	}
}
