/*
 * Really easy field validation with Prototype
 * http://tetlaw.id.au/view/blog/really-easy-field-validation-with-prototype
 * Andrew Tetlaw
 * Version 1.5.2 (2006-06-25)
 *  
 * http://creativecommons.org/licenses/by-sa/2.5/
 */
 
 
Validator = Class.create();

Validator.prototype = {
	initialize : function(className, error, test, options) {
		this.options = Object.extend({}, options || {});
		this._test = test ? test : function(v,elm){ return true };
		this.error = error ? error : 'Validation failed.';
		this.className = className;
	},
	test : function(v, elm) {
		return this._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) {
            try {
                Form.getElements(this.form).findAll(function(elm){return $(elm).hasClassName('validation-failed')}).first().focus()
		    } catch ( e ) {
            }
    }
		this.options.onFormValidate(result, this.form);

        //added by Nir Levy, 22/11/06
        //If the programer wanted form level validation and the validation failed
        //then i want to change to field level validation so the user can corrent
        //his errors and see immediate result.
        if ( !result && !this.options.immediate  ) {
            this.options.immediate = true;
            useTitles = this.options.useTitles;
            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}); });
            });
        }
        //

        return result;
	},
	reset : function() {
		Form.getElements(this.form).each(Validation.reset);
	}
}

//------------------------------------------------
function insertIframe(obj){
	var ieMat=document.createElement('IFRAME'+obj.name);
	alert("ieMat="+ieMat);
	alert("obj="+obj.id);
	
	ieMat.src="empty.html";//empty page

    ieMat.scrolling="no";
    ieMat.frameBorder="0";

    //the iframe's height && width has to be the same as the popup's
    ieMat.style.width=obj.offsetWidth+"px";
    ieMat.style.height=obj.offsetHeight+"px";

    //visually - the iframe behind the popup
    ieMat.style.zIndex="-1";

    //mouse - the z-index is not enough the iframe has to be before the popup div

	//new Insertion.After(ieMat, obj);
    //obj.insertBefore(ieMat, obj.children[0]);
    
   /// alert("sdfsf");
    //visually - the popup infont of the iframe
    obj.style.zIndex="101";
    window.status="creating iframe";	
}
//------------------------------------------------

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();
		var style = "";
		if (navigator.appName.indexOf('Netscape') != -1){
			style = "position:relative"
		}
        if ( name == "validate-title") {
            var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
	        
	        advice = '<div class="validation-advice" style = "' + style +'" id="advice-' + name + '-' + Validation.getElmID(elm)+'" style="display:none" ' + ' onclick="Validation.reset(this);"> &nbsp;'+ errorMsg + '</div>&nbsp;'
		    new Insertion.After(elm, advice);
		    advice = $('advice-' + name + '-' + Validation.getElmID(elm));
            advice.style.display = 'block';
            elm.addClassName("errorMessage_" + elm.name);
           // new Effect.Appear(advice, {duration : 0.3, to: 0.9 });
        }
        // Yossi Rubinroit 21.02.07: added some style to the div - image to close advice + nobr + changed the affects duraction appear / fade
        else if(Validation.isVisible(elm) && !v.test($F(elm), elm)) {
			if(!elm[prop]) {
				var advice = Validation.getAdvice(name, elm);
                //if(typeof advice == 'undefined') {
                //alert(advice);
					var errorMsg = useTitle ? ((elm && elm.title) ? elm.title : v.error) : v.error;
					advice = '<div  class="validation-advice" style = "' + style +'" id="advice-' + name + '-' + Validation.getElmID(elm)+'" style="display:none" ' + ' onclick="Validation.reset(this);"> &nbsp;' + errorMsg + '</div>&nbsp;'
					
					//advice = '&nbsp;<div class="validation-advice" id="advice-' + name + '-' + Validation.getElmID(elm) +'" style="display:none">' + '<nobr><img src="/RealCMS/Ext/Img/CVTSA/general/close_but.gif" align="absmiddle" style="cursor:hand" onclick="new Effect.Fade(this.parentElement.parentElement,  {duration : 0.4});">' + errorMsg + '</nobr></div>'					
					new Insertion.After(elm, advice);
					advice = $('advice-' + name + '-' + Validation.getElmID(elm));
					advice.style.display = 'block';
	
	//				var el2 = '<iframe src="empty.html" id="advice-iframe-'+ name + '-' + Validation.getElmID(elm)+'" scrolling="no" frameBorder="0" style="width:'+advice.offsetWidth+'px;  height:'+advice.offsetHeight+'px; z-index:99;position:absolute;"></iframe>';
	//				new Insertion.After(elm, el2);
					
					
				//}				
				
			}
			elm[prop] = true;
			elm.removeClassName('validation-passed');
			elm.addClassName('validation-failed');
            return false;
		} else {
			var iframeObj =$('advice-iframe-'+ name + '-' + Validation.getElmID(elm));
			if(typeof iframeObj != 'undefined') iframeObj.hide();
			var advice = Validation.getAdvice(name, elm);
			if(typeof advice != 'undefined') advice.hide();
			elm[prop] = '';
			elm.removeClassName('validation-failed');
			elm.addClassName('validation-passed');
			return true;
		}

    },
	isVisible : function(elm) {
		while(elm.tagName != 'BODY') {
			if(!$(elm).visible()) return false;
			elm = elm.parentNode;
		}
		return true;
	},
	getAdvice : function(name, elm) {
		return Try.these(
			function(){ return $('advice-' + name + '-' + Validation.getElmID(elm)) },
			function(){ return $('advice-' + Validation.getElmID(elm)) }
		);
	},
	getElmID : function(elm) {
		return elm.id ? elm.id : elm.name;
	},
	reset : function(elm) {
 //       alert("reset:" + elm.name);
        elm = $(elm);
		var cn = elm.classNames();
//        alert(cn);
        cn.each(function(value) {
            if ( value.indexOf('errorMessage') != -1 ) {
//            	alert("reset:" + elm.name);
                advice = $('advice-' + 'validate-title' + '-' + Validation.getElmID(elm));
                advice.hide();
                return;
            }
            var prop = '__advice'+value.camelize();
			if(elm[prop]) {
				var advice = Validation.getAdvice(value, elm);
//              alert("advice: " + advice );
                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] : new Validator();
	},
		
	showErrorMessage : function(  message, element ) {
	    element.title=message;
		Validation.test('validate-title',element,true);		
	},
	
	methods : {}
});

Validation.add('IsEmpty', '', function(v) {
				return  ((v == null) || (v.length == 0)); // || /^\s+$/.test(v));
			});


