// ***************************************************
//	Este componente muestra una venta para logearse
//****************************************************

var AjaxLogin = {
	
	// PROPERTIES PUBLIC
	init:{
		root: '',  //Required
		path_include_form: '', //Required
		name_container: 'ajaxlogin_container',
		width: '480px',
		height: '350px',
		input_user: '', //Required
		input_pass: '',  //Required
		Class:{
			button_close: 'AjaxLogin_ButtonClose'
		}
	},
	active: false,
	Elements: {},
	on_finalizer: function(){},
	data: Array(),
	set_focus: {},
	
	// METHODS PUBLIC
	show: function(){			
		if( this.active ) return;
		this.active = true;
		sizeWindow = this._getSizeWindow();

		// Muestra Tapa
		var div = document.createElement("DIV");
			div.style.position = "absolute";
			div.style.left = "0px";
			div.style.top = "0px";
			div.style.width = sizeWindow.x+"px";
			div.style.height = sizeWindow.y+"px";
			div.style.zIndex = 200;
			div.style.backgroundColor = "black";
			this._set_opacity(div, 5);
	
		this._objects.divTapa = div;
		document.body.style.overflow="hidden";
		document.body.appendChild(div);
				
		// Ventanita
		var div = document.createElement("DIV");
			div.style.position = "absolute";
			div.style.width = this.init.width;
			div.style.height = this.init.height;
			div.style.left = ((sizeWindow.x/2) - parseInt(div.style.width)/2)+"px";
			div.style.top = ((sizeWindow.y/2) - parseInt(div.style.height)/2)+"px";
			div.style.zIndex = 201;
			div.style.backgroundColor = "#1F1F21";	
			this._set_opacity(div, 0);

		this._objects.divWindow = div;				
		document.body.appendChild(div);
		
				
		this._progress.show();
		this.Ajax.on_finalizer = function(){
			var div = AjaxLogin._objects.divWindow;
			div.innerHTML = this.resultText;
			
			// Button Close
			var divButton = document.createElement("DIV");
				divButton.className = AjaxLogin.init.Class.button_close;															
				divButton.onclick = AjaxLogin.close;
			div.appendChild( divButton );
				divButton.style.left = ( parseInt(div.style.width) - parseInt(AjaxLogin._get_property_css(divButton, "width"))-10 )+"px";
			
			
			AjaxLogin._objects.containers = AjaxLogin._get_div_container();
							
			
			var containers = div.getElementsByTagName("div");
			var container=false;
			
			for( var i=0; i<=containers.length-1; i++ ){
				if( containers[i].id=="AjaxLogin_Container" ){
					if( containers[i].style.display=="" ){
						container = containers[i];
						break;
					}
				}					
			}
							
			var inputs = container.getElementsByTagName("input");
			for( var i=0; i<=inputs.length-1; i++ ){
				if( inputs[i].id!="" ){						
				
					if( inputs[i].getAttribute("keypress_enter")!=null ){
						var attr = inputs[i].getAttribute("keypress_enter");
						
						inputs[i].onkeyup = function(e){
							var code = e.keyCode || e.which;
							if( code==13 ) {
								eval(attr);
							}
						}
					}
					
					if( inputs[i].getAttribute("setfocus")!=null ){
						inputs[i].focus();
					}

				}
			}
			
		}
		this.Ajax.execute("GET", this.init.path_include_form, "", AjaxLogin);
			

		this._opacity.opacity_max = 10;
		this._opacity.duration = 50;
		this._opacity.opacity = 0;
		this._opacity.show( this._objects.divWindow );
	},
	
	close: function(){
		AjaxLogin._opacity.duration = 50;
		AjaxLogin._opacity.on_finalizer = function(){
			AjaxLogin._close_all();
		}
		AjaxLogin._opacity.hidden( AjaxLogin._objects.divWindow );
		
	},
	
	action_button: function(option){
		switch(option){
		case 1: //Entrar	(Administrador)
			var Err = this._validate('form1');
			if( Err.error ){
				this._show_error();
				return;
			}else{
				var oUser = document.getElementById(this.Elements.username);
				var oPass = document.getElementById(this.Elements.password);
				
				this._progress.show();
				this.Ajax.on_finalizer = function(){
					var resultText = this.resultText;
					var resultXML = this.resultXML;
					
					if( !isNaN(resultText) ){
						if( confirm("Tu usuario esta siendo usado o ha quedado abierto. ¿Desea expulsarlo?") ){
							AjaxLogin._progress.show();
							AjaxLogin.Ajax.on_finalizer = function(){
								AjaxLogin._save_result(this.resultXML);
								return;
							}
							AjaxLogin.Ajax.execute("POST", 
												   AjaxLogin.init.path_ajax_sql+"?action=logout", 
												   "path_connection="+AjaxLogin.init.path_connection+"&coduser="+resultText+"&username="+oUser.value+"&pass="+oPass.value,
												   AjaxLogin);
						}
						return;
					}
					
					
					if( resultText=="false" ){
						var tag = document.getElementById(AjaxLogin.validate.tag_error.form1);
						AjaxLogin._Err = {error:true, description: "El usuario y/o password son incorrectos.", 
										  object: oUser, 
										  tag_error: tag};
						AjaxLogin._show_error();										 
						return;
					}else{
						AjaxLogin._save_result(resultXML);
					}
				}

				this.Ajax.execute("POST", this.init.path_ajax_sql+"?action=validate", "path_connection="+this.init.path_connection+"&username="+oUser.value+"&pass="+oPass.value, AjaxLogin);
				
			}
		break;
		
		case 2: //Entrar  (Usuario)
			var Err = this._validate('form1');
			if( Err.error ){
				this._show_error();
				return;
			}else{
				var oName  = document.getElementById(this.Elements.name);
				var oEmail = document.getElementById(this.Elements.email);
				
				this._progress.show();
				this.Ajax.on_finalizer = function(){
					AjaxLogin._save_result(this.resultXML);
				}
				this.Ajax.execute("POST", this.init.path_ajax_sql+"?action=validate2", "path_connection="+this.init.path_connection+"&name="+oName.value+"&email="+oEmail.value, AjaxLogin);
				
			}		
		break;
		}
	},
	
	validate:{
		object: {},
		set_objects: function(){
			for( var i=0; i<=arguments.length-1; i++ ){
				eval("this.object."+arguments[i]+"={};");
			}
		},
		set_tag_error: function(){
			var param = new Array();
			var form,id_tag;
			for( var i=0; i<=arguments.length-1; i++ ){
				param = arguments[i];
				if( param.length==2 ){
					form = param[0];
					id_tag  = param[1];
					eval("this.tag_error."+form+"='"+id_tag+"';");
				}
			}			
		},
		tag_error: {}
	},


	// PROPERTIES PRIVATE
	_objects: {},
	_Err: {error: false},

	// METHODS PRIVATE
	_opacity: {
		object: false,
		object2: false,
		tempID: false,
		opacity: 0,
		opacity_max: 6,
		opacity_min: 0,
		duration: 25,
		
		show: function(object){
			this.object = object;
			this.tempID = setInterval("AjaxLogin._opacity.to_grow_dark()", this.duration);
			
		},
		hidden: function(object){
			this.object = object;
			this.tempID = setInterval("AjaxLogin._opacity.to_aclarecer()", this.duration);			
		},
		
		to_grow_dark: function(){
			if( this.opacity < this.opacity_max ){
				this.opacity+=1;
				AjaxLogin._set_opacity(this.object, this.opacity);
			}else{
				clearInterval(this.tempID);
				this.on_finalizer();
			}
			
		},
		to_aclarecer: function(){
			if( this.opacity > this.opacity_min ){
				this.opacity-=1;
				AjaxLogin._set_opacity(this.object, this.opacity);				
			}else{
				clearInterval(this.tempID);
				this.on_finalizer();
			}
		},
		
		on_finalizer: function(){}
		
	},
	
	
	_getSizeWindow: function(){
		var x, y;
		if (self.innerHeight) { // MOS
			y = self.innerHeight + window.pageYOffset;
			x = self.innerWidth + window.pageXOffset;
		} else if (document.documentElement && document.documentElement.clientWidth) { // IE6 Strict
			x = document.documentElement.clientWidth + document.documentElement.scrollLeft;
			y = document.documentElement.clientHeight + document.documentElement.scrollTop;
		} else if (document.body.clientHeight) { // IE quirks
			y = document.body.clientHeight + document.body.scrollTop;
			x = document.body.clientWidth + document.body.scrollLeft;
		}
		return {x: x, y: y};
	},
	
	_set_opacity: function(o, val) {
		if( document.all ) {  //For IE
			val = parseInt(val)*10;
			try {
				o.filters.item("DXImageTransform.Microsoft.Alpha").opacity = val;
			} 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+')';
			}
		} else {
			val = parseInt(val)*0.1;
			o.style.opacity = val;
			o.style.MozOpacity = val;  //This is for older Mozilla Browsers
		}
	},

	Ajax:{
		XMLHttp: false,
		on_finalizer: function(){},
		resultText: '',
		resultXML: '',
		
		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(This){
			if( This.Ajax.XMLHttp.readyState==1 ){
				try{
					This.Ajax.XMLHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				}
				catch(e){}
			}
			
			if( This.Ajax.XMLHttp.readyState==4 ){
				if( This.Ajax.XMLHttp.status==200 ){
					This.Ajax.resultText = This.Ajax.XMLHttp.responseText;
					This.Ajax.resultXML = This.Ajax.XMLHttp.responseXML;
					AjaxLogin._progress.hidden();
					This.Ajax.on_finalizer();
					
				}else{
					alert("Error al recibir respuesta "+This.Ajax.XMLHttp.statusText);
				}
			}
		},
		
		execute: function(method, link, send, This){
			this.XMLHttp = this.create_instance_ajax();
			if( this.XMLHttp ){
				if( typeof(send)=="undefined" ) send=null;
				this.XMLHttp.onreadystatechange = function(){This.Ajax.changing_state_ajax(This)};
				this.XMLHttp.open(method, link, true);
				this.XMLHttp.send(send);
				return;
			}		
		}
	},	
	
	
	_remove_object: function(o){
		p = o.parentNode;
		p.removeChild(o);
	},

	_progress:{
		show: function(){
			AjaxLogin._set_opacity(AjaxLogin._objects.divWindow, 5);

			var div = document.createElement("DIV");
				div.style.position = "absolute";
				div.style.background = "url("+AjaxLogin.init.root+"/progress.gif) no-repeat top";
				div.style.width = "32px";
				div.style.height = "32px";
				div.style.left = (parseInt(AjaxLogin._objects.divWindow.style.width)/2 - parseInt(div.style.width)/2)+"px";
				div.style.top = (parseInt(AjaxLogin._objects.divWindow.style.height)/2 - parseInt(div.style.height)/2)+"px";
				div.style.zIndex=11;
				AjaxLogin._objects.divWindow.appendChild(div);
				AjaxLogin._objects.progress = div;
				
		},
		hidden: function(){
			if( AjaxLogin._objects.progress ){
				AjaxLogin._remove_object( AjaxLogin._objects.progress );
				AjaxLogin._set_opacity(AjaxLogin._objects.divWindow, 10);
			}
		}		
	},
	
	_get_div_container: function(){
		var divWindow = this._objects.divWindow;
		var elements = divWindow.getElementsByTagName("DIV");
		var objects = new Array();			
		
		for( var i=0; i<=elements.length-1; i++ ){
			if( elements[i].id.toLowerCase() == this.init.name_container )
				objects[i] = elements[i];	
		}		
		
		return objects;
	},
	
	_reset_inputbox: function(object){
		var elements = object.getElementsByTagName("INPUT");
		for( var i=0; i<=elements.length-1; i++ ){
			if( elements[i].getAttribute("type")=="text" || elements[i].getAttribute("type")=="password" ){
				elements[i].value="";
			}
		}
	},
	
	_visible_container: function(nameform){
		var objects = this._objects.containers;
		if( objects.length>0 ){
			eval("var tag_error = document.getElementById(this.validate.tag_error."+nameform+");");
			for( var i=0; i<=objects.length-1; i++ ){
				if( objects[i].getAttribute("nameform").toLowerCase() == nameform.toLowerCase() ){
					objects[i].style.display="";
										
					this._reset_inputbox( objects[i] );
					tag_error.style.display="none";					
					
					var inputs = objects[i].getElementsByTagName("input");					
					for( var i2=0; i2<=inputs.length-1; i2++ ){
						if( inputs[i2].id!="" ){
							if( inputs[i2].getAttribute("setfocus") ){
								inputs[i2].focus();
								break;
							}
						}
					}
					
				}else{
					objects[i].style.display="none";					
				}
			}
		}		
		
	},
	
	_get_form: function(nameform){
		var objects = this._objects.containers;
		if( objects.length>0 ){
			for( var i=0; i<=objects.length-1; i++ ){
				if( objects[i].getAttribute("nameform").toLowerCase() == nameform.toLowerCase() )
					return objects[i];
			}
		}
	},
	
	_validate: function(nameform){		
		var object = this._get_form(nameform);	
		if( !object ) return;
		
		eval("var tag = document.getElementById(this.validate.tag_error."+nameform+");");
		if( tag ){
			tag.innerHTML = "";
			tag.style.display = "none";			
		}				

		var elements = object.getElementsByTagName("INPUT");
		var value;
		
		for( var i=0; i<=elements.length-1; i++ ){
			if( elements[i].getAttribute("type")=="text" || elements[i].getAttribute("type")=="password" ){
				
				eval("value = this.validate.object."+elements[i].id+".required");
				if( typeof(value)!="undefined" ){
					if( this._trim(elements[i].value)=="" ) {
						this._Err = {error:true, description: value, object: elements[i], tag_error: tag};
						return this._Err;
					}
				}
			
				eval("value = this.validate.object."+elements[i].id+".string");
				if( typeof(value)!="undefined" ){
					if( value[0] ){
						if( !isNaN(elements[i].value) ) {
							this._Err = {error:true, description: value[1], object: elements[i], tag_error: tag};
							return this._Err;
						}
					}else{
						if( isNaN(elements[i].value) ) {
							this._Err = {error:true, description: value[1], object: elements[i], tag_error: tag};
							return this._Err;
						}
					}
				}

				eval("value = this.validate.object."+elements[i].id+".mail");
				if( typeof(value)!="undefined" ){
					if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(elements[i].value) == false ) {
						this._Err = {error:true, description: value, object: elements[i], tag_error: tag};
						return this._Err;
					}
				}

			}
		}
		
		this._Err={error: false};
		return {error:false};
	},
	
	_trim: function(str){		
		return str.replace(/^\s*|\s*$/g,"");
	},
	
	_remove_object: function(obj){
		if( obj ){
			nodePadre = obj.parentNode;
			nodePadre.removeChild(obj);
		}
	},
	
	_get_property_css: function(object, prop){
		if( document.defaultView && document.defaultView.getComputedStyle ) {
			return document.defaultView.getComputedStyle(object,'').getPropertyValue(prop);
		}else{
			if( object.currentStyle ){
				eval("var result = object.currentStyle."+prop);
				return result;
			}else return "";
		}		
	},
		
	
	_show_error: function(){		
		if( this._Err.tag_error ){
			this._move_window.on_finalizer = function(){
				AjaxLogin._Err.tag_error.innerHTML = AjaxLogin._Err.description;
				AjaxLogin._Err.tag_error.style.display = "";
				AjaxLogin._Err.object.focus();
			}
			this._move_window.start();
		}
	},
	
	_move_window: {
		object: false,
		tempID: false,
		on_finalizer: function(){},
		left_center:0,
		topLeft:0,
		topRight:0,
		lap:0,
		inc:10,
		
		start: function(){
			this.lap++;
						
			var num = new Array();
			num[1] = (!document.all) ? 30 : 25;
			num[2] = (!document.all) ? 20 : 15;
			num[3] = (!document.all) ? 10 : 5;
			
			switch( this.lap ){
			case 1:							
				this.object = AjaxLogin._objects.divWindow;
				this.left_center = parseInt(this.object.style.left);
				this.topLeft = parseInt(this.object.style.left)-num[1];
				this.topRight = parseInt(this.object.style.left)+num[1];
			break;

			case 2:							
				this.topLeft = parseInt(this.object.style.left)-num[2];
				this.topRight = parseInt(this.object.style.left)+num[2];
			break;

			case 3:							
				this.topLeft = parseInt(this.object.style.left)-num[3];
				this.topRight = parseInt(this.object.style.left)+num[3];
			break;
			}
			
			
			if( this.lap<4 ) {
				this.tempID = setInterval("AjaxLogin._move_window.move('left')", 5);
			}else{
				this.on_finalizer();
				this.lap=0;
			}
		},
				
		move: function(address){
			var posX = parseInt(this.object.style.left);
			
			switch( address ){
			case "left":
				if( posX > this.topLeft ){
					this.object.style.left = (posX-this.inc)+"px";
				}else{
					clearInterval(this.tempID);
					this.tempID = setInterval("AjaxLogin._move_window.move('right')", 25);
				}
			break;
			case "right":
				if( posX < this.topRight ){
					this.object.style.left = (posX+this.inc)+"px";
				}else{		
					clearInterval(this.tempID);
					this.tempID = setInterval("AjaxLogin._move_window.move('center')", 25);
				}
			break;
			case "center":
				if( posX > this.left_center ){
					this.object.style.left = (posX-this.inc)+"px";
				}else{
					clearInterval(this.tempID);
					this.object.style.left = (this.left_center)+"px";
					this.start();
				}
			break;
			}			
		}
	},
	
	_close_all: function(){
		AjaxLogin._remove_object( AjaxLogin._objects.divWindow );
		AjaxLogin._remove_object( AjaxLogin._objects.divTapa );
		AjaxLogin.active = false;
		AjaxLogin._opacity.on_finalizer = function(){};
		document.body.style.overflow = "auto";
	},
	
	_save_result: function(resultXML){
		if( resultXML==null ) return;
		
		if( resultXML.documentElement.nodeName ){
			var rows = resultXML.getElementsByTagName("row");
			var strProp="";
			var valueprop="";
			
			for( var i=0; i<=rows.length-1; i++ ){
				for( var x=0; x<=rows[i].childNodes.length-1; x++ ){
					valueprop = (isNaN(rows[i].childNodes[x].childNodes[0].nodeValue)) ? "'"+rows[i].childNodes[x].childNodes[0].nodeValue+"'" : rows[i].childNodes[x].childNodes[0].nodeValue;
					strProp += rows[i].childNodes[x].nodeName+": "+valueprop+",";
				}
				strProp = strProp.substr(0, strProp.length-1);
				eval("AjaxLogin.data[i] = {"+strProp+"};");
			}
			
			AjaxLogin._close_all();
			
			//Execute Event Finalizer
			AjaxLogin.on_finalizer();
		}
	}

	
}
