/*
* 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 first = 1;
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}); });              
              //var evt = (input.type == 'checkbox') ? 'change' : 'blur';
              //Event.observe(input, evt, function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });                 
			});
		}
	},
	onSubmit :  function(ev){
        var callback = this.options.onElementValidate;
        Form.getElements(this.form).each(function(input) { // Thanks Mike!
            Event.observe(input, 'keypress', function(ev) { Validation.validate(Event.element(ev),{useTitle : false, onElementValidate : callback}); });              
          //var evt = (input.type == 'checkbox') ? 'change' : 'blur';
          //Event.observe(input, evt, function(ev) { Validation.validate(Event.element(ev),{useTitle : useTitles, onElementValidate : callback}); });                 
        });        
    first = 0;       
		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);
                // for checkboxes, see if siblings have validate-one-required
                /*if(elm.type == 'radio' && !elm.hasClassName('validate-paymentmethod')) {
                  var p = elm.parentNode;
                        var siblings = p.getElementsByTagName('INPUT');
                        var validate_one_elm = $A(siblings).find(function(elm) {
                                return elm.hasClassName('validate-paymentmethod');
                        });
                        if( validate_one_elm != undefined ) { elm = validate_one_elm }
                }         
                */
                
		var cn = elm.classNames();
		return result = cn.all(function(value) {
        if(value.indexOf("required")!=-1 && first==1 ){
            var test=false;
            //console.log("req "+test);
            }
        else{
			var test = Validation.test(value,elm,options.useTitle);            
                //console.log("oth "+test);
			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 = '<span class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + errorMsg + '</div>'
                 //advice = '<div class="fielderror" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none"><div class="errorinfo"><a href="javascript:;" onclick="showInfoError(this)" onmouseover="highlight(this)" onmouseout="unlight()"><img src="/bilder/info-error-button.gif" alt="Info" class="screen"><img src="/bilder/info-error-button-druck.gif" alt="" class="print"></a></div><div class="errordesc" style="display:none">' + errorMsg + '</div></div>'
                 advice = '<div class="fielderror" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none"><div class="errorinfo"><a href="javascript:;" onclick="showInfoError(this)" onmouseover="highlight(this)" onmouseout="unlight()"><img src="/bilder/info-error-button.gif" alt="Info" class="screen"><img src="/bilder/info-error-button-druck.gif" alt="" class="print"></a></div><div class="errordesc" style="display:none">' + errorMsg + '</div></div>'					
                 switch (elm.type.toLowerCase()) {
						case 'checkbox':
                        var p = elm.parentNode;
                        var frow = p.parentNode;
                        Element.addClassName(frow,"errorformrow");                         
                        new Insertion.After(p, advice);
                        break;
						case 'radio':
							var p = elm.parentNode;  
                      var frow = p.parentNode;
                      Element.addClassName(frow,"errorformrow");    
							if(p) {
								new Insertion.After(p, advice);
							} else {
								new Insertion.Bottom(elm, advice);
							}         
                         
							break;
                     case 'textarea':
                        var p = elm.parentNode;
                        new Insertion.Bottom(p, advice);
                        break;
						default:
                        if(Element.hasClassName(elm,"calender")){
                            var p = elm.parentNode;
                            var f = p.parentNode;
                            //console.log(f.inspect());
                            var fi = Element.getElementsByClassName(f,"fieldicon"); 
                            Element.addClassName(f,"errorformrow");
                            new Insertion.After(fi[0], advice);
                            break;
                        }                      
                        var p = elm.parentNode;
                        var frow = p.parentNode;
                        //frow.addClassName('errorformrow');
                        Element.addClassName(frow,"errorformrow");
                        //console.log(frow.inspect());                        
                        new Insertion.After(p, advice);
				    }
					advice = Validation.getAdvice(name, elm);
				}
				if(typeof Effect == 'undefined') {
					advice.style.display = 'inline';
				} 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');
        var p = elm.parentNode;  
        var frow = p.parentNode;
        Element.removeClassName(frow,"errorformrow");              
			return true;
		}
		} catch(e) {
			throw(e)
		}
	},
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		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) {
      //if(first != 1){
        //console.log("first: "+first+((v == null) || (v.length == 0)));      
        return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
      //}
      //else{
        //console.log("first: "+first+" not validated"); 
        //return true;
      //}              
});                      

