//<![CDATA[
window.addEvent('domready', function(){
	new Gusanito.layout800x600();
	new Gusanito.idioma('lang');
	new Gusanito.Buscador({
		input: 'q',
		disparador: 'ok',
		buscar_en: 'b_en',
		forma: 'buscador_gusanito'
	});
	new Gusanito.menuBuscarEn('buscar_en', 'b_en', 'oculto');
    new Gusanito.autocompletar('q', {
		div_id: 'ac_autocompletado', 
		clase_activa: 'activa', 
		modo: 'html', 
		arreglo_base: $('top_tags').value.split(','), 
		delay: 600
	});
	new Gusanito.animarForma('frm_enviar_postal', 'resaltado_2');
	//new Gusanito.desactivarBoton('enviar');
	new Gusanito.calificar({
		id: 'cnt_calificador',
		calificacion: 'img_calificacion',
		contador_votos: 'contador_votos',
		exito: 'objeto_calificado',
		descr_calif: 'descripcion_calificacion'
	});
	new Gusanito.recomendar({
		id: 'cnt_recomendador',
		disparador: 'btn_enviar_recomienda',
		exito: 'recomendacion_enviada',
		clase_oculto: 'oculto'
	});
	new Gusanito.favoritos('btn_favoritear',{
		id: 'cnt_favoriteador',
		exito: 'objeto_favoriteado',
		clase_oculto: 'oculto'
	});
	new Gusanito.tabsHerramientas('barra_herramientas_tabs', 'active',{
		tab_default: 0, 
		clase_tabs: 'tab', 
		clase_contenido: 'tab_contenedor'
	});
	new Gusanito.EnviarPostal.filas('cnt_para', 'numero_destinatarios', {
		identificador_filas: '.fila',
		nuevos_ids: ['nom_destinatario_', 'email_destinatario_'],
		onComplete: function(){
			new Gusanito.animarForma('frm_enviar_postal', 'resaltado_2');
		}
	});
	//new Gusanito.EnviarPostal.vistaPreviaMensaje('preview', 'fckeditor', 'postal_mensaje', 'oculto', 'vista_previa', 'msg_predef');
	new Tips($$('.toolTipElement'), {
		timeOut: 700,
		maxTitleChars: 50,
		maxOpacity: 0.8
	});

	
	//new Gusanito.EnviarPostal.agregarMsjPredeterminado('postal_mensaje', 'msg_predef');
	new Gusanito.EnviarPostal.fechaEnvio('enviar_en', 2, ['flecha_gris', 'mes', 'dia', 'anio']);
	//var _FCKEditor = new FCKeditor( 'postal_mensaje' ) ;
	//_FCKEditor.BasePath	= 'http://'+document.domain+'/js/fckeditor/';
	//_FCKEditor.ToolbarSet = 'Gusano' ;
	//_FCKEditor.Width	= 420 ;
	//_FCKEditor.Height	= 120 ;
	//_FCKEditor.ReplaceTextarea();
});


/**
 *
 *	Funciones agregadas para funcionalidad de Importar Contactos
 *
 * */


function validate(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = email;
   if(reg.test(address) == false) {
      alert('Introduzca su correo en la forma mi@correo.com');
	  $('importa_correo').focus();
      return false;
   }

   return true;
}

function validate_password(password){
	if(password.length < 1){
		alert('Introduzca un password');
		$('importa_password').focus();
		return false;
	}

	return true;
}


function replaceHtml(el, html) {
	var oldEl = (typeof el === "string" ? document.getElementById(el) : el);
	/*@cc_on // Puro innerHTML para IE (que es más rápido)
	oldEl.innerHTML = html;
	return oldEl;
	@*/
	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);
	return newEl;
}


/** 
 * Resetea la forma de importar contactos
 * */

