// Zusatz zu
// FISFormValidator Version 0.88
// FISolution
// 10. Juli 2009 16:52:54
// Uses mootools-beta-1.2b1-compatible.js


var FISFV = new Class({
	// Optionen Implementieren
	Implements : [Options],
	
	// Default Optionen setzen
	options : {
		
	},
	form: null,
	fields: null,
	validations: null,
	
	// init
	initialize: function(formId, options) {
		// optionen übernehmen
		this.setOptions(options);
		
		this.fields = new Array();
		this.validations = new Array();
		
		this.form = $(formId);
		
		this.form.FISFViframecounter = 0;
		
		this.form.validateFVForm = function(e) {
			var status = true;
			for(var i = 0; i < this.fields.length; i++) {
				status = this.fields[i].validate() && status;
			}
			if(status) { 
				var progressUrl = this.form.getAttribute('statusbaruploadurl');
				if(progressUrl && progressUrl != null) {
					var use_controlled = false;
					for(var i = 0; i < this.fields.length; i++) {
						if(this.fields[i].type && this.fields[i].type == 'file' && this.fields[i].value.trim() != '') {
							use_controlled = true;
							break;
						}	
					}
					if(use_controlled) {
						new Event(e).stop();
						this.form.sendControlled(progressUrl);
					}
				}
				return true;
			}
			else {
				return false;
			}
		}.bind(this);
		
		this.form.FISFV = this;
		this.form.addEvent('submit', this.form.validateFVForm.bind(this));
		
		this.form.sendControlled = function(progressUrl) {
			this.form.originalTarget = this.form.getAttribute('target');
			this.form.originalAction = this.form.getAttribute('action');
			this.form.action = progressUrl + '?anticache=' + Math.round(Math.random() * 10000000); 
				
			var centerBox = null;
			var showCenterBox = function(content, width, height) {
				var trans = new Element('div', {
					'styles': {
						'background-color': 'white',
						'opacity': 0,
						'position': 'absolute',
						'z-index': 1000
					}
				} );
				centerBox = trans;
				
				var box = new Element('div', {
					'class': 'centerBox',
					'styles': {
						'opacity': 0
					}
				});
				box.inject($(document.body));
				var inner = new Element('div', {
					'styles': {
						'margin': 10			
					}
				});
				if(content.innerHTML || content.innerHTML == '') content.inject(inner);
				else inner.innerHTML = content;
				inner.inject(box);
				if(width) {
					box.setStyles( { 'width': width } );
				}
				else {
					width = box.getSize().size.x;
				}
				if(height) {
					box.setStyles( { 'height': height} );
				}
				else {
					height = box.getSize().size.y;
				}
				var pos = box.getPosition();
				
				var fx1 = new Fx.Styles(box, { duration: 400, wait: false, onComplete:function() {
					if(box.removed) {
						box.remove();					
					}		
				} }).start({ opacity: 1 });	
				
				trans.inject($(document.body));
				var fx2 = new Fx.Styles(trans, { duration: 400, wait: false, onComplete:function() {
					if(trans.removed) {
						trans.remove();					
					}				
				} }).start({ opacity: 0.9 });
				box.trans = trans;
				trans.close = function() {
					trans.removed = box.removed = mailCloseIcon = 1;
					fx1.start({ opacity: 0 });
					fx2.start({ opacity: 0 });
					if(fx3) fx3.start({ opacity: 0 });
				}
				var fxBox = new Fx.Styles(box, { duration: 800, wait: false });	
				var smooth = false;
				window.addEvent('scroll', function() {
					trans.setStyles( {
						'top': window.getScrollTop(),
						'left': window.getScrollLeft(),
						'width': '100%',
						'height': '100%'
					});
					
					var h = (window.innerHeight ? window.innerHeight : document.body.clientHeight);
					if(height && h > height) h = height;
					var w = (window.innerWidth ? window.innerWidth : document.body.clientWidth);
					if(width && w > width) w = width;
					
					var top = window.getScrollTop() + (window.innerHeight ? window.innerHeight : document.body.clientHeight) / 4 - h / 2;
					var left = window.getScrollLeft() + (window.innerWidth ? window.innerWidth : document.body.clientWidth) / 2 - w / 2;
					
					
					if(top < 15) top = 15;
					if(left < 15) left = 15;
					
					if(!smooth) {
						smooth = true;
						fxBox.set( {
							'top': top,
							'left': left,
							'width': w,
							'height': h
						});
					}
					else {
						fxBox.start( {
							'top': top,
							'left': left,
							'width': w,
							'height': h
						});
					}
				}); 
				
				window.addEvent('resize', function() {
					window.fireEvent('scroll');
				}); 
				window.fireEvent('scroll');
			}
			var closeCenterBox = function(status, lines) {
				this.form.target = this.form.originalTarget == null ? '_self' : this.form.originalTarget;
				this.form.action = this.form.originalAction == null ? document.location.href : this.form.originalAction;
				
				if(status) {
					var i = 0;
					var next = true;
					for(i = 1; i < lines.length; i++) {
						var line = lines[i];
						var tmp = line.split(/ /);
						var fieldName = tmp[0];
						var data = tmp[1];
						var inputs = this.form.getElements('input');
						var j = 0;
						for(j = 0; j < inputs.length; j++) {
							var input = inputs[j];
							if(input.type == 'file' && input.name == fieldName) {
								new Element('input', {
									type: 'text',
									name: 'filepost[' + fieldName + ']',
									value: data
								}).injectBefore(input);	
								input.remove();
							}
						};
					}
					this.form.submit();
				}
				else {
					window.setTimeout(centerBox.close, 3000);
				}	
			}.bind(this);
						
			
			this.form.FISFViframecounter++;
			
			var debug = false;
			
			var iframecounter = 0;
			var status = new Element('div', {
				id: 'progressbar',
				styles: {
					'display': 'block'
				}
			});
			
			var div = new Element('div');
			var span = new Element('div', {'class': "uploadprogress_caption"}).setHTML('Uploadvorgang wird durchgeführt');
			span.inject(div);
			status.inject(div);
			showCenterBox(div, 500, 60, true);
			
			this.form.uploadId = parseInt(Math.round(Math.random() * 100) + this.form.FISFViframecounter * 1000);
			this.form.uploadPercent = 0;
			this.form.uploadSpeed = 0;
			
			var dt_start = null;
			
			if(!status.sd) {
				status.sd = new Element('div', {
					'class': 'progressbar_percent progressbar_percent_l50',
					'styles': {
						position: 'absolute',
						left: 0,
						top: 0
					}
				});
				status.sd.inject(status);
				status.sd.setHTML('...initialisiere Upload...');
			
				status.si = new Element('div', {
					'class': 'progressbar_bar',
					'styles': {
						width: 0
					}
				});
				status.si.inject(status);
			}
			status.si.interval = null;
			status.si.setStatus = function(done, total) {
				var percent = (Math.round(done / total * 10) / 10);
			//	status.si.setHTML(percent + '%');
				status.si.done = done;
				status.si.donetime = new Date().getTime() / 1000 - dt_start;
				status.si.avg = status.si.done / status.si.donetime;
				
				if(status.si.interval == null) {
					status.si.total = total;
					status.si.interval = window.setInterval(function() {
						status.si.setPercent();
					}, 100);
				}
			};
			
			status.si.setPercent = function(percent) {
				if(!percent) {
					var donetime = new Date().getTime() / 1000 - dt_start;
					percent = status.si.avg * donetime / status.si.total * 100;
					if(percent > 100) percent = 100;
				}
				status.si.setStyle('width', percent + "%");
				status.sd.className = status.sd.className.replace(/progressbar_percent_.../, '') + ' ' + (percent < 50 ? 'progressbar_percent_l50' : 'progressbar_percent_u50');
				if(percent < 100) {
					status.sd.setHTML(Math.round(percent) + " %");
				}
				else {
					status.sd.setHTML('... Verarbeite, bitte warten ...');
				}
			}
			
			this.form.uploadIframe = new Element('iframe', {
				'name': "upload_iframe_" + this.form.FISFViframecounter,
				'styles': {
					'width': 800,
					'height': 500,
					'display': (!debug ? 'none' : '')
				},
				'src': ''
			});
			this.form.uploadIframe.injectBefore(this.form);
			this.form.target = this.form.uploadIframe.name;
		
			if(!this.form.uploadField) {
				this.form.uploadField = new Element('input', {
					'name': 'UPLOAD_IDENTIFIER',
					'type': 'hidden',
					'value': this.form.uploadId
				});
				this.form.uploadField.injectBefore(this.form.getChildren()[0]);				
			}
			
			var checkTimeout = null;
			
			var uploadStatus = 0;
			
			this.form.readAjaxStatus = function() {
				if(this.form.percent == 100) return;
				new Ajax(progressUrl + '?id=' + this.form.uploadId + '&check&anticache=' + Math.random(), {
					method: 'get', 
					evalScripts: false, 
					onSuccess: function(response) {
						var now = new Date();
						
						var curStatus = null;
						if(document.frames) {
							curStatus = document.frames[this.form.uploadIframe.name].document.body.innerHTML.split(/\|/);
						}
						else {
							curStatus = this.form.uploadIframe.contentDocument.body.innerHTML.split(/\|/);
						}
						
						if(uploadStatus < 1 && curStatus[0] == '') {
							status.sd.setHTML('... Initialisiere, bitte warten ...');
							uploadStatus = 1;
						}
						else if(curStatus[0] == 'UPLOAD DONE') {	
							uploadStatus = 3;
							window.clearInterval(checkTimeout);
							
							window.clearInterval(status.si.interval);
							status.si.setPercent(100);
							
							closeCenterBox(true, curStatus);
						}
						else if(curStatus[0] == 'UPLOAD ERR') {
							window.clearInterval(checkTimeout);
							window.clearInterval(status.si.interval);
					
							status.si.setPercent(100);
							status.si.className += ' progressbar_bar_error';
							
							status.sd.setHTML('... Fehler beim Upload ...');
							status.sd.setStyle('color', 'white');
							
							closeCenterBox(false);
						}
						else {
							var response = response.split(/\n/);
							var f = parseFloat(response[0]);
							if(uploadStatus == 2 && f == 0) {
								window.clearInterval(status.si.interval);
								status.si.setPercent(100);
							}
							else if(f > 0) {
								uploadStatus = 2;
								status.si.setStatus(response[0], response[1]);								
							}
						}						
					}.bind(this)
				}).request();
			}.bind(this);
			
			window.setTimeout(function() {
				dt_start = new Date().getTime() / 1000;
				this.form.submit();
			}.bind(this), 100);
			checkTimeout = window.setInterval(this.form.readAjaxStatus, 1000);
						
		}.bind(this);
		
	},
	registerField: function(id) {
		var field = $(id);
		if(field == null) return;
		field.validations = new Array();
		field.addValidations = function(validationsArray) {
			field.validations[field.validations.length] = validationsArray;
		}
		field.validate = function() {
			if(!field.setEvents) {
				var tag = field.tagName.toString().toLowerCase().trim();
				if(tag == 'input' && (field.type == 'radio' || field.type == 'checkbox')) {
					field.addEvent('click', function() { field.validate(); });
					field.addEvent('change', function() { field.validate(); });		
				}
				else {
					field.addEvent('keyup', function() { field.validate(); });
					field.addEvent('change', function() { field.validate(); });	
				}
				field.setEvents = true;
			}
			var error = false;
			var or_sub_res = false;
			for(var i = 0; i < field.validations.length; i++) {
				// DIESE HIER ALLE "UND"-VERKNÜPFT
				var or_res = false;
				for(var j = 0; j < field.validations[i].length; j++) {
					// DIE HIER ALLE "ODER"-VERKNÜPFT
					if(!or_res && !error) {
						or_sub_res = field.validations[i][j].validate(field);
					}
					else {
						or_sub_res = true;
					}
					field.validations[i][j].showError(or_sub_res);
					if(or_sub_res) {
						or_res = true;
					}
				}
				error = (error | !or_res);
			}
			return !error;
			
		}.bind(this);
		field.errorDiv = false;
		field.pendingErrors = new Array();
		field.setMessage = function(validation, valid) {
			if(valid) {
				if(this.errorDiv && this.errorDiv.validatorId == validation.id) {
					this.errorDiv.remove();
					this.errorDiv = false;
					
					if(this.pendingErrors.length > 0) {
						var tmp = this.pendingErrors;
						var err = this.pendingErrors[0];
						this.pendingErrors = new Array();
						for(var i = 1; i < tmp.length; i++) {
							this.pendingErrors[i - 1] = tmp[i];
						}
						this.setMessage(err, false);
					}
				}
				return;
			}
			if(!this.errorDiv) {
				var behind = field;
				var tag = field.tagName.toString().toLowerCase().trim();
				if(tag == 'input' && (field.type == 'checkbox' || field.type == 'radio')) {
					$$('label').each(function(label) {
						if(label.getAttribute('for') == field.id) {
							behind = label;
						}
					});
				}
				var pos = behind.getPosition('main');
				this.errorDiv = new Element('div', {
					'class': 'FV_error_display_top',
					'styles': {
						position: 'absolute',
						left: pos.x + behind.offsetWidth + 5,
						top: pos.y
					}
				});
				this.errorDiv.validatorId = validation.id;
				var inner = new Element('div' , {
					'class': 'FV_error_display',
					'styles': {
						overflow: 'hidden'
					}
				});
				inner.setHTML(validation.errorMsg).inject(this.errorDiv);
				this.errorDiv.injectAfter(behind);
				return;
			}
			else if(this.errorDiv.validatorId != validation.id) {
				for(var i = 0; i < this.pendingErrors.length; i++) {
					if(this.pendingErrors[i] == validation) {
						return;
					}
				}
				this.pendingErrors[this.pendingErrors.length] = validation;			
			}
			
		}
		this.fields[this.fields.length] = field;
	},
	addValidation: function(id, validationArray) {
		var field = $(id);
		if(field) field.addValidations(validationArray);
	}
});

