/* FUNCIONES INICIALES ***************/
window.addEvent('domready', function() {
	//caja-ayuda
	var ayu=$('caja-ayuda');
	if(ayu){
		$('caja-ayuda').fade(0,0);
		$('btn_ayuda').addEvent('click', function(){ $('caja-ayuda').fade(1); });
		$('btn_cerrar_ayuda').addEvent('click', function(){ $('caja-ayuda').fade(0); });
	}

	//caja-comparte
	var com=$('caja-comparte');
	if(com){
		$('caja-comparte').fade(0,0);
		$('btn_comparte').addEvent('click', function(){ $('caja-comparte').fade(1); });
		$('btn_cerrar_comparte').addEvent('click', function(){ $('caja-comparte').fade(0); });
		cambiarTab('pestana2','tab2');
	}
});	

window.addEvent('load', function() {
	document.getElementById("submit").disabled = false;
});

/*************************************/

/* TABS CAJA COMPARTE ****************/
function cambiarTab(pestana,tab){
	var tabs=['tab1','tab2'];
	var pestanas=['pestana1','pestana2'];
	for(i=0;i<tabs.length;i++){
		document.getElementById(tabs[i]).style.display="none";
		document.getElementById(pestanas[i]).className="";
	}
	document.getElementById(tab).style.display="block";
	document.getElementById(pestana).className="activa";
}
/*************************************/

/* BUSCADOR CABECERA *****************/
function busqueda_form() {
	document.getElementById('q').value=document.getElementById('q_temp').value;
	document.getElementById('q_temp').value='';
	$('google_search').submit();
}

function buscarEnter(evt){
	 var key = evt.keyCode ? evt.keyCode : evt.which ;	
	 if (key == 13) {
		 busqueda_form();
	 }
}

function limpiarBusqueda(origen){
	casilla=origen.parentNode;
	if(origen.value=="") {casilla.className="ocupado";}
}
function restaurarBusqueda(origen){
	casilla=origen.parentNode;
	if(origen.value=="") {casilla.className="vacio";}
}
/*************************************/

/* FORMULARIO LOGIN ******************/
function limpiarCasilla(casilla,texto){
	if(casilla.value==texto) {casilla.value="";}
}
function restaurarCasilla(casilla,texto){
	if(casilla.value=="") {
		casilla.type="text";
		casilla.value=texto;
	}
}
function cambiarTipo(casilla){
	casilla.type="password";
}
/*************************************/

/* VALIDACION ************************/
function solicitarClave() {
	document.getElementById('FRMLOGIN').action = "http://mipcs.entelpcs.com/mipcs2/comunes/solicitarClave/enviarClaveMovil.do";
	document.getElementById('FRMLOGIN').submit();
}

function validaFormulario(){
	var ok=1;
	var errores = new Array();

	//validacion
	formatearRut('EMPATRUT');
	formatearRut('USURUT');
	limpiarCasillas(["EMPATRUT","USURUT","USUPAS"],'input_cuenta');
	
	if(document.getElementById("EMPATRUT").value!="RUT Empresa" && !validarRutCompleto("EMPATRUT","10")){ ok=0; errores.push(["EMPATRUT","Debes ingresar un RUT Empresa válido."]); }
	if(document.getElementById("USURUT").value!="RUT Administrador" && !validarRutCompleto("USURUT","10")){ ok=0; errores.push(["USURUT","Debes ingresar un RUT Administrador válido."]); }
	if(document.getElementById("USUPAS").value.length < 4){ ok=0; errores.push(["USUPAS","Clave incorrecta."]); }
	
	//respuesta
	if(ok==0){
		mostrarErrores(errores);
		return false;
	}
	else{
		$('alerta_error').fade(0); //requiere mootools
		return true;
	}
}

function enviarFormulario(){
	var errores = new Array();
	if(!document.getElementById("EMPATRUT").value || document.getElementById("EMPATRUT").value=="RUT Empresa"){ errores.push(["EMPATRUT","Debes ingresar un RUT Empresa válido."]); }
	if(!document.getElementById("USURUT").value || document.getElementById("USURUT").value=="RUT Administrador"){ errores.push(["USURUT","Debes ingresar un RUT Administrador válido."]); }
	if(!document.getElementById("USUPAS").value || document.getElementById("USUPAS").value=="Clave"){ errores.push(["USUPAS","Debes ingresar la clave de tu PCS."]); }

	if(errores.length){ mostrarErrores(errores); }
	else{
		if(validaFormulario()){
			if(!document.getElementById("submit").disabled) {

				document.getElementById("submit").src="/archivos_home/img/home/btn_login.gif";
				document.getElementById("submit").disabled = true;

				setTimeout(function() {
					document.getElementById("FRMLOGIN").action="http://www.vas.entelpcs.cl/acceso_emp/entrada_emp.php";
					document.getElementById("FRMLOGIN").submit();
				}, 500);
			}
		}
	}
}