function cancelarContactos(){
	replaceHtml('carga_contactos', '');
	$('importa_correo').value = '';
	$('importa_password').value = '';
	var coords = $('importa_correo').getPosition();
	scrollTo(coords.x, coords.y - 30 );
	$('importa_correo').focus();

	try{
		$('toggle_correo').removeClass('error');
		$('toggle_password').removeClass('error');	
	}catch(e){
						
	}

}


function cancelarContactos2(){
	replaceHtml('carga_contactos', '');
	$('importa_correo').value = '';
	$('importa_password').value = '';
 
	try{
		$('toggle_correo').removeClass('error');
		$('toggle_password').removeClass('error');	
	}catch(e){
						
	}

}


 
//Enviar request por ajax para obtener los contactos a importar 
function getContactos(){

	var u = $('importa_correo').value;			//username
	var p = $('importa_password').value;		//password
	var s = $('provider_box').value;			//servicio

	var valido_mail		= u.length || validate(u) ;
	var valido_password = validate_password(p); 
	var _error = false;


	//var fx1 	= new Fx.Slide('toggle_warning', {duration: 500});
	//var fx2 	= new Fx.Slide('toggle_send', {duration: 500});
	//var fx3 	= new Fx.Slide('toggle_password', {duration: 500});
	//var fx4 	= new Fx.Slide('toggle_proveedor', {duration: 500});
	//var fx5 	= new Fx.Slide('toggle_correo', {duration: 500});
	//var fx6		= new Fx.Slide('carga_contactos', {duration: 500});

	//esconder tabla de resultados inicialmente
	//fx6.hide();

	if( Boolean(valido_mail) && Boolean(valido_password) ){


		new Ajax(Gusanito.webservice, {
            method: 'post',
            postBody: 'accion=carga_contactos&u='+u+'&p='+p+'&s='+s,
            update: $('carga_contactos'),
			onStart: replaceHtml('carga_contactos', 'Importando Contactos...<br /><img src="/img/loading2.gif" />'),
            onComplete:function(resp){
				$('carga_contactos').setHTML(resp);
				var coords = $('carga_contactos').getPosition();

				if($('warning_importar')){
					$('toggle_correo').addClass('error');
					$('toggle_password').addClass('error');

					if( $('error_usuario') ){
						try{
							$('toggle_password').removeClass('error');
						}catch(e){
						
						}

					}

					$('importa_correo').focus();
					_error = true;
				}else{
					//if(_error){
						try{
							$('toggle_correo').removeClass('error');
							$('toggle_password').removeClass('error');	
						}catch(e){
						
						}
						
					//}

					scrollTo(coords.x, coords.y - 30 );
					error = 0;
				}

 
				//	Encoger la forma y mostrar la tabla
			 	/*fx1.toggle();
				fx1.hide();
				fx2.toggle();
				fx2.hide();
				fx3.toggle();
				fx3.hide();
				fx4.toggle();
				fx4.hide();
				fx5.toggle();
				fx5.hide();
				
				fx6.toggle();*/
				
			}.bind(this)
        }).request();

	}
	
}

/**
 *
 * Implementación del foreach
 *
 * */
function ForEach(array, fn)
{
  for (var n = 0; n < array.length; n++)
  {
    var r = fn(array[n]);

    if (r != undefined)
      return r;
  }

  return undefined;
}


/*
 *	Vuelve a mostrar la forma para introducir el usuario,red y pass.
 *
 * */
function recargarProveedores(){

	var formas = ["toggle_warning","toggle_send","toggle_password","toggle_proveedor","toggle_correo","carga_contactos"];

	ForEach(formas, function(element){
		document.getElementById(element).style.display = 'block';
    });
	
	
}



/**
 *
 * Selecciona / deselecciona todos los contactos
 * en el importador
 *
 * */