var fieldNulls = new Array();
var fieldIds = new Array();

var FISFValidation = new Class({
	id: 0,
	errorMsg: null, 
	expects: null,
	option: null,
	displayAt: null,
	field: null,
	initialize: function(id, field_id, expects, option, errorMsg, displayAt) {
		this.field = $(field_id);
		
		var maybenull = false;
		var found = -1;
		for(var i = 0; i < fieldIds.length; i++) {
			if(fieldIds[i] == field_id) {
				found = i;
				maybenull = fieldNulls[i];
				break;
			}
		}
		
		maybenull = maybenull || (expects == 'null');
		if(this.field) this.field.className = this.field.className.replace(/\s*FV_validation_required\s*/, ' ');
		if(found == -1) {
			fieldNulls[fieldIds.length] = maybenull;			
			fieldIds[fieldIds.length] = field_id;
		}
		else {
			fieldNulls[found] = maybenull;	
		}
		if(!maybenull && this.field) {
			this.field.className = this.field.className + " FV_validation_required ";
		}
		
		this.id = id;
		this.expects = expects;
		this.option = option;
		this.errorMsg = errorMsg;
		if(this.errorMsg.trim() == '') this.errorMsg = 'expects ' + expects
		this.displayAt = displayAt;
		
		if(expects == 'zip') {
			if($(option)) {
				var setZipLength = function() {
					var state = $(option).getValue();
					var maxLength = 5;
					if(false) maxLength = 5;
					else if(state == "A") maxLength = 4;
					else if(state == "B") maxLength = 4;
					else if(state == "CH") maxLength = 4;
					else if(state == "CZ") maxLength = 5;
					else if(state == "D") maxLength = 5;
					else if(state == "DK") maxLength = 4;
					else if(state == "F") maxLength = 5;
					else if(state == "I") maxLength = 5;
					else if(state == "GB") maxLength = 8;
					else if(state == "L") maxLength = 4;
					else if(state == "NL") maxLength = 7;
					else if(state == "PL") maxLength = 6;
					else if(state == "SK") maxLength = 5;
					else if(state == "SRB") maxLength = 5;
					this.field.maxLength = maxLength;
					this.field.value = this.field.value.substr(0, maxLength);					
				}.bind(this);
				$(option).addEvent('change', function() {
					setZipLength();
				});
				setZipLength();
			}
			else {
				this.field.maxLength = 5;
			}
		}
		
	},
	showError: function(valid) {
		var obj = this.displayAt ? this.displayAt : this.field;
		obj.setMessage(this, valid);
	},
	validate: function() {
		var field = this.field;
		var tag = field.tagName.toString().toLowerCase().trim();
		var value = field.getValue().toString().trim();
		if(tag == 'input' && field.type == 'file') {
			value = field.value.trim();
		}
		if(tag == 'input' && field.type == 'checkbox') {
			if(this.expects != 'checked') {
				return false;	
			}
			else {
				return field.checked;
			}
		}
		else if(tag == 'input' && field.type == 'radio') {
			value = field.value.trim();
			if(this.expects == 'value' && value == this.option) {
				return field.checked;
			}
			else {
				return false;
			}		
		}
		
		
		switch(this.expects) {
			case 'url':
				return value.test(/^((https?|ftp):\/\/|www\.)[a-z0-9_\.öäüÖÄÜ-]+\.[a-z]{2,4}$/i);
			case 'email':
				return value.test(/^[\d\w\.\-]+@[\d\w\.\-]+\.[a-z]{2,4}$/i);
			
			case 'integer':
				return value.test(/^\d+$/);
			case 'float':
				return value.test(/^(-?)\d+(\.\d+)?$/);
			
			case 'notnull':
				return value.test(/./);
			case 'null':
				return value.test(/^$/);
			
			case 'preg':
				return value.test(this.option);
			
			case 'zip':
				var state = $(this.option);
				if(state) state = state.getValue();
				
				if(!state || state == 'D' || state == 'CZ' || state == 'F' || state == 'FIN' || state == 'S' || state == 'SK' || state == 'I') {
					return value.test(/^\d{5}$/);
				}
				else if(state == 'A' || state == 'B' || state == 'CH' || state == 'DK' || state == 'L') {
					return value.test(/^\d{4}$/);
				}
				else if(state == 'PL') {
					return value.test(/^\d{2}\-\d{3}$/);
				}
				else if(state == 'NL') {
					return value.test(/^\d{4} [A-Z]{2}$/g);
				}
				else if(state == 'GB') {
					return value.test(/^[A-Z](\d|\d{2}|\d[A-Z]|[A-Z]\d{1,2}|[A-Z]\d[A-Z]) \d[A-Z]{2}$/g);
				}
				else {
					return true;
				}
				
			case 'same':
				var other = $(this.option);
				if(!other) return true;
				if(other.validate && !other.validate()) return true;
				var otherValue = other.getValue().toString().trim();
				return (value == otherValue);
			
			case 'greater':
				if(!_FISFVvalidate(value, 'float', null)) return false;
				return (value > this.option);
			case 'greater_equal':
				if(!_FISFVvalidate(value, 'float', null)) return false;
				return (value >= this.option);
			case 'smaller':
				if(!_FISFVvalidate(value, 'float', null)) return false;
				return (value < this.option);
			case 'smaller_equal':
				if(!_FISFVvalidate(value, 'float', null)) return false;
				return (value < this.option);
			case 'minlength':
				return (value.length >= this.option);
			case 'maxlength':
				return (value.length <= this.option);
			case 'value':
				return (value == this.option);
			
			case 'file':
				return value.test(/./);
			case 'image':
				return value.test(/\.(jpe?g|png|gif)$/i);
			case 'pdf':
				return value.test(/\.(pdf)$/i);
			case 'filesizemax':
				return true;
				
			case 'germandate':
				var s = value.split(/\./);
				if(s.length != 3) return false;
				var d = s[0];
				var m = s[1];
				var y = s[2];
				if(!d.test(/^\d+$/)) return false;
				if(!m.test(/^\d+$/)) return false;
				if(!y.test(/^\d+$/)) return false;
				d = d * 1;
				m = m * 1;
				y = y * 1;
				if(y < 100 && y > 70) {
					y = parseInt(y) + 1900;
				}
				if(y < 100) {
					y = parseInt(y) + 2000;
				}
				if(y < 1000) return false;
				var date = new Date();
				date.setDate(d);
				date.setMonth(m-1);
				date.setDate(d);
				date.setFullYear(y);
				var d2 = parseInt(date.getDate());
				var m2 = parseInt(date.getMonth()) + 1;
				var y2 = parseInt(date.getYear());
				if(y2 < 200) y2 += 1900;
				return (d2 == d && m2 == m && y2 == y);
			
			case 'function': 
				if(this.option) {
					return this.option(value, this);	
				}
				alert("FNF");
				return false;
		}
		return false;
	}
});