function limpiarCasillas(casillas,estilo){
	for(i=0;i<casillas.length;i++){
		document.getElementById(casillas[i]).className=estilo;
	}
}

function enviarComparte(){
	var errores = new Array();
	limpiarCasillas(["para","nombre","email"],'');
	
	if(!validarMail("para")){ ok=0; errores.push(["para","Debes ingresar el e-mail del destinatario."]); }
	if(!validacionAlfabetica("nombre","3")){ ok=0; errores.push(["nombre","Debes ingresar tu nombre."]); }
	if(!validarMail("email")){ ok=0; errores.push(["email","Debes ingresar tu e-mail."]); }

	if(errores.length){
		alertarErrores(errores);
	}
	else{
		var nombre = document.getElementById('nombre').value
		nombre=nombre.replace(/\s/g,"%20");
		nombre=nombre.replace(/á/g,"%E1");
		nombre=nombre.replace(/é/g,"%E9");
		nombre=nombre.replace(/í/g,"%ED");
		nombre=nombre.replace(/ó/g,"%F3");
		nombre=nombre.replace(/ú/g,"%FA");
		var str = "para="+document.getElementById('para').value+"&";
		str += "nombre="+nombre+"&";
		str += "email="+document.getElementById('email').value;
		
		$('frm-comparte').fade(1,0);
		$('ajax-enviando').fade(0,1);
		makePOSTRequest('/envio_mail/envio_social.iws', str, 'ajax-enviando', 'ajax-sent', 'frm-comparte');
	}
}
/*************************************/

/* FIX PARA EXPLORER 6 *******************/
function PNG_loader() {
   for(var i=0; i<document.images.length; i++) {
      var img = document.images[i];
      var imgName = img.src.toUpperCase();
      if (imgName.substring(imgName.length-3, imgName.length) == "PNG") {
         var imgID = (img.id) ? "id='" + img.id + "' " : "";
         var imgClass = (img.className) ? "class='" + img.className + "' " : "";
         var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' ";
         var imgStyle = "display:inline-block;" + img.style.cssText;
         if (img.align == "left") imgStyle += "float:left;";
         if (img.align == "right") imgStyle += "float:right;";
         if (img.parentElement.href) imgStyle += "cursor:hand;";
         var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
         img.outerHTML = strNewHTML;
         i--;
      }
   }
}
if(window.attachEvent) window.attachEvent("onload",PNG_loader);
/*****************************************/

/* AJAX **********************************/
var http_request = false;
function makePOSTRequest(url, parameters, ocultarAlEnviar, mostrarAlEnviar, casillaInicial) {
  http_request = false;
  casillaOcultar=ocultarAlEnviar;
  casillaMostrar=mostrarAlEnviar;
  if (window.XMLHttpRequest) {
	 http_request = new XMLHttpRequest();
	 if (http_request.overrideMimeType) {
		http_request.overrideMimeType('text/html');
	 }
  } else if (window.ActiveXObject) { // IE
	 try {
		http_request = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
		try {
		   http_request = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {}
	 }
  }
  if (!http_request) {
	 alert('Cannot create XMLHTTP instance');
	 return false;
  }
  
  http_request.onreadystatechange = function(){
	  if (http_request.readyState == 4) {
		 if (http_request.status == 200) {
			//result = http_request.responseText;
			$(ocultarAlEnviar).fade(1,0); //requiere mootools
			$(mostrarAlEnviar).fade(0,1); //requiere mootools
			if(casillaInicial) { setTimeout(function(){ $(mostrarAlEnviar).fade(1,0); $(casillaInicial).fade(0,1); },2000); } //requiere mootools
		 } else {
			alert('Ha ocurrido un error. Por favor, inténtalo más tarde.');
		 }
	  }
  }
  http_request.open('POST', url, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
}
/*****************************************/