function toggleSelecciona(){

  c = document.getElementsByTagName('input');

  for (var i = 0; i < c.length; i++){
		if (c[i].type == 'checkbox'  &&  ( c[i].id != 'opc_1' ) && ( c[i].id != 'opc_2' ) && ( c[i].id != 'toggle_selecciona' )  ){
				if( c[i].checked == true ){
					c[i].checked = false;
					document.getElementById('toggle_selecciona').checked = false;
				}else{
					c[i].checked = true;
					document.getElementById('toggle_selecciona').checked = true;
				}
		}
	}
}

 

/** 
 *
 * Regresa los elementos no seleccionados
 * para removerlos de la forma antes
 * de hacer el submit
 *
 * */
function check_all_in_document(doc){

  var c = new Array();
  var retArr = new Array();
  var lastElement = 0;


  c = doc.getElementsByTagName('input');

  for (var i = 0; i < c.length; i++)
  {
    if (c[i].type == 'checkbox'  )
    {
			if( c[i].checked == true &&  ( c[i].id != 'opc_1' ) && ( c[i].id != 'opc_2' ) && ( c[i].id != 'toggle_selecciona' )  ){
				retArr.length = lastElement;
				retArr[lastElement] = c[i].value;
				lastElement++;
			}
	}
  }

  return retArr;

}


/**
 *
 * Wrapper para onsubmit
 *
 * */
function generaForma(){

	var seleccionadas = check_all_in_document(document);

 
	if( document.getElementById('metodo_agregar_importar').checked == true && seleccionadas.length < 1 ){
		alert('Selecciona uno o varios contactos');
		var coords = $('importa_correo').getPosition();
		scrollTo(coords.x, coords.y - 30 );
		$('importa_correo').focus();

		//Borrar contactos manuales
		$('nom_destinatario_').value = '';
		$('email_destinatario_1').value = '';
		$('numero_destinatarios').value = 1;

		return false;
	}else{
		new Gusanito.desactivarBoton('enviar');
		cancelarContactos2();
		return true;
	}

	
	//console.log(no_seleccionadas);


	//alert(no_seleccionadas);

/**
 * Remover del DOM
 *
 *     [nombres_destinatarios] => Array
        (
            [0] => 
            [1] => angymalibu@hotmail.com
            [2] => ches che
            [3] => Franchesco Romero
        )

    [emails_destinatarios] => Array
        (
            [0] => 
            [1] => angymalibu@hotmail.com
            [2] => ches che
            [3] => Franchesco Romero
        )

 *
 * */

 
	ForEach(no_seleccionadas, function(v){
 		document.getElementById('nom_destinatario_'+v).style.display = 'none';
		document.getElementById('nom_destinatario_'+v).firstChild.remove();
		document.removeChild(document.getElementById('nom_destinatario_'+v));

		document.getElementById('span_'+v).style.display = 'none';
		document.getElementById('span_'+v).firstChild.remove();
		document.removeChild(document.getElementById('span_'+v));


		document.getElementById('email_destinatario_'+v).style.display = 'none';
		document.getElementById('email_destinatario_'+v).firstChild.remove();
		document.removeChild(document.getElementById('email_destinatario_'+v));


		document.getElementById('checkbox_'+v).style.display = 'none';
		document.getElementById('checkbox_'+v).firstChild.remove();
		document.removeChild(document.getElementById('checkbox_'+v));


		document.getElementById('tr_'+v).style.display = 'none';
		document.getElementById('tr_'+v).firstChild.remove();
		document.removeChild(document.getElementById('tr_'+v));
 	});
 
	//cambiar este  y el de la forma después de debuggear.
 
}




function correoUsuario(){
	var mylist=document.getElementById('provider_box'); 
	var val = mylist.options[mylist.selectedIndex].value; 
	
	if(val == 'gmail' || val == 'lycos' || val == 'terra' ){
		replaceHtml('correo_usuario','Usuario ');
		//document.getElementById('correo_usuario').innerHTML = 'Usuario ';
	}else{
		replaceHtml('correo_usuario','E-mail ');
		//document.getElementById('correo_usuario').innerHTML = 'E-mail ';
	}	

}


// ]]>
