Index: trunk/jabberit_messenger/java_source/src/nu/fw/jeti/backend/CapabilitiesCache.java
===================================================================
--- trunk/jabberit_messenger/java_source/src/nu/fw/jeti/backend/CapabilitiesCache.java	(revision 1014)
+++ trunk/jabberit_messenger/java_source/src/nu/fw/jeti/backend/CapabilitiesCache.java	(revision 1424)
@@ -63,7 +63,11 @@
 	public CapabilitiesCache(Backend backend)
 	{
-		this.backend = backend;
-		capabilities = new HashMap();
-		cache = new HashMap();
+		try
+		{
+			this.backend = backend;
+			capabilities = new HashMap();
+			cache = new HashMap();
+		}
+		catch(Exception e){}
 	}
 	
Index: trunk/jabberit_messenger/java_source/src/nu/fw/jeti/backend/LoginInfo.java
===================================================================
--- trunk/jabberit_messenger/java_source/src/nu/fw/jeti/backend/LoginInfo.java	(revision 1014)
+++ trunk/jabberit_messenger/java_source/src/nu/fw/jeti/backend/LoginInfo.java	(revision 1424)
@@ -30,4 +30,5 @@
 
 import nu.fw.jeti.util.Utils;
+
 
 /**
@@ -48,5 +49,4 @@
 	private String resource;
 	private String password;
-	private boolean useJavaProxy=true;
 	private boolean ssl=false;
 	private int proxyType=NO_PROXY;
@@ -54,12 +54,12 @@
 	private String proxyPort;
 	private String proxyUsername;
-	private String proxyPassword;  //encrypt?
+	private String proxyPassword; 
 	private int priority;
 
 	//applet
-    public LoginInfo(String server, String host, String username,
-                     String password, String resource,int port,boolean ssl,int priority)
-    {
-    	if( username != null && username.indexOf("@") !=-1 )
+    public LoginInfo(String server, String host, String username,String password,
+    		String resource,int port,boolean ssl,int priority)
+    {
+    	if(username!=null && username.indexOf("@")!=-1 )
     	{
     		this.host = server;
@@ -85,16 +85,8 @@
     }
 
-	public LoginInfo(String server, String host, String username,
-            String password, String resource,int port, boolean ssl,int priority,
-            boolean useProxy)
-	{
-		 this(server,host,username,password,resource,port,ssl,priority);
-		 this.useJavaProxy = useProxy;
-	}
-
-	public LoginInfo(String server, String host, String username,
+    public LoginInfo(String server, String host, String username,
                      String password, String resource,int port, boolean ssl,int priority,
                      int proxy, String proxyServer, String proxyUsername,
-                     String proxyPassword, String proxyPort)
+                     String proxyPassword, String proxyPort )
     {
         this(server,host,username,password,resource,port,ssl,priority);
@@ -106,4 +98,18 @@
     }
 
+    public LoginInfo(String server, String host, String username, String password, String resource,
+    				 int port, boolean ssl, String proxyServer, String proxyPort)
+    {
+    	this.server = server;
+    	this.host = host;
+    	this.username = username;
+    	this.password = password;
+    	this.resource = resource;
+    	this.port = port;
+    	this.ssl = ssl;
+    	this.proxyServer = proxyServer;
+    	this.proxyPort = proxyPort;
+    }
+    
 	/**
 	 * Returns the port.
@@ -143,13 +149,4 @@
 
     /**
-     * Returns the useJavaProxy.
-     * @return boolean
-     */
-    public boolean getJavaProxy()
-    {
-    	return useJavaProxy;
-    }
-    
-    /**
 	 * Returns the ssl.
 	 * @return boolean
@@ -190,4 +187,9 @@
 	}
 
+	public void setProxyPassword(String proxyPassword)
+	{
+		this.proxyPassword = proxyPassword;
+	}
+	
 	/**
 	 * Returns the proxyPassword.
@@ -217,4 +219,14 @@
 	}
 
+	/**
+	 * Set the proxyUsername;
+	 * 
+	 */
+	
+	public void setProxyUsername(String proxyUsername)
+	{
+		this.proxyUsername = proxyUsername;
+	}
+	
 	/**
 	 * Returns the proxyUsername.
@@ -247,30 +259,11 @@
 	public boolean isHTTPProxy()
 	{
+		//System.out.println( "( " + proxyType + "==" + LoginInfo.HTTP_PROXY + " ) = " + useProxy(LoginInfo.HTTP_PROXY));
+		
 		if( useProxy(LoginInfo.HTTP_PROXY) ) 
 			return true;
-
-		if( Start.applet )
-		{
-			try
-			{
-				ProxyInfo info[] = ProxyService.getProxyInfo(new URL("http://www.google.com.br"));
-				
-				if (info != null && info.length > 0 )
-				{
-					proxyType = HTTP_PROXY;
-					proxyServer = info[0].getHost();
-					proxyPort = String.valueOf(info[0].getPort());
-					return true;
-				}
-
-			}
-			catch (Exception ex)
-			{
-				System.err.println("could not retrieve proxy configuration, attempting direct connection.");
-			}
-		}
-		return false;
-	}
-
+		else
+			return false;
+	}
 }
 /*
Index: trunk/jabberit_messenger/java_source/src/nu/fw/jeti/backend/Connect.java
===================================================================
--- trunk/jabberit_messenger/java_source/src/nu/fw/jeti/backend/Connect.java	(revision 1014)
+++ trunk/jabberit_messenger/java_source/src/nu/fw/jeti/backend/Connect.java	(revision 1424)
@@ -23,7 +23,17 @@
 package nu.fw.jeti.backend;
 
+import java.awt.Color;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.Insets;
+import java.awt.event.ActionEvent;
+import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.InputStreamReader;
 import java.io.OutputStream;
+import java.io.PrintWriter;
 import java.io.UnsupportedEncodingException;
 import java.net.InetAddress;
@@ -46,5 +56,12 @@
 import javax.net.ssl.TrustManager;
 import javax.net.ssl.X509TrustManager;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JLabel;
 import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JPasswordField;
+import javax.swing.JTextField;
+import javax.swing.border.EmptyBorder;
 
 import nu.fw.jeti.events.DiscoveryListener;
@@ -68,4 +85,5 @@
 import nu.fw.jeti.plugins.PluginsInfo;
 import nu.fw.jeti.plugins.XMPP;
+import nu.fw.jeti.util.Digest;
 import nu.fw.jeti.util.I18N;
 import nu.fw.jeti.util.Log;
@@ -79,5 +97,6 @@
 //TODO improve error reporting, make it translatable
  //class voor connectie
- public class Connect implements ConnectionPacketReceiver
+
+public class Connect implements ConnectionPacketReceiver
 {
 	private Output output;
@@ -102,4 +121,17 @@
 	private Handlers handlers;
 	private XMPP xmpp;
+	
+	// windowProxy
+	private JButton buttonCancel;
+	private JButton buttonOk;
+	private JDialog dialog;
+	private JLabel infoLabel;
+	private JLabel lblUsername;
+	private JLabel lblPassword;
+	private JPanel buttonPanel;
+	private JPanel panelMain;
+	private JPasswordField txtPassword;
+	private JOptionPane optionPane;
+	private JTextField txtUsername;
     
 	public Connect(Backend backend,IQTimerQueue timerQueue,Handlers handlers)
@@ -164,22 +196,9 @@
     public void login(LoginInfo info)
     {
-    	abort = false;
-		loginInfo = info;
-		connectThread = new Thread()
-		{
-			public void run()
-			{
-				connect();
-			}
-		};
-		connectThread.start(); 
+    	autoLogin(info,2);
     }
     
-	public void autoLogin(LoginInfo info,final int tries)
-	{
-		if(System.currentTimeMillis() < latestConnected + 60000)
-		{//prevent ping pong if things go wrong at login
-			return;
-		}
+    public void autoLogin(LoginInfo info,final int tries)
+	{
 		abort = false;
 		loginInfo = info;
@@ -187,21 +206,92 @@
 		{
 			int tel = 0;
+			
 			public void run()
 			{
-				boolean connected=false;
-				while(tel < tries)
+				boolean connected = false;
+				int triesc	= 0; 
+				int posIn	= 0;
+				int posFi	= 0;
+				
+				String hosts = loginInfo.getHost();
+				
+				if( hosts.indexOf(" ") != -1 )
 				{
-					connected = connect();
-					if(connected) break;
-					try
+					hosts = hosts + " ";
+					
+					for( int i = 0; i < hosts.length(); i++ )
 					{
-						Thread.sleep(60000);
+						String w = String.valueOf(hosts.charAt(i));
+						
+						if( w.equals(" ") )
+						{
+							posIn = posFi;
+							posFi = i;
+							
+							String hostConnect = hosts.substring(posIn, posFi).trim();
+							
+							while( tel < tries )
+							{
+								if( tel == 0)
+								{
+									connected = connect( hostConnect, false );
+								}
+								else
+								{
+									connected = connect( hostConnect, true );
+								}
+
+								if( connected )
+								{
+									i = hosts.length();
+									break;
+								}	
+								
+								try { Thread.sleep(600);}
+								catch (InterruptedException e){}
+								tel++;
+							}	
+							
+								
+							tel = 0;
+						}
 					}
-					catch (InterruptedException e){}
-					tel++;
 				}
+				else
+				{
+					
+					while( tel < tries )
+					{
+						if( tel == 0)
+						{
+							connected = connect( hosts, false );
+						}
+						else
+						{
+							connected = connect( hosts, true );
+						}
+
+						if( connected )
+						{
+							break;
+						}	
+						
+						try { Thread.sleep(600);}
+						catch (InterruptedException e){}
+						tel++;
+					}	
+				}
+
+				if( !connected )
+				{
+					interrupt();
+	        		loginInfo.setProxyUsername(null);
+	        		loginInfo.setProxyPassword(null);
+					System.out.println("***** Login Failed *****");					
+				}
 			}
 		};
-		connectThread.start(); 
+		
+		connectThread.start();
 	}
     
@@ -209,5 +299,6 @@
     {
 		abort = true;
-		if(socket != null)
+		
+		if( socket != null )
 		{
 			try
@@ -229,5 +320,5 @@
     }
 
-	synchronized private boolean connect()
+	synchronized private boolean connect( String host, boolean proxy )
 	{	
 		latestConnected = System.currentTimeMillis();
@@ -238,13 +329,4 @@
 		if( authenticated )
 			disconnect();//clear old connection
-		
-		if (loginInfo.useProxy(LoginInfo.SOCKS_PROXY))
-		{
-			System.getProperties().put( "proxySet", "true" );
-			System.getProperties().setProperty("socksProxyHost", loginInfo.getProxyServer());
-			System.getProperties().setProperty("socksProxyPort", loginInfo.getProxyPort());
-		  	System.getProperties().setProperty("socksProxyUserName", loginInfo.getProxyUsername());
-		  	if(loginInfo.getProxyPassword()!=null)System.getProperties().setProperty("socksProxyPassword", loginInfo.getProxyPassword());
-		}
 		
 		jabberHandler = new JabberHandler(this,handlers);
@@ -258,6 +340,6 @@
 		try
 		{   		
-            host = loginInfo.getHost();
-            if (host == null || host.length() == 0)
+            
+			if (host == null || host.length() == 0)
             {
             	if(loginInfo.useProxy(LoginInfo.NO_PROXY) && PluginsInfo.isPluginLoaded("xmpp"))
@@ -268,29 +350,35 @@
             }
                        
-		   	if(loginInfo.isSSl()) 
+		   	if( loginInfo.isSSl() ) 
 	       	{
-		   		if( loginInfo.isHTTPProxy() && loginInfo.getJavaProxy() ) 
-	           	{
-	   				Socket tunnel = createHTTPTunel(host); 
-	       			socket = new DummySSLSocketFactory().createSocket(tunnel,host,loginInfo.getPort(),true);
+		   		if( proxy )
+		   	   	{
+	   				//System.out.println("CONNECT COM PROXY - SEGURA : " + host);
+		   			Socket tunnel = createHTTPTunel(host); 
+	       			socket = new DummySSLSocketFactory().createSocket(tunnel, host, loginInfo.getPort(),true);
 	       		}
 		   		else
+		   		{
+		   			//System.out.println("CONNECT SEM PROXY - SEGURA : " + host);
 		   			socket = new DummySSLSocketFactory().createSocket(host,loginInfo.getPort());
+		   		}
 	       	}
 	       	else 
 	       	{
-	       		socket = new Socket(host,loginInfo.getPort());
+	       		if( proxy )
+	       		{
+	       			//System.out.println("CONNECT COM PROXY - NÃO SEGURA : " + host);
+	       			socket = createHTTPTunel(host);
+	       		}
+	       		else
+	       		{
+	       			//System.out.println("CONNECT SEM PROXY - NÃO SEGURA : " + host);
+	       			socket = new Socket( host,loginInfo.getPort() );
+	       		}
 	       	}
         }
-		catch (UnknownHostException ex)
-        {
-            sendLoginError(MessageFormat.format(I18N.gettext("main.loginstatus.Server_{0}_could_not_be_found"), new Object[] { loginInfo.getHost() } ));
-			return false;
-        }
-		catch (IOException ex)
-		{
-			sendLoginError(ex.getMessage());
-			return false;
-        }
+		catch (UnknownHostException ex){ return false; }
+		catch (IOException ex){ return false; }
+
 		if( abort )
 			return false;
@@ -298,11 +386,7 @@
 		try
 		{
-			input = new Input(socket.getInputStream(),this,jabberHandler);
+			input = new Input(socket.getInputStream(), this, jabberHandler);
         }
-		catch (IOException ex)
-        {
-			sendLoginError(I18N.gettext("main.loginstatus.Could_not_open_input_because") + " " + ex.getMessage());
-			return false;
-        }
+		catch (IOException ex){ return false; }
 		
 		if( abort )
@@ -311,21 +395,20 @@
 	    try
 	    {
-			output = new Output(socket,loginInfo.getServer(),this,socket.getOutputStream());
+			output = new Output(socket, loginInfo.getServer(), this, socket.getOutputStream());
         }
-	    catch (IOException ex)
-        {
-			sendLoginError(I18N.gettext("main.loginstatus.Could_not_open_output_because") + " " +ex.getMessage());
+	    catch (IOException ex){ return false; }
+		
+        return true;
+	}
+	
+	String host;
+	
+	public boolean startTls(ConnectionPacketReceiver cpr)
+	{
+		if(abort)
 			return false;
-        }
-
-        return true;
-	}
-	
-	String host;
-	
-	public boolean startTls(ConnectionPacketReceiver cpr)
-	{
-		if(abort)return false;
-		try{   		
+		
+		try
+		{   		
            //TODO stop output
 			output.disconnect(false);
@@ -334,29 +417,35 @@
             jabberHandler = new JabberHandler(cpr,handlers);
           
-            
-            try{
+            try
+            {
 	            input = new Input(socket.getInputStream(),this,jabberHandler);
-	        }catch (IOException ex)
+	        }
+            catch (IOException ex)
 	        {
-				sendLoginError(I18N.gettext("main.loginstatus.Could_not_open_input_because") + " " + ex.getMessage());
 				return false;
 	        }
 	        
-            try{
+            try
+            {
 		    	output = new Output(socket,loginInfo.getServer(),this,socket.getOutputStream());
-	        }catch (IOException ex)
+	        }
+            catch (IOException ex)
 	        {
-				sendLoginError(I18N.gettext("main.loginstatus.Could_not_open_output_because") + " " +ex.getMessage());
+				//sendLoginError(I18N.gettext("main.loginstatus.Could_not_open_output_because") + " " +ex.getMessage());
 				return false;
 	        }
 	                    
-	        if(abort) return false;
+	        if(abort)
+	        	return false;
 	       
-		}catch (IOException e) {e.printStackTrace();}
+		}
+		catch(IOException e){}
+		
 		return true;
 	}
 	
 	//used by compression plugin
-	public Socket getSocket(){
+	public Socket getSocket()
+	{
 		return socket;
 	}
@@ -367,4 +456,5 @@
 		if ( abort )
 			return false;
+	
 		output.disconnect(false);
 		Input input2 = input;
@@ -391,5 +481,4 @@
 	}
 	
-	
 	public void startSasl(ConnectionPacketReceiver cpr)
 	{
@@ -426,25 +515,204 @@
 		String tunnelHost = loginInfo.getProxyServer();
 	    int tunnelPort = Integer.valueOf(loginInfo.getProxyPort()).intValue();
-	    Socket tunnel = new Socket(tunnelHost, tunnelPort);
-	    doTunnelHandshake(tunnel,host,loginInfo.getPort());
-	    return tunnel;	     	     
-	}
-	
-	private void doTunnelHandshake(Socket tunnel, String host, int port)    throws IOException
+	    String typeProxy = typeProxy(tunnelHost, tunnelPort, host, loginInfo.getPort());
+
+		if( typeProxy.indexOf("Proxy-Authenticate: Digest") != -1 )
+		{
+			// Proxy Username and Password
+			if( loginInfo.getProxyPassword() == null && loginInfo.getProxyPassword() == null)
+				windowProxy(tunnelHost);
+
+			return doTunnelHandshakeDigest(host, loginInfo.getPort());
+		}
+		else if( typeProxy.indexOf("Proxy-Authenticate: Basic") != -1 )
+		{
+			// Proxy Username and Password
+			if( loginInfo.getProxyPassword() == null && loginInfo.getProxyPassword() == null)
+				windowProxy(tunnelHost);
+
+			Socket tunnel = new Socket(tunnelHost, tunnelPort);
+			doTunnelHandshake(tunnel, host, loginInfo.getPort());
+			return tunnel;
+		}
+		else if( typeProxy.indexOf("HTTP/1.0 200") != -1 )
+		{
+			Socket tunnel = new Socket(tunnelHost, tunnelPort);
+			PrintWriter writeConnection = new PrintWriter( tunnel.getOutputStream(), true ); 
+			BufferedReader readConnection = new BufferedReader(new InputStreamReader(tunnel.getInputStream()));
+
+			String msg = "CONNECT " + host + ":" + loginInfo.getPort() + " HTTP/1.1\r\n" +
+			 			 "User-Agent: " + sun.net.www.protocol.http.HttpURLConnection.userAgent + "\r\n" + 
+			 			 "Proxy-Connection: Keep-Alive\r\n";
+			
+			writeConnection.println(msg);
+			String line = "";
+			
+			while((line = readConnection.readLine()) != null )
+			{
+				if( line.indexOf("HTTP/1.0 200") != -1 )
+					break;
+			}
+			
+			return tunnel;
+		}
+
+		return new Socket();
+	}
+
+	private void windowProxy(String tunnelHost)
+	{
+		panelMain = new JPanel();
+		panelMain.setBackground(Color.ORANGE);
+		panelMain.setPreferredSize(new Dimension(400,120));
+		panelMain.setLayout(new GridBagLayout());
+		GridBagConstraints gbc = new GridBagConstraints();
+
+		// Espaco entre elementos;
+		gbc.insets = new Insets(2, 2, 2, 2);
+	    gbc.gridy = 0; // row
+	    gbc.gridx = 0; // col
+	    gbc.gridwidth = 2; 
+	    gbc.anchor = GridBagConstraints.WEST;
+	    
+	    infoLabel = new JLabel(I18N.gettext("main.connect.proxy.Authentication_for") + " " + tunnelHost + " :");
+	    infoLabel.setFont(new Font("SansSerif",Font.BOLD, 14));
+	    infoLabel.setBorder(new EmptyBorder(0, 0, 5, 0));
+	    panelMain.add(infoLabel, gbc);
+
+	    // Label Username
+	    gbc.gridy = 1; // row
+	    gbc.gridx = 0; // col
+	    gbc.gridwidth = 1;
+	    lblUsername = new JLabel(I18N.gettext("main.connect.proxy.Username")+":");
+	    panelMain.add(lblUsername, gbc);
+
+	    // JTextField do Username
+	    gbc.gridy = 1; // row
+	    gbc.gridx = 1; // col
+	    txtUsername = new JTextField(20);
+	    panelMain.add(txtUsername, gbc);
+
+	    // Label Password
+	    gbc.gridy = 2; // row
+	    gbc.gridx = 0; // col
+	    lblPassword = new JLabel(I18N.gettext("main.connect.proxy.Password")+":");
+	    panelMain.add(lblPassword, gbc);    
+
+	    // JPasswordField		    
+	    gbc.gridy = 2; // row
+	    gbc.gridx = 1; // col
+	    txtPassword = new JPasswordField(20);
+	    panelMain.add(txtPassword, gbc);
+
+	    // Buttons
+	    gbc.gridy = 3; // linha
+	    gbc.gridx = 1; // coluna
+	    gbc.gridwidth = 2; // duas células na linha
+	    gbc.anchor = GridBagConstraints.WEST;
+	    buttonPanel	= new JPanel();
+	    buttonCancel = new JButton(I18N.gettext("main.connect.proxy.Cancel"));
+	    buttonOk = new JButton(I18N.gettext("main.connect.proxy.Ok"));
+	    
+	    // Event click Ok
+		buttonOk.addActionListener(new java.awt.event.ActionListener()
+		{
+            public void actionPerformed(ActionEvent e)
+            {
+            	String Username = txtUsername.getText().toString();
+            	String Password = txtPassword.getText().toString();
+            	
+            	if( !Username.trim().equals("") && !Password.trim().equals("") )
+            	{	 
+            		loginInfo.setProxyUsername(Username);
+            		loginInfo.setProxyPassword(Password);
+            		dialog.setVisible(false);
+            	}
+            }
+		});
+
+	    // Event click Cancel
+		buttonCancel.addActionListener(new java.awt.event.ActionListener()
+		{
+            public void actionPerformed(ActionEvent e)
+            {
+        		loginInfo.setProxyUsername(null);
+        		loginInfo.setProxyPassword(null);
+            	dialog.setVisible(false);
+            }
+		});
+		
+		buttonPanel.setBackground(Color.ORANGE);
+		buttonPanel.add(buttonOk);
+		buttonPanel.add(buttonCancel);
+	    panelMain.add(buttonPanel, gbc);
+		
+	    optionPane = new JOptionPane();
+	    optionPane.setMessage(I18N.gettext("main.connect.proxy.The_proxy_is_requesting_a_username_and_password") + "!");
+	    optionPane.setMessageType(JOptionPane.INFORMATION_MESSAGE);
+	    optionPane.setOptions(new Object[] {panelMain});
+	    dialog = optionPane.createDialog(null, I18N.gettext("main.connect.proxy.Authentication_required"));
+	    dialog.setVisible(true);
+	}
+	
+	private String typeProxy(String proxyServer, int proxyPort, String host, int port) throws IOException
+	{
+		Socket connection = new Socket(proxyServer, proxyPort);
+		PrintWriter writeConnection = new PrintWriter( connection.getOutputStream(), true ); 
+		BufferedReader readConnection = new BufferedReader(new InputStreamReader(connection.getInputStream()));
+		String _return = "";
+		String line = "";
+		int count = 0;
+		
+		String msg = "CONNECT " + host + ":" + port + " HTTP/1.1\r\n" +
+					 "User-Agent: " + sun.net.www.protocol.http.HttpURLConnection.userAgent + "\r\n" + 
+					 "Proxy-Connection: Keep-Alive\r\n";
+
+		writeConnection.println(msg);
+		
+		while((line = readConnection.readLine()) != null )
+		{
+			if( line.indexOf("Proxy") != -1 )
+				_return += line + "\n";
+			
+			if( line.indexOf("Proxy-Connection: close") != -1 || count == 12 )
+				break;
+
+			if( line.indexOf("HTTP/1.0 200") != -1 )
+			{
+				_return += line + "\n";
+				break;
+			}
+			count++;
+		}
+		
+		
+		writeConnection.close();
+		readConnection.close();
+		connection.close();
+
+		return _return;
+	}
+
+	// Proxy Authorization: Basic	
+	private void doTunnelHandshake(Socket tunnel, String host, int port) throws IOException
 	{
 		OutputStream out = tunnel.getOutputStream();
+		
 		String msg = "CONNECT " + host + ":" + port + " HTTP/1.0\n"
 				+ "User-Agent: "
 				+ sun.net.www.protocol.http.HttpURLConnection.userAgent;
-				
-		if (loginInfo.getProxyUsername() != null && loginInfo.getProxyPassword() != null) {
-		          //add basic authentication header for the proxy
-		          sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
-		          String encodedPassword = enc.encode((loginInfo.getProxyUsername() + ":" + loginInfo.getProxyPassword()).getBytes());
-		           msg = msg + "\nProxy-Authorization: Basic " + encodedPassword;
+		
+		if ( loginInfo.getProxyUsername() != null && loginInfo.getProxyPassword() != null )
+		{
+			//add basic authentication header for the proxy
+			sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
+			String encodedPassword = enc.encode((loginInfo.getProxyUsername() + ":" + loginInfo.getProxyPassword()).getBytes());
+			msg = msg + "\nProxy-Authorization: Basic " + encodedPassword;
 	    }
-	    msg = msg + "\nContent-Length: 0"
-	    			+"\nPragma: no-cache"
-					+"\r\n\r\n";
+		
+		msg = msg + "\nContent-Length: 0"
+				  + "\nPragma: no-cache"
+		          + "\r\n\r\n";
+
 		byte b[];
 		try
@@ -455,5 +723,6 @@
 			 */
 			b = msg.getBytes("ASCII7");
