//***********************************
// Validador de datos
// Version: 2.1
// Desarrollado en Nov, 2008
// Pogramador: Ivan Mattoni
//***********************************

var Validator={
	// PROPERTIES PUBLIC
	init: {
		root: '',
		classname: {
			msgbox               :  'validator_MSGBOX',
			border_top_left      :  'validator_MSGBOX_top_left',
			border_top           :  'validator_MSGBOX_top',
			border_top_right     :  'validator_MSGBOX_top_right',
			border_left          :  'validator_MSGBOX_left',
			inner                :  'validator_MSGBOX_inner',
			border_right         :  'validator_MSGBOX_right',
			border_bottom_left   :  'validator_MSGBOX_bottom_left',
			mark                 :  'validator_MSGBOX_mark',
			border_bottom_right  :  'validator_MSGBOX_bottom_right',
			icon                 :  'validator_ICON'
		},
		path:{
			link_css: '',
			script_securimage: ''
		}
	},
	
	configure: {
		show_alert: true,
		dinamic: false
	},
	error: 0,
	objects: {},
	Err: {
		error:0,
		description:'',
		objectname: '',
		_reset: function(){
			this.error=0;
			this.description="";
			this.objectname="";
		}
	},
	on_finalizer: function(){},
	working: false,
	


	// METHODS PUBLIC
	set_objects: function(){		
		var prop= "required: false,";
		prop+="string: true,";
		prop+="alphanumeric: false,";
		prop+="ismail: false,";
		prop+="max: 0,";
		prop+="min: 0,";
		prop+="confirm_password: '',";
		prop+="securimage: false,";
		prop+="message_required: '',";
		prop+="message_string: '',";
		prop+="message_ismail: '',";
		prop+="message_min: '',";
		prop+="message_max: '',";
		prop+="message_securimage: '',";
		prop+="message_confirmpassword: '',";
		prop+="style_msgbox: {}";

		for(var i=0; i<=arguments.length-1; i++){
			o = this._$(arguments[i]);
			if( o ){				
				eval("this.objects."+arguments[i]+"={"+prop+"};");

				this._objects_name[i] = arguments[i];
				if( this.configure.dinamic ){
					this._add_event(o, "change", "Validator._edit=true");
					this._add_event(o, "focus", "Validator._edit=false");
					this._add_event(o, "blur", "if( Validator._edit ) {Validator.validate(event)}");
				}
			}
		}
		
		if( !this.configure.show_alert ){
			path = (this.init.path.link_css=="") ? this.init.root+'/stylemsgbox.css' : this.init.path.link_css;
			var headID = document.getElementsByTagName("head")[0];
			var cssNode = document.createElement('link');
				cssNode.type = 'text/css';
				cssNode.rel = 'stylesheet';
				cssNode.href = path;
				headID.appendChild(cssNode);
		}
	},

	validate: function(e){
		if( this.working ) return;
		this.working=true;
		
		if( this.configure.dinamic ){
			if (!e) var e = window.event;
			if (e.target) targ = e.target;
			else if (e.srcElement) targ = e.srcElement;
			if (targ.nodeType == 3) // defeat Safari bug
				targ = targ.parentNode;

			if( targ.id && targ.id!="" )
				this._execute_validate(targ.id);
								
			if( !this._object_msgbox ) this.working=false;
			
		}else{
			for(var i=0; i<=this._objects_name.length-1; i++){
				if( !this._execute_validate(this._objects_name[i]) )
					break;
			}			
			
			if( this.configure.show_alert ){
				this.working=false;
				if( this.Err.error==0 ){
					Validator.on_finalizer();
				}
				
			}else{
			
				if( this.Err.error==0 && i==this._objects_name.length ){
					if( this._object_msgbox ){
						this._tempID = setInterval("Validator._to_verify();", 5);					
						setTimeout("clearInterval(Validator._tempID)", 3000);
					}else{				
						this.working=false;
						Validator.on_finalizer();
					}
				}
			}
		}		
	},

	show_message_special: function(id, msg){
		this.Err.description = msg;		
		this._show_message(id);
	},




	// PROPERTIES PRIVATE
	_objects_name: Array(),
	_edit: false,
	_XMLHttp: false,
	_object_msgbox: false,
	_tempID: false,
	

	// METHODS PRIVATE
	_$: function(id){
		return document.getElementById(id);	
	},
		
	_to_verify: function(){
		if( !this._object_msgbox ) {
			clearInterval(Validator._tempID);
			this.working=false;
			Validator.on_finalizer();
		}
	},

	_execute_validate: function(name){
		o = this._$(name);
		
		// REQUIRED
		if( this.Err.error==0 || this.Err.error=="required" ){
			if( this._read_data("objects", name, "required") ){				
				if( o.value.length==0 ){
					this.Err.error = "required";
					this.Err.description = this._read_data("objects", name, "message_required");
					this.Err.objectname = name;
					this._show_message(name);
					return;
				}else{
					if( this.Err.error!=0 ) this.Err._reset();
				}
			}
		}

		// STRING
		if( this.Err.error==0 || this.Err.error=="string" ){
		if( !this._read_data("objects", name, "alphanumeric") ){
			if( this._read_data("objects", name, "string") ){
				if( !isNaN(o.value) ){
					this.Err.error = "numeric";
					this.Err.description = this._read_data("objects", name, "message_string");
					this.Err.objectname = name;
					
					this._show_message(name);
					return;
				}else{
					if( this.Err.error!=0 ) this.Err._reset();
				}
			}else{
				if( isNaN(o.value) ){
					this.Err.error = "string";
					this.Err.description = this._read_data("objects", name, "message_string");
					this.Err.objectname = name;

					this._show_message(name);
					return;
				}else{
					if( this.Err.error!=0 ) this.Err._reset();
				}
			}
		}}
		
		if( o.value.length>0 ){
			// MIN
			if( this.Err.error==0 || this.Err.error=="min" ){
				min = this._read_data("objects", name, "min");
				if( min > 0 ){
					if( o.value.length < min ){				
						this.Err.error = "min";
						this.Err.description = this._read_data("objects", name, "message_min");
						this.Err.objectname = name;

						this._show_message(name);
						return;
					}else{
						if( this.Err.error!=0 ) this.Err._reset();
					}
				}
			}
		
			// MAX
			if( this.Err.error==0 || this.Err.error=="max" ){
				max = this._read_data("objects", name, "max");
				if( max > 0 ){
					if( o.value.length > max ){
						this.Err.error = "max";
						this.Err.description = this._read_data("objects", name, "message_max");
						this.Err.objectname = name;

						this._show_message(name);
						return;
					}else{
						if( this.Err.error!=0 ) this.Err._reset();
					}
				}
			}
		}
		
		// ISMAIL
		if( this.Err.error==0 || this.Err.error=="ismail" ){
			if( this._read_data("objects", name, "ismail") ){
				if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(o.value) == false ){
					this.Err.error = "ismail";
					this.Err.description = this._read_data("objects", name, "message_ismail");
					this.Err.objectname = name;

					this._show_message(name);
					return;
				}else{
					if( this.Err.error!=0 ) this.Err._reset();
				}
			}
		}
	
		// SECURIMAGE
		if( this.Err.error==0 || this.Err.error=="securimage" ){
			if( this._read_data("objects", name, "securimage") && this.init.path.script_securimage!="" ){
				this._XMLHttp = this._create_instance_ajax();
				if( this._XMLHttp ){
					this.Err.objectname = name;
					this._XMLHttp.onreadystatechange = this._changing_state_ajax;
					this._XMLHttp.open("POST", this.init.path.script_securimage+"/securimage_valida.php", true);
					this._XMLHttp.send("code="+o.value);
					return;
				}
			}
		}

		// CONFIRM_PASSWORD
		if( this.Err.error==0 || this.Err.error=="confirm_password" ){
		objValid = this._$(this._read_data("objects", name, "confirm_password"));
			
		if( objValid ){

			if( objValid.value!="" && (String(o.value) != String(objValid.value)) ){
				this.Err.error = "confirm_password";
				this.Err.description = this._read_data("objects", name, "message_confirmpassword");
				this.Err.objectname = name;

				this._show_message(name);
				return;				
			}else{
				if( this.Err.error!=0 ) this.Err._reset();
			}
		
		}}
				
		if( !this.configure.show_alert && this._object_msgbox && this.Err.error==0 ){
			this._opacity.hidden();
			return false;
		}else{
			this.working=false;
			return true;	
		}	
	},
	
	_read_data: function(object, prop, prop2){
		js="this."+object+"."+prop;
		if( prop2 ) js+="."+prop2
		return eval(js);
	},

	_trim: function(str){
		return 	str.replace(/^\s+|\s+$/g,"");
	},
	
	_show_message: function(nameobj){		
		this.working=true;
		var	o = this._$(nameobj);
		if( this.configure.show_alert ){
			alert( this.Err.description );
		}
		else
		{			
			div = o.parentNode;			
			
			if( div.nodeName=="DIV" || div.nodeName=="LABEL" ){
				div.style.position="relative";
				
				this._remove_message();

				msgbox = document.createElement("DIV");
				msgbox.id = this.init.classname.msgbox;
				this._object_msgbox = msgbox;
				
				var Style = this._read_data("objects", nameobj, "style_msgbox");
				if( Style ){					
					for( prop in Style ){
						eval("value = Style."+prop+";");
						eval("msgbox.style."+prop+"='"+value+"';");
					}
				}
				
												
				this._set_opacity(msgbox, 0);

				var table = document.createElement("TABLE"); 
					table.width = "100%";
					table.cellSpacing = "0";
					table.cellPadding = "0";
				
				var classCss = new Array();
				var css = new Array();
				
				classCss[0] = [this.init.classname.border_top_left, this.init.classname.border_top, this.init.classname.border_top_right];
				classCss[1] = [this.init.classname.border_left, this.init.classname.inner, this.init.classname.border_right];
				classCss[2] = [this.init.classname.border_bottom_left, this.init.classname.mark, this.init.classname.border_bottom_right];
			
				for( var y=0; y<=classCss.length-1; y++ ){
					css = classCss[y];
					var tr = document.createElement("TR");
					
					for( var x=0; x<=css.length-1; x++ ){
						var td = document.createElement("TD");
							td.className = css[x];
							
							if( y==1 && x==1 ){
								var newTable = document.createElement("TABLE");
									newTable.width="100%";
									newTable.cellSpacing="4";
									newTable.cellPadding="0";									
								var newTR = document.createElement("TR");
								var newTD1 = document.createElement("TD");
									newTD1.className=this.init.classname.icon;
																		
								var newTD2 = document.createElement("TD");
									newTD2.align="left";
									newTD2.innerHTML = "<span>"+this.Err.description+"</span>";
									
								newTR.appendChild(newTD1);
								newTR.appendChild(newTD2);
								newTable.appendChild(newTR);
								td.appendChild(newTable);
							}
							
						tr.appendChild(td);
					}
					table.appendChild(tr);
				}
				
				msgbox.appendChild(table);	
				msgbox.innerHTML = "<p>" + msgbox.innerHTML + "</p>";
				div.appendChild(msgbox);
								
				//Execute Degrades
				this._opacity.show();				
			}
			
		}
		if( o.focus ) o.focus();
		return;
	},
	
	_remove_message: function(){
		o = this._$(this.init.classname.msgbox);
		if( o ){
			node = o.parentNode;
			node.removeChild(o);
			this._object_msgbox=false;
		}
	},

	_add_event: function(o, evType, fn){
		if( o.addEventListener ){
			//o.addEventListener(evType, fn, false);
			funcPrevious = o.getAttribute("on"+evType);
			if( funcPrevious!=null ){
				if( funcPrevious.substr(funcPrevious.length-1)!=";" ) funcPrevious+=";"	
					o.setAttribute("on"+evType, funcPrevious+fn);				
			}else{
				o.setAttribute("on"+evType, fn);				
			}
		
		} else if( o.attachEvent ){
			o.attachEvent("on"+evType, Function(fn));
		}		
	},
	
	_opacity:{
		opacity: 0,
		tempID: false,
	
		show: function(){
			this.opacity=0;
			this.tempID = setInterval("Validator._opacity.to_grow_dark()", 40);
		},
		hidden: function(){
			this.tempID = setInterval("Validator._opacity.to_aclarecer()", 40);
		},
		
		to_grow_dark: function(){
			if( this.opacity < 10 ){
				this.opacity++;
				Validator._set_opacity(Validator._object_msgbox, this.opacity);
			}else{
				clearInterval(this.tempID);
				Validator.working=false;
			}
		},		
		to_aclarecer: function(){
			if( this.opacity > 0 ){
				this.opacity--;
				Validator._set_opacity(Validator._object_msgbox, this.opacity);
			}else{
				clearInterval(this.tempID);
				Validator._remove_message();
				Validator.working=false;
				if( !Validator.configure.dinamic ) Validator.validate();
			}
		}		
		
	},	
	
	_set_opacity: function(o, val) {
		if( document.all ) {  //For IE
			val = parseInt(val)*10;
			try {
				o.filters.item("DXImageTransform.Microsoft.Alpha").opacity = val;
				if( val==100 ) o.filters.item("DXImageTransform.Microsoft.Alpha").opacity="";
			} catch (e) { 
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				o.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+val+')';
				
				if( val==100 ) o.style.filter = '';
			}
		} else {
			val = parseInt(val)*0.1;
			o.style.opacity = val;
			o.style.MozOpacity = val;  //This is for older Mozilla Browsers
		}
	},

	_create_instance_ajax: function(){
		this._XMLHttp=false;
		
		if( window.XMLHttpRequest ){
			return new XMLHttpRequest();
		}
		else if( window.ActiveXObject ){
			var versiones = ["Msxml2.XMLHTTP.7.0","Msxml2.XMLHTTP.6.0","Msxml2.XMLHTTP.5.0","Msxml2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
			
			for(var i=0;i<versiones.length;i++){
				try {
					XMLHttp = new ActiveXObject(versiones[i]);
					if( XMLHttp ){
						return XMLHttp;
						break;
					}
				} catch(e){}
			}
		}
	},
	
	_changing_state_ajax: function(){
		if( Validator._XMLHttp.readyState==1 ){
			try{
				Validator._XMLHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			}
			catch(e){}
		}
				
		if( Validator._XMLHttp.readyState==4 ){	
		  if( Validator._XMLHttp.status==200 ){
				if( Validator._XMLHttp.responseText=="ok" ){									
					if( Validator.Err.error!=0 ) Validator.Err._reset();
					
					if( !Validator.configure.show_alert ){
						Validator._remove_message();
					}

				}else{
					Validator.Err.error = "securimage";
					Validator.Err.description= Validator._read_data("objects", Validator.Err.objectname, "message_securimage");
					
					Validator._show_message(Validator.Err.objectname);
				}			
			}
			else{
				alert("Error al recibir respuesta "+Validator._XMLHttp.statusText);
			}
		}			
	}

}