/*
* Really easy field validation with Prototype
* http://tetlaw.id.au/view/javascript/really-easy-field-validation
* Andrew Tetlaw
* Version 1.5.4.1 (2007-01-05)
*
* Copyright (c) 2007 Andrew Tetlaw
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
var Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		if(typeof test == 'function'){
			this.options = $H(options);
			this._test = test;
		} else {
			this.options = $H(test);
			this._test = function(){return true};
		}
		this.error = error || 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return (this._test(v,elm) && this.options.all(function(p){
			return Validator.methods[p.key] ? Validator.methods[p.key](v,elm,p.value) : true;
		}));
	}
}
Validator.methods = {
	pattern : function(v,elm,opt) {return Validation.get('IsEmpty').test(v) || opt.test(v)},
	minLength : function(v,elm,opt) {return v.length >= opt},
	maxLength : function(v,elm,opt) {return v.length <= opt},
	min : function(v,elm,opt) {return v >= parseFloat(opt)},
	max : function(v,elm,opt) {return v <= parseFloat(opt)},
	notOneOf : function(v,elm,opt) {return $A(opt).all(function(value) {
		return v != value;
	})},
	oneOf : function(v,elm,opt) {return $A(opt).any(function(value) {
		return v == value;
	})},
	is : function(v,elm,opt) {return v == opt},
	isNot : function(v,elm,opt) {return v != opt},
	equalToField : function(v,elm,opt) {return v == $F(opt)},
	notEqualToField : function(v,elm,opt) {return v != $F(opt)},
	include : function(v,elm,opt) {return $A(opt).all(function(value) {
		return Validation.get(value).test(v,elm);
	})}
}

var Validation = Class.create();

Validation.prototype = {
	initialize : function(form, options){
		this.options = Object.extend({
			onSubmit : true,
			stopOnFirst : false,
			immediate : false,
			focusOnError : true,
			useTitles : false,
			onFormValidate : function(result, form) {},
			onElementValidate : function(result, elm) {}
		}, options || {});
		this.form = $(form);
		if(this.options.onSubmit) Event.observe(this.form,'submit',this.onSubmit.bind(this),false);
		if(this.options.immediate) {
			var useTitles = this.options.useTitles;
			var callback = this.options.onElementValidate;
			Form.getElements(this.form).each(function(input) { // Thanks Mike!
				Event.observe(input, 'blur', function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });
			});
		}
	},
	onSubmit :  function(ev){
		if(!this.validate()) Event.stop(ev);
	},
	validate : function() {
		var result = false;
		var useTitles = this.options.useTitles;
		var callback = this.options.onElementValidate;
		if(this.options.stopOnFirst) {
			result = Form.getElements(this.form).all(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); });
		} else {
			result = Form.getElements(this.form).collect(function(elm) { return Validation.validate(elm,{useTitle : useTitles, onElementValidate : callback}); }).all();
		}
		if(!result && this.options.focusOnError) {
			Form.getElements(this.form).findAll(
				function(elm){
				return $($(elm).hasClassName('validation-failed'))
				}).first().focus()
			}
		this.options.onFormValidate(result, this.form);
		return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

Object.extend(Validation, {
	validate : function(elm, options){
		options = Object.extend({
			useTitle : false,
			onElementValidate : function(result, elm) {}
		}, options || {});
		elm = $(elm);
		var cn = elm.classNames();
		return result = cn.all(function(value) {
			var test = Validation.test(value,elm,options.useTitle);
			options.onElementValidate(test, elm);
			return test;
		});
	},
	test : function(name, elm, useTitle) {
		var v = Validation.get(name);
		var prop = '__advice'+name.camelize();
		try {
		if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
				if(advice == null) {
					var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					advice = '<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
					switch (elm.type.toLowerCase()) {
						case 'checkbox':
						case 'radio':
							var p = $(elm.parentNode);
							if(p) {
								new Insertion.Bottom(p, advice);
							} else {
								new Insertion.After(elm, advice);
							}
							break;
						default:
							new Insertion.After(elm, advice);
				    }
					advice = Validation.getAdvice(name, elm);
				}
				if(typeof Effect == 'undefined') {
					advice.style.display = 'block';
				} else {
					new Effect.Appear(advice, {duration : 1 });
				}
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
			return false;
		} else {
			var advice = Validation.getAdvice(name, elm);
			if(advice != null) advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = $(elm.parentNode);
			if (!elm || !elm.tagName) {
				return false;
			}
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return $('advice-' + name + '-' + Validation.getElmID(elm)) || $('advice-' + Validation.getElmID(elm));
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
		elm = $(elm);
		var cn = elm.classNames();
		cn.each(function(value) {
			var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
				advice.hide();
				elm[prop] = '';
			}
			elm.removeClassName('validation-failed');
			elm.removeClassName('validation-passed');
		});
	},
	add : function(className, error, test, options) {
		var nv = {};
		nv[className] = new Validator(className, error, test, options);
		Object.extend(Validation.methods, nv);
	},
	addAllThese : function(validators) {
		var nv = {};
		$A(validators).each(function(value) {
				nv[value[0]] = new Validator(value[0], value[1], value[2], (value.length > 3 ? value[3] : {}));
			});
		Object.extend(Validation.methods, nv);
	},
	get : function(name) {
		return  Validation.methods[name] ? Validation.methods[name] : Validation.methods['_LikeNoIDIEverSaw_'];
	},
	methods : {
		'_LikeNoIDIEverSaw_' : new Validator('_LikeNoIDIEverSaw_','',{})
	}
});

Validation.add('IsEmpty', '', function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});

Validation.addAllThese([
	['required', 'To pole nie może być puste.', function(v) {
				return !Validation.get('IsEmpty').test(v);
			}],
	['validate-number', 'Please enter a valid number in this field.', function(v) {
				return Validation.get('IsEmpty').test(v) || (!isNaN(v) && !/^\s+$/.test(v));
			}],
	['validate-digits', 'Please use numbers only in this field. please avoid spaces or other characters such as dots or commas.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/[^\d]/.test(v);
			}],
	['validate-alpha', 'Please use letters only (a-z) in this field.', function (v) {
				return Validation.get('IsEmpty').test(v) ||  /^[a-zA-Z]+$/.test(v)
			}],
	['validate-alphanum', 'Please use only letters (a-z) or numbers (0-9) only in this field. No spaces or other characters are allowed.', function(v) {
				return Validation.get('IsEmpty').test(v) ||  !/\W/.test(v)
			}],
	['validate-alphanum-space', 'Please use only letters (a-z) or numbers (0-9) only in this field.', function(v) {
				return Validation.get('IsEmpty').test(v) || /^[a-zA-Z0-9 ]+$/.test(v)
			}],
//	['validate-date', 'Please enter a valid date.', function(v) {
//				var test = new Date(v);
//				return Validation.get('IsEmpty').test(v) || !isNaN(test);
//			}],
	['validate-email', 'Proszę podać prawidłowy adres email.', function (v) {
				return Validation.get('IsEmpty').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
			}],
	['validate-url', 'Please enter a valid URL.', function (v) {
				return Validation.get('IsEmpty').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i.test(v)
			}],
	['validate-date', 'Proszę podać datę w formacie: rrrr-mm-dd.', function(v) {
				if(Validation.get('IsEmpty').test(v)) return true;
				var regex = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/;
				if(!regex.test(v)) return false;
				return true;
			}],
	['validate-selection', 'Please make a selection', function(v,elm){
				return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
			}],
	['validate-one-required', 'Proszę wybrać przynajmniej jedną opcję.', function (v,elm) {
				var p = $(elm.parentNode);
				var options = p.getElementsByTagName('INPUT');
				return $A(options).any(function(elm) {
					return $F(elm);
				});
			}],
	['validate-tags', 'Proszę podać prawidłową listę tagów oddzieloną przecinkami.', function (v,elm) {
			v = v.replace(/^\s+|\s+$/g, '');
			var tags = v.split(',');
			var regexp = /^[a-zA-Z0-9ęóąśłżźćńĘÓĄŚŁŻŹĆŃ]+$/;
			for(i = 0; i < tags.length; i++) {
				if(!regexp.test(tags[i].replace(/^\s+|\s+$/g, ''))) return false;
			}
			return true;
			}],
	['validate-movie-cats', 'Proszę wybrać od 1 do 3 kategorii.', function (v,elm) {
				var p = $(elm.up(1));
				var options = p.getElementsByTagName('INPUT');
				var count = 0;
				$A(options).each(function(elm) {
					if($F(elm)) count++;
				});
				return count > 0 && count <=3;
			}],
	['validate-movie-pass', 'To pole nie może być puste.', function(v) {
				return $('publication_private').checked && !Validation.get('IsEmpty').test(v);
			}],
	['validate-movie-code', 'Proszę podać poprawny kod.', function(v) {
		if( !( $('content_source_code').checked && !Validation.get('IsEmpty').test(v) ) ) return false;
		var regexps = $A();
		regexps[0] = /^<object width="[0-9]+"\s+height="[0-9]+">\s*<param name="movie" value="http:\/\/www.youtube.com\/v\/[0-9a-zA-z\-_=&]+"><\/param><param name="allowFullScreen" value="true"><\/param><.*?><embed(type)? src="http:\/\/www.youtube.com\/v\/[0-9a-zA-z\-_=&]+" type="application\/x-shockwave-flash" .*? width="[0-9]+" height="[0-9]+"><\/embed><\/object>$/;
		regexps[1] = /^<script type="text\/javascript" src="http:\/\/video.interia.pl\/player.js#[0-9]+,[0-9]+,[0-9]+"><\/script>$/;
		regexps[2] = /^<script type="text\/javascript" src="http:\/\/www.wrzuta.pl\/wrzuta_embed.js\?wrzuta_key=[a-zA-Z0-9]+\&wrzuta_flv=[a-zA-Z0-9\/:\.=\&_\-]+\&wrzuta_mini=[a-zA-Z0-9\/:\.=\&_\-%]+"><\/script>$/;
		regexps[3] = /^<object width="[0-9]+" height="[0-9]+"><param name="movie" value="http:\/\/patrz.pl\/patrz.pl.swf\?id=[0-9]+\&r=[0-9a-zA-Z]+\&o=[0-9a-zA-Z]*"><\/param><param name="wmode" value="transparent"><\/param><embed src="http:\/\/patrz.pl\/patrz.pl.swf\?id=[0-9]+\&r=[0-9a-zA-Z]+\&o=[0-9a-zA-Z]*" type="application\/x-shockwave-flash" wmode="transparent" width="[0-9]+" height="[0-9]+"><\/embed><\/object>$/;
		regexps[4] = /^<embed style="width:[0-9]+px; height:[0-9]+px;" id="VideoPlayback" type="application\/x-shockwave-flash" src="http:\/\/video.google.com\/googleplayer.swf\?docId=[0-9]+\&hl=[a-zA-Z0-9]+" flashvars=""> <\/embed>$/;
		regexps[5] = /^<embed src="http:\/\/www.metacafe.com\/fplayer\/[0-9]+\/[0-9a-zA-Z\_]+\.swf" width="[0-9]+" height="[0-9]+" wmode="transparent" pluginspage="http:\/\/www.macromedia.com\/go\/getflashplayer" type="application\/x-shockwave-flash"> <\/embed><br><font size = 1><a href="http:\/\/www.metacafe.com\/watch\/[0-9]+\/[0-9a-zA-Z_]+\/">[a-zA-Z0-9\.):\-_\s]+<\/a>[\s\-]+<a href="http:\/\/www.metacafe.com\/">[a-zA-z0-9\.\-\s,]+<\/a><\/font>$/;
		regexps[6] = /^<div><object width="[0-9]+" height="[0-9]+"><param name="movie" value="http:\/\/www.dailymotion.com\/swf\/[0-9a-zA-Z]+"><\/param><param name="allowfullscreen" value="true"><\/param><embed src="http:\/\/www.dailymotion.com\/swf\/[0-9a-zA-Z]+" type="application\/x-shockwave-flash" width="[0-9]+" height="[0-9]+" allowfullscreen="true"><\/embed><\/object><br \/><b><a href="http:\/\/www.dailymotion.com\/video\/[a-zA-Z0-9_\-]+">[a-zA-Z0-9\s]+<\/a><\/b><br \/><i>[a-zA-Z0-9:\?\s]+ <a href="http:\/\/www.dailymotion.com\/[a-zA-Z0-9_\-]+">[a-zA-Z0-9_\-]+<\/a><\/i><\/div>$/;
		regexps[7] = /^<a href="http:\/\/myspacetv.com\/index.cfm\?fuseaction=[a-zA-A0-9\.]+\&videoid=[0-9]+">[a-zA-Z0-9\-\.:()\s]+<\/a><br><embed src="http:\/\/lads.myspace.com\/videos\/vplayer.swf" flashvars="m=[0-9]+\&v=[0-9]+\&type=[0-9a-zA-Z]+" type="application\/x-shockwave-flash" width="[0-9]+" height="[0-9]+"><\/embed><br><a href="http:\/\/myspacetv.com\/index.cfm\?fuseaction=[a-zA-Z0-9\.]+\&videoid=[0-9]+\&title=[a-zA-Z0-9\-_\.:()\s]+">[a-zA-Z0-9\s]+<\/a> \| <a href="http:\/\/myspacetv.com\/index.cfm\?fuseaction=[0-9a-zA-Z\.]+">[0-9a-zA-Z\s]+<\/a>$/;
		v = v.replace(/^\s+|\s+$/g, '');
		v = v.replace('Å�', '');
		for(i = 0; i < regexps.length; i++) {
			if( regexps[i].test(v.replace(/\[/g, '<').replace(/\]/g, '>')) ) return true;
		}
		return false;
	}]

]);