Validation.add('validate_socid', 'Vänligen kontrollera ditt personnummer (det angivna personnumret stämmer inte).', function(nr) {
	valid=false;    
    
	if(!nr.match(/^(\d{2})(\d{2})(\d{2})\-(\d{4})$/)){ return false; }
    console.log(nr);
	now=new Date(); nowFullYear=now.getFullYear()+""; nowCentury=nowFullYear.substring(0,2); nowShortYear=nowFullYear.substring(2,4);
	year=RegExp.$1; month=RegExp.$2; day=RegExp.$3; controldigits=RegExp.$4;
	fullYear=(year*1<=nowShortYear*1)?(nowCentury+year)*1:((nowCentury*1-1)+year)*1;
	var months = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
	if(fullYear%400==0||fullYear%4==0&&fullYear%100!=0){ months[1]=29; }
	if(month*1<1||month*1>12||day*1<1||day*1>months[month*1-1]){ return false; }
	alldigits=year+month+day+controldigits;
	var nn="";
	for(var n=0;n<alldigits.length;n++){ nn+=((((n+1)%2)+1)*alldigits.substring(n,n+1)); }
	checksum=0;
	for(var n=0;n<nn.length;n++){ checksum+=nn.substring(n,n+1)*1; }
	//valid=(checksum%10==0)?true:false;
    console.log(checksum%10==0);
   return (checksum%10==0)?true:false;
	//sex=parseInt(controldigits.substring(2,3))%2;
/*    
    function validatePersonalIdNumber($personal_id_number) {
        $personal_id_number = ereg_replace("[^0-9]",'',$personal_id_number);
        if (ereg('^[0-9]{10}$', $personal_id_number)) {
            $sum = 0;
            for ($i = 0; $i < strlen($personal_id_number) - 1; $i++ ) {
                $number = substr($personal_id_number, $i, 1);
                if ($i % 2 == 0) {
                    $number = $number * 2;
                    if ($number > 9) {
                        $tmp = substr($number,0,1) + substr($number,1,1);
                        $number = $tmp;
                    }
                }
                $sum += $number;
            }
            $check_sum = substr($sum, strlen($sum) - 1, 1);
            if ($check_sum > 0) {
                $check_sum = 10 - $check_sum;
            }
            if ($check_sum != substr($personal_id_number,9,1)) {
                $this->addMessage('soc_id', null, 'validate-socid');
            }
        }
        else {
            $this->addMessage('soc_id', null, 'required-socid');
        }
        return $personal_id_number;
    }*/    
});
                              

Validation.add('class-name', 'errmess', {
     pattern : new RegExp("^[a-zA-Z0-9'`ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþÿ][.][,][-][\p{space}]+$","gi"), // only letter allowed
     minLength : 6, // value must be at least 6 characters
     maxLength : 13, // value must be no longer than 13 characters
     min : 5, // value is not less than this number
     max : 100, // value is not more than this number
     notOneOf : ['password', 'PASSWORD'], // value does not equal anything in this array
     oneOf : ['fish','chicken','beef'], // value must equal one of the values in this array
     is :  '5', // value is equal to this string
     isNot : 'turnip', //value is not equal to this string
     equalToField : 'password', // value is equal to the form element with this ID
     notEqualToField : 'username', // value is not equal to the form element with this ID
     include : ['validate-alphanum'] // also tests each validator included in this array of validator keys (there are no sanity checks so beware infinite loops!)
}); 
            
Validation.addAllThese([
    ['required', 'Vänligen fyll i...', 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-date', 'Please enter a valid date.', function(v) {
                var test = new Date(v);
                return Validation.get('IsEmpty').test(v) || !isNaN(test);
            }],
    ['validate-email', 'Vänligen kontrollera din e-postadress. Ska se ut som t ex namn@domän.se', 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-au', 'Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.', function(v) {
                if(Validation.get('IsEmpty').test(v)) return true;
                var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
                if(!regex.test(v)) return false;
                var d = new Date(v.replace(regex, '$2/$1/$3'));
                return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) && 
                            (parseInt(RegExp.$1, 10) == d.getDate()) && 
                            (parseInt(RegExp.$3, 10) == d.getFullYear() );
            }],
    ['validate-currency-dollar', 'Please enter a valid $ amount. For example $100.00 .', function(v) {
                // [$]1[##][,###]+[.##]
                // [$]1###+[.##]
                // [$]0.##
                // [$].##
                return Validation.get('IsEmpty').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
            }],
    ['validate-selection', 'Please make a selection', function(v,elm){
                return elm.options ? elm.selectedIndex > 0 : !Validation.get('IsEmpty').test(v);
            }],
    ['validate-one-required', 'Please select one of the above options.', function (v,elm) {
                var p = elm.parentNode;
                var options = p.getElementsByTagName('INPUT');
                return $A(options).any(function(elm) {
                    return $F(elm);
                });
            }]
]);