-		} catch (UnsupportedEncodingException ignored)
+		} 
+		catch (UnsupportedEncodingException ignored)
 		{
 			/*
@@ -503,5 +772,6 @@
 		{
 			replyStr = new String(reply, 0, replyLen, "ASCII7");
-		} catch (UnsupportedEncodingException ignored)
+		}
+		catch (UnsupportedEncodingException ignored)
 		{
 			replyStr = new String(reply, 0, replyLen);
@@ -512,4 +782,5 @@
 		 * HTTP/1.1 instead of 1.0
 		 */
+		
 		// if (!replyStr.startsWith("HTTP/1.0 200")) {
 		if (replyStr.toLowerCase().indexOf("200 connection established") == -1)
@@ -518,10 +789,119 @@
 			String tunnelPort = System.getProperty("http.proxyPort");
 			throw new IOException("Unable to tunnel through " + tunnelHost
-					+ ":" + tunnelPort + ".  Proxy returns \"" + replyStr
-					+ "\"");
-		}
+					+ ":" + tunnelPort + ".  Proxy returns \"" + replyStr + "\"");
+		}
+		
 		/* tunneling Handshake was successful! */
 	}
 
+	//Proxy-Authenticate Digest
+	private Socket doTunnelHandshakeDigest(String host, int port) throws IOException
+	{
+		Digest hashProxy	= new Digest();
+		String response		= "";
+		String nonce		= "";
+		String cnonce		= "ALEC290908" + String.valueOf(System.currentTimeMillis());
+		String qop			= "";
+		String uri			= "/";
+		String username		= loginInfo.getProxyUsername();
+		String password		= loginInfo.getProxyPassword();
+		String realm		= "";
+		String line			= "";
+
+		// Dados Proxy
+		String proxyServer = loginInfo.getProxyServer();
+		int proxyPort = Integer.valueOf(loginInfo.getProxyPort()).intValue();
+
+		// PRIMEIRA PARTE
+		Socket tunnel = new Socket(proxyServer, proxyPort);
+		PrintWriter writeTunnel = new PrintWriter(tunnel.getOutputStream(), true);
+		BufferedReader readTunnel = new BufferedReader(new InputStreamReader(tunnel.getInputStream()));		
+
+		String msg = "CONNECT " + host + ":" + port + " HTTP/1.1\r\n" +
+					 "User-Agent: " + sun.net.www.protocol.http.HttpURLConnection.userAgent + "\r\n" +
+					 "Proxy-Connection: Keep-Alive\r\n";
+
+		writeTunnel.println(msg);
+		
+		while((line = readTunnel.readLine()) != null )
+		{
+			// Get nonce;
+			if ( line.indexOf("nonce=\"") != -1 )
+			{
+	    		nonce = line.substring(line.indexOf("nonce=\"") + 7);
+	    		nonce = nonce.substring(0,nonce.indexOf("\","));
+			}	
+
+			// Get realm;
+			if ( line.indexOf("realm=\"") != -1 )
+			{
+	    		realm = line.substring(line.indexOf("realm=\"") + 7);
+	    		realm = realm.substring(0,realm.indexOf("\","));
+			}
+			
+			// Get qop;
+			if ( line.indexOf("qop=\"") != -1 )
+			{
+				qop = line.substring(line.indexOf("qop=\"") + 5);
+				qop = qop.substring(0,qop.indexOf("\","));
+			}
+		}
+
+		writeTunnel.close();
+		readTunnel.close();
+		tunnel.close();
+		
+		response = hashProxy.hashMD5(nonce, cnonce, qop, "CONNECT:"+uri, username, password, realm);
+		line = "";
+		
+		// SEGUNDA PARTE
+		tunnel		= new Socket(proxyServer, proxyPort);
+		writeTunnel	= new PrintWriter(tunnel.getOutputStream(), true);
+		readTunnel	= new BufferedReader(new InputStreamReader(tunnel.getInputStream()));		
+
+		msg = "CONNECT " + host + ":" + port + " HTTP/1.1\r\n" +
+			  "Proxy-Authorization: Digest username=\""+username+"\", "+
+		      "realm=\""+realm+"\", nonce=\""+nonce+"\", uri=\""+uri+"\", " +
+		      "cnonce=\""+cnonce+"\", nc=00000001, qop=\""+qop+"\", response=\""+response+"\"\r\n" +
+			  "User-Agent: " + sun.net.www.protocol.http.HttpURLConnection.userAgent + "\r\n" +
+		      "Proxy-Connection: Keep-Alive\r\n";
+
+		int count = 0;
+		writeTunnel.println(msg);
+		
+		while((line = readTunnel.readLine().trim()) != null )
+		{
+			if( line.indexOf("HTTP/1.0 200 OK") != -1 )
+				break;
+			
+			if( line.indexOf("HTTP/1.0 503") != -1 )
+				break;
+			
+			if( count == 1 )
+				break;
+			
+			count++;
+		}
+		
+		/* tunneling Handshake was successful! */		
+		return tunnel;
+	}
+	
+	private void sendLoginMessage(String message)
+	{
+		for(Iterator j = backend.getListeners(LoginListener.class);j.hasNext();)
+		{
+			((LoginListener)j.next()).loginMessage(message);
+		}
+	}
+	
+	private void sendLoginStatus(int count)
+	{
+		/*for(Iterator j = backend.getListeners(LoginListener.class);j.hasNext();)
+		{
+			((LoginListener)j.next()).loginStatus(count);
+		}*/
+	}
+	
 	public void sendLoginError(String message)
 	{
@@ -623,5 +1003,5 @@
 				return;
 			}
-//			TODO remove lowercase if filetransfer bug fixed
+			//TODO remove lowercase if filetransfer bug fixed
 			JID jid = new JID(loginInfo.getUsername().toLowerCase(),loginInfo.getServer() ,loginInfo.getResource());
 			authenticated(jid);
@@ -637,11 +1017,11 @@
         reconnecting = false;
 		output.setAuthenticated(); 
-		//output.send(new InfoQuery(new JID(server),"get",new IQBrowse()));
-		//browse(new JID(loginInfo.getServer()),null);
+
 		//TODO increase timeout
 		getItems(new JID(loginInfo.getServer()), new DiscoveryListener()
 		{
 			public void discoveryItemResult(JID jid, DiscoveryItem item)
-			{//cache disco items for this server
+			{
+				//cache disco items for this server
 				if (item.hasItems())
 				{
@@ -660,15 +1040,8 @@
 		{
 			show = Presence.AVAILABLE;
-			//status = Presence.toLongShow(show);
-		}
-		latestConnected =System.currentTimeMillis();
-		//moved to backend rosterloaded
-		//			for(Iterator j = backend.getListeners(nu.fw.jeti.events.StatusChangeListener.class);j.hasNext();)
-		//			{//online
-		//				((nu.fw.jeti.events.StatusChangeListener)j.next()).connectionChanged(true);
-		//			}
-		//changeStatus(show,status);
-	}
-	
+		}
+		latestConnected = System.currentTimeMillis();
+		
+	}
 	
 	public void connected()
@@ -703,5 +1076,4 @@
 	public void inputDeath()
 	{
-		//if(true)return; something todo with xmpp plugin, should not be here????? or server deads will not be detected
 		try
 		{
@@ -729,8 +1101,5 @@
 			}
 		}
-		sendLoginError(I18N.gettext("main.loginstatus.Lost_Input"));
-		//else
-		//io error while logging in
-		//do something usefull
+		
 	}
 
@@ -853,6 +1222,8 @@
 		private SSLSocketFactory factory;
 		
-		public DummySSLSocketFactory() {
-			try {
+		public DummySSLSocketFactory()
+		{
+			try
+			{
 				SSLContext sslcontent = SSLContext.getInstance("TLS");
 				sslcontent.init(null, // KeyManager not required
@@ -861,16 +1232,16 @@
 				factory = sslcontent.getSocketFactory();
 			}
-			catch (NoSuchAlgorithmException e) {
+			catch (NoSuchAlgorithmException e)
+			{
 				e.printStackTrace();
 			}
-			catch (KeyManagementException e) {
+			catch (KeyManagementException e)
+			{
 				e.printStackTrace();
 			}
 		}
 	
-
 		public Socket createSocket(Socket socket, String s, int i,boolean flag)	throws IOException
 		{
-			
 			return factory.createSocket(socket, s, i, flag);
 		}
@@ -893,31 +1264,32 @@
 		public Socket createSocket(String s, int i)	throws IOException
 		{
-	        /*
-	        * register a callback for handshaking completion event
-	        */
+		  
+		  /**
+	       * register a callback for handshaking completion event
+	       */
 			
 			Socket so = factory.createSocket(s, i);
-	         ((SSLSocket)so).addHandshakeCompletedListener(
-	            new HandshakeCompletedListener() {
-	               public void handshakeCompleted(
-	                  HandshakeCompletedEvent event) {
-	                  System.out.println("Handshake finished!");
-	                  System.out.println(
-	                  "\t CipherSuite:" + event.getCipherSuite());
-	                  System.out.println(
-	                  "\t SessionId " + event.getSession());
-	                  System.out.println(
-	                  "\t PeerHost " + event.getSession().getPeerHost());
-	               }
-	            }
-	         );
+	        ((SSLSocket)so).addHandshakeCompletedListener(new HandshakeCompletedListener()
+				{
+					public void handshakeCompleted(HandshakeCompletedEvent event)
+					{
+						System.out.println("** Handshake finished! **");
+						//System.out.println("\t CipherSuite:" + event.getCipherSuite());
+						//System.out.println("\t SessionId " + event.getSession());
+						//System.out.println("\t PeerHost " + event.getSession().getPeerHost());
+					}
+				}
+	        );
+	        
 	        return so;
 		}
 		
-		public String[] getDefaultCipherSuites() {
+		public String[] getDefaultCipherSuites()
+		{
 			return factory.getSupportedCipherSuites();
 		}
 
-		public String[] getSupportedCipherSuites() {
+		public String[] getSupportedCipherSuites()
+		{
 			return factory.getSupportedCipherSuites();
 		}
@@ -928,19 +1300,21 @@
 	 * except date validation.
 	 */
-	private static class DummyTrustManager implements X509TrustManager {
+	private static class DummyTrustManager implements X509TrustManager
+	{
 
 		public void checkClientTrusted(X509Certificate[] chain, String authType) {	}
 
-		public void checkServerTrusted(X509Certificate[] chain, String authType)  {
-			try {
+		public void checkServerTrusted(X509Certificate[] chain, String authType)
+		{
+			try
+			{
 				chain[0].checkValidity();
 			}
-			catch (CertificateExpiredException e) {
-			}
-			catch (CertificateNotYetValidException e) {
-			}
-		}
-
-		public X509Certificate[] getAcceptedIssuers() {
+			catch (CertificateExpiredException e){}
+			catch (CertificateNotYetValidException e){}
+		}
+
+		public X509Certificate[] getAcceptedIssuers()
+		{
 			return new X509Certificate[0];
 		}
