#!/usr/bin/wish
###############################################################
### Msn4Lin					###############
### http://www.BorSanZa.com/    		###############
### Borja Snchez Zamorano                      ###############
###						###############
### Version 0.2                 		###############
###############################################################
###
### Original Version
###
### Compu's Messenger - ccmsn
### Copyright (C) 2001 Dave Mifsud
###
### This program is free software; you can redistribute it and/or modify
### it under the terms of the GNU General Public License as published by
### the Free Software Foundation; version 2 of the License
###
### This program is distributed in the hope that it will be useful,
### but WITHOUT ANY WARRANTY; without even the implied warranty of
### MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
### GNU General Public License for more details.
###
### You should have received a copy of the GNU General Public License
### along with this program; if not, write to the Free Software
### Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

exec ./comprobar &
set comprobacion 0

source migmd5.tcl

set version "0.2e"

###############################################################################

set images_folder "images"
set sounds_folder "sounds"
set lang_folder   "lang"

# :):D:o:P;):(:S:|(Y)(N)(L)(U)(K)(G)(F)(X)(Z)(P)(B)(D)(T)(@)(C)(i)(H)(S)(*)(8)(E)(M):[:'((w)(&)(o):$:@(A)(6)(~)(^)({)(})
set emotions {{":-)" smile} {":)" smile} {":-D" smiled} {":D" smiled}
	{":->" smiled} {":>" smiled} {":-O" smileo} {":O" smileo} {":-P" smilep}
	{":P" smilep} {";-)" wink} {";)" wink} {":-(" sad} {":(" sad}
	{":-<" sad} {":<" sad} {":-S" crooked} {":S" crooked} {":-|" disgust}
	{":|" disgust} {"(Y)" thumbu} {"(N)" thumbd} {"(L)" love} {"(U)" unlove}
	{"(K)" lips} {"(G)" gift} {"(F)" rose} {"(X)" emgirl} {"(Z)" emboy}
	{"(P)" photo} {"(B)" beer} {"(D)" coctail} {"(T)" emphone} {"(@)" emcat}
	{"(C)" emcup} {"(I)" embulb} {"(H)" emhottie} {"(S)" emsleep}
	{"(*)" emstar} {"(8)" emnote} {"(E)" email} {"(M)" messenger}
	{":-[" vampire} {":[" vampire} {":'(" crysmile} {"(W)" wiltedrose}
	{"(&)" bowwow}  {"(O)" emclock} {":$" embaressed} {":-$" embaressed}
	{":@" angry} {":-@" angry} {"(A)" angel} {"(6)" devil} {"(~)" film}
	{"(^)" cake} {"(\173)" dudehug} {"(\175)" girlhug}}

set emotion_files {smile smiled smileo smilep wink sad crooked disgust thumbu
	thumbd love unlove lips gift rose emgirl emboy photo beer coctail
	emphone emcat emcup embulb emhottie emsleep emstar emnote email
	messenger vampire crysmile wiltedrose bowwow emclock embaressed
	angry angel devil film cake dudehug girlhug}

set list_states {{NLN 17 #000000 online online}
		{IDL 26 #000000 online away}
		{BRB 19 #000000 online away}
		{PHN 21 #000000 online busy}
		{BSY 18 #000000 online busy}
		{AWY 27 #000000 online away}
		{LUN 22 #000000 online away}
		{HDN 23 #000000 offline offline}
		{FLN 23 #000000 offline offline}}

###############################################################################

set trid 0

set user_info ""
set user_stat "FLN"

set list_fl [list]
set list_rl [list]
set list_al [list]
set list_bl [list]
set list_users [list]
set list_notify [list]
set list_cmdhnd [list]

set mostrar_desconectados 1
set mostrar_conectados 1
set sb_num 0
set sb_list [list]
set sb_list_cal [list]

set config(login) ""			;# These are defaults for users without
set config(save_password) 0		;# a config file
set config(keep_logs) 0
set config(fontname) Helvetica
set config(fontsize) 12
set config(no_auto_update) 0
set config(language) 1000
set config(proxy) ""
set config(start_ns_server) "messenger.hotmail.com:1863"
set config(last_client_version) ""

set password ""

###############################################################################

if {$tcl_platform(platform) == "unix"} {
  set HOME "$env(HOME)/.msn4lin"
} else {
  set HOME "msn4lin"
}

set log_dir "${HOME}/logs"

###############################################################################

for {set i 1} {$i <= 256} {incr i} {
  set c [format %c $i]
  if {![string match \[a-zA-Z0-9\] $c]} {
    set url_map($c) %[format %.2X $i]
  }
}

###############################################################################
###############################################################################
###############################################################################

proc create_dir {path} {
  global tcl_platform

  if {[file isdirectory $path] == 0} {
     file mkdir $path
     if {$tcl_platform(platform) == "unix"} {
       file attributes $path -permissions 00700
     }
  }
}

###############################################################################

proc save_config {} {
  global tcl_platform config HOME version password

  if {$tcl_platform(platform) == "unix"} {
    set file_id [open "${HOME}/config" w 00600]
  } else {
    set file_id [open "${HOME}/config" w]
  }
  puts $file_id "msn4lin_config_version 1"
  set config(last_client_version) $version

  set config_entries [array get config]
  set items [llength $config_entries]
  for {set idx 0} {$idx < $items} {incr idx 1} {
    set var_attribute [lindex $config_entries $idx]; incr idx 1
    set var_value [lindex $config_entries $idx]
    puts $file_id "$var_attribute $var_value"
  }
  if {$config(save_password)} {
    puts $file_id "password ${password}"
  }
  close $file_id
}

###############################################################################

proc load_config {} {
  global config HOME password

  if {([file readable "${HOME}/config"] == 0) ||
    ([file isfile "${HOME}/config"] == 0)} {
    return 1
  }
  set file_id [open "${HOME}/config" r]
  gets $file_id tmp_data
  if {$tmp_data != "msn4lin_config_version 1"} {	;# config version not supported!
    return 1
  }
  while {[gets $file_id tmp_data] != "-1"} {
    set var_data [split $tmp_data]
    set var_attribute [lindex $var_data 0]
    set var_value [lindex $var_data 1]
    set config($var_attribute) $var_value
  }
  if {[info exists config(password)]} {
    set password $config(password)
    unset config(password)
  }
  close $file_id
}

###############################################################################

proc load_lang_disponibles {} {
  global lang_disponibles lang_folder

  if {([file readable "${lang_folder}/languages"] == 0) ||
    ([file isfile "${lang_folder}/languages"] == 0)} {
    return 1
  }
  set file_id [open "${lang_folder}/languages" r]
  while {[gets $file_id tmp_data] != "-1"} {
    set var_data [split $tmp_data]
    set lang_disponibles([lindex $var_data 0]) [lindex $var_data 1]
  }
  close $file_id
}

###############################################################################

proc msn4lin_reboot {} {
  global Frases allfonts

  toplevel .reiniciar
  wm geometry .reiniciar +0+0
  wm title .reiniciar $Frases(65)
  wm resizable .reiniciar false false
  wm transient .reiniciar .
  canvas .reiniciar.c -width 250 -height 70
  pack .reiniciar.c -expand true -fill both
  tkwait visibility .reiniciar
  .reiniciar.c create text 125 10 -font "$allfonts(3) bold" -anchor n -text $Frases(66)
  button .reiniciar.c.cancel -text $Frases(15) -command "destroy .reiniciar" -font "$allfonts(1)"
  .reiniciar.c create window 125 35 -window .reiniciar.c.cancel -anchor n
  set x [expr ([winfo vrootwidth .reiniciar] - [winfo width .reiniciar]) / 2]
  set y [expr ([winfo vrootheight .reiniciar] - [winfo height .reiniciar]) / 2]
  wm geometry .reiniciar +${x}+${y}

  bind .reiniciar <Destroy> {if {"%W" == ".reiniciar"} { grab release .reiniciar } }
  bind .reiniciar <Escape> { destroy .reiniciar }
  bind .reiniciar <Return> { destroy .reiniciar }

  grab set .reiniciar
}

###############################################################################

proc load_lang {{select -1}} {
  global Frases lang_folder config lang_disponibles allfonts

# Cargar idioma por defecto

  if {([file readable "${lang_folder}/spanish.msn4lin"] == 0) ||
     ([file isfile "${lang_folder}/spanish.msn4lin"] == 0)} {
    return 1
  }
  set file_id [open "${lang_folder}/spanish.msn4lin" r]
  while {[gets $file_id tmp_data] != "-1"} {
    set var_data [split $tmp_data "="]
    set Frases([lindex $var_data 0]) [lindex $var_data 1]
  }
  close $file_id

  if {$select!=-1} {
    set config(language) $select
    save_config
  }

# Cargar las frases que se puedan del idioma seleccionado

  if {([file readable "${lang_folder}/$lang_disponibles($config(language))"] == 0) ||
     ([file isfile "${lang_folder}/$lang_disponibles($config(language))"] == 0)} {
    return 1
  }
  set file_id [open "${lang_folder}/$lang_disponibles($config(language))" r]
  while {[gets $file_id tmp_data] != "-1"} {
    set var_data [split $tmp_data "="]
    set Frases([lindex $var_data 0]) [lindex $var_data 1]
  }
  close $file_id

  if {$select!=-1} {
    msn4lin_reboot
  }
}

###############################################################################

proc msn4lin_draw_about {} {
  global Frases allfonts
  toplevel .about
  wm title .about $Frases(25)
  wm resizable .about false false
  wm transient .about .

  text .about.info -background white -width 60 -height 30 -wrap word -font "$allfonts(1)" -yscrollcommand ".about.ys set"
  scrollbar .about.ys -command ".about.info yview"
  pack .about.ys -side right -fill y
  pack .about.info -expand true -fill both
  set id [open "original.txt" r]
  .about.info insert 1.0 [read $id]
  close $id
  .about.info configure -state disabled
  update idletasks
  set x [expr ([winfo vrootwidth .about] - [winfo width .about]) / 2]
  set y [expr ([winfo vrootheight .about] - [winfo height .about]) / 2]
  wm geometry .about +${x}+${y}
}

###############################################################################

proc msn4lin_draw_about2 {} {
  global Frases allfonts
  toplevel .about2
  wm title .about2 $Frases(7)
  wm resizable .about2 false false
  wm transient .about2 .

  text .about2.info -background white -width 43 -height 19 -wrap word -font "$allfonts(1)" -yscrollcommand ".about2.ys set"
  scrollbar .about2.ys -command ".about2.info yview"
  pack .about2.ys -side right -fill y
  pack .about2.info -expand true -fill both
  set id [open "leeme.txt" r]
  .about2.info insert 1.0 [read $id]
  close $id
  .about2.info configure -state disabled
  update idletasks
  set x [expr ([winfo vrootwidth .about2] - [winfo width .about2]) / 2]
  set y [expr ([winfo vrootheight .about2] - [winfo height .about2]) / 2]
  wm geometry .about2 +${x}+${y}
}

###############################################################################

proc msn4lin_draw_agradecimientos {} {
  global Frases allfonts
  toplevel .gracias
  wm title .gracias $Frases(24)
  wm resizable .gracias false false
  wm transient .gracias .

  text .gracias.info -background white -width 43 -height 19 -wrap word -font "$allfonts(1)" -yscrollcommand ".gracias.ys set"
  scrollbar .gracias.ys -command ".gracias.info yview"
  pack .gracias.ys -side right -fill y
  pack .gracias.info -expand true -fill both
  set id [open "agradecimientos.txt" r]
  .gracias.info insert 1.0 [read $id]
  close $id
  .gracias.info configure -state disabled
  update idletasks
  set x [expr ([winfo vrootwidth .gracias] - [winfo width .gracias]) / 2]
  set y [expr ([winfo vrootheight .gracias] - [winfo height .gracias]) / 2]
  wm geometry .gracias +${x}+${y}
}

###############################################################################

proc status_log {txt {colour ""}} {

  set timestamp [clock format [clock seconds] -format %H:%M:%S]
#   .status.info insert end "\[$timestamp\] $txt" $colour
#   .status.info yview moveto 1.0
}

###############################################################################

proc msn4lin_draw_main {} {
  global images_folder emotion_files version Frases lang_disponibles allfonts version

  menu .menu_idioma -tearoff 0 -type normal -borderwidth 1 -activeborderwidth 1 -font "$allfonts(2)"
  set lang_entries [array get lang_disponibles]
  set items [llength $lang_entries]

  set cont 0

  for {set idx 0} {$idx < $items} {incr idx 1} {
    set var_attribute [lindex $lang_entries $idx]
    lappend LengOrd "$Frases($var_attribute) $var_attribute"
    incr idx 1
    incr cont 1
  }
  set LengOrd [lsort $LengOrd]

  for {set idx 0} {$idx < $cont} {incr idx 1} {
    .menu_idioma add command -label [lindex [lindex $LengOrd $idx] 0] -command "load_lang [lindex [lindex $LengOrd $idx] 1]"
  }

  .menu_idioma add command -label "$Frases(84)..." -command "sendMail \"borsanza@terra.es\" \"Aqu mando un nuevo idioma\""

  menu .my_menu -tearoff 0 -type normal -borderwidth 1 -activeborderwidth 1 -font "$allfonts(2)"
  .my_menu add command -label $Frases(17) -command "change_my_status NLN"
  .my_menu add command -label $Frases(18) -command "change_my_status BSY"
  .my_menu add command -label $Frases(19) -command "change_my_status BRB"
  .my_menu add command -label $Frases(20) -command "change_my_status AWY"
  .my_menu add command -label $Frases(21) -command "change_my_status PHN"
  .my_menu add command -label $Frases(22) -command "change_my_status LUN"
  .my_menu add command -label $Frases(23) -command "change_my_status HDN"

  menu .user_menu -tearoff 0 -type normal

  menu .main_menu -tearoff 0 -type menubar -borderwidth 0 -activeborderwidth 0 -font "$allfonts(2)"
  .main_menu add cascade -label $Frases(4) -menu .main_menu.msn
  .main_menu add cascade -label $Frases(3) -menu .main_menu.msg -state disabled
  .main_menu add cascade -label $Frases(68) -menu .main_menu.tools
  .main_menu add cascade -label $Frases(2) -menu .main_menu.help

  menu .main_menu.tools -tearoff 0 -type normal -borderwidth 1 -activeborderwidth 1 -font "$allfonts(2)"
  .main_menu.tools add cascade -label $Frases(47) -menu .menu_idioma
  .main_menu.tools add command -label $Frases(69) -command msn4lin_choose_font

  menu .main_menu.help -tearoff 0 -type normal -borderwidth 1 -activeborderwidth 1 -font "$allfonts(2)"
  .main_menu.help add command -label $Frases(5) -command "msn4lin_comprobar 1"
  .main_menu.help add command -label "$Frases(6)..." -command msn4lin_draw_agradecimientos
  .main_menu.help add separator
  .main_menu.help add command -label "$Frases(83)..." -command "sendMail \"borsanza@terra.es\" \"Fallo en Msn4Lin $version\""
  .main_menu.help add separator
  .main_menu.help add command -label $Frases(8) -command msn4lin_draw_about
  .main_menu.help add command -label $Frases(7) -command msn4lin_draw_about2

  menu .main_menu.msn -tearoff 0 -type normal -borderwidth 1 -activeborderwidth 1 -font "$allfonts(2)"
  .main_menu.msn add command -label "$Frases(81)..." -state disabled -command "login_ok 1"
  .main_menu.msn add command -label "$Frases(9)..." -command msn4lin_draw_login
  .main_menu.msn add command -label $Frases(10) -state disabled -command msn4lin_logout
  .main_menu.msn add cascade -label $Frases(11) -state disabled -menu .my_menu
  .main_menu.msn add separator
  .main_menu.msn add command -label "$Frases(12)..." -state disabled -command msn4lin_draw_addcontact
  .main_menu.msn add separator
  .main_menu.msn add command -label $Frases(13) -state disabled -command msn4lin_change_name
  .main_menu.msn add separator
  .main_menu.msn add command -label $Frases(14) -command msn4lin_proxy
  .main_menu.msn add separator
  .main_menu.msn add command -label $Frases(15) -command exit

  menu .main_menu.msg -tearoff 0 -type normal -borderwidth 1 -activeborderwidth 1 -font "$allfonts(2)"
  .main_menu.msg add separator
  .main_menu.msg add command -label "$Frases(16)..." -command send_im_other -state disabled

  wm title . "Msn4Lin $version"
  wm geometry . -0+0
  wm iconname . "Msn4Lin"
  . conf -menu .main_menu

  frame .main
  pack .main -expand true -fill both

  image create photo online -file ${images_folder}/online.gif
  image create photo offline -file ${images_folder}/offline.gif
  image create photo away -file ${images_folder}/away.gif
  image create photo busy -file ${images_folder}/busy.gif
  image create photo blocked -file ${images_folder}/blocked.gif

  image create photo flechaar -file ${images_folder}/flechaar.gif
  image create photo flechaab -file ${images_folder}/flechaab.gif
  image create photo onlineh -file ${images_folder}/onlinehigh.gif
  image create photo offlineh -file ${images_folder}/offlinehigh.gif
  image create photo awayh -file ${images_folder}/awayhigh.gif
  image create photo busyh -file ${images_folder}/busyhigh.gif
  image create photo flechanegra -file ${images_folder}/flechanegra.gif
  image create photo cabezon -file ${images_folder}/cabezon.gif
  image create photo login -file ${images_folder}/login.gif

  foreach img_name $emotion_files {
    image create photo $img_name -file ${images_folder}/${img_name}.gif
  }

  text .main.text -background white -width 35 -height 30 -wrap none -yscrollcommand ".main.ys set" -cursor left_ptr
  scrollbar .main.ys -command ".main.text yview"

  pack .main.ys -side right -fill y
  pack .main.text -expand true -fill both

  .main.text configure -state disabled

  msn4lin_draw_offline
}

###############################################################################

proc msn4lin_draw_offline {} {
  global version Frases allfonts config

  wm title . "Msn4Lin $version"

  .main.text configure -state normal
  .main.text delete 0.0 end

  .main.text tag conf start_login_gran -underline false -font "$allfonts(3) bold" -fore #000000
  .main.text tag bind start_login_gran <Enter> ".main.text conf -cursor hand2"
  .main.text tag bind start_login_gran <Leave> ".main.text conf -cursor left_ptr"
  .main.text tag bind start_login_gran <Button-1> "login_ok 1"

  .main.text tag conf start_login -underline true -font "$allfonts(2) bold" -fore #000000
  .main.text tag bind start_login <Enter> ".main.text conf -cursor hand2"
  .main.text tag bind start_login <Leave> ".main.text conf -cursor left_ptr"
  .main.text tag bind start_login <Button-1> "login_ok 1"

  .main.text tag conf start_login_dif -underline true -font "$allfonts(2) bold" -fore #000000  -justify center
  .main.text tag bind start_login_dif <Enter> ".main.text conf -cursor hand2"
  .main.text tag bind start_login_dif <Leave> ".main.text conf -cursor left_ptr"
  .main.text tag bind start_login_dif <Button-1> "msn4lin_draw_login"

  .main.text tag conf derecha -justify right

  .main.text insert end "\n\n\n\n\n\n     "
  if {$config(save_password)==1} {
    .main.text insert end "$config(login)" start_login_gran
  }
  .main.text insert end "\n"
  .main.text image create end -image login
  .main.text insert end " "
  if {$config(save_password)==1} {
    .main.text insert end $Frases(1) start_login
  } else {
    .main.text insert end $Frases(1) start_login_dif
  }

  .main.text insert end "\n\n\n\n\n\n\n\n"
  if {$config(save_password)==1} {
    .main.text insert end "$Frases(79)\n" start_login_dif
    .main.text insert end "$Frases(80)" start_login_dif
  } else {
    .main.text insert end "\n"
  }

  .main.text insert end "\n " derecha
  .main.text image create end -image cabezon

  .main.text configure -state disabled

  .main_menu entryconfigure 1 -state disabled
  if {$config(save_password)==1} {
    .main_menu.msn entryconfigure 0 -state normal -label "$Frases(81) $config(login)"
  } else {
    .main_menu.msn entryconfigure 0 -state disabled -label $Frases(81)
  }
  .main_menu.msn entryconfigure 1 -state normal
  .main_menu.msn entryconfigure 2 -state disabled
  .main_menu.msn entryconfigure 3 -state disabled
  .main_menu.msn entryconfigure 5 -state disabled
  .main_menu.msn entryconfigure 7 -state disabled
  .main_menu.msn entryconfigure 9 -state normal
}

###############################################################################

proc msn4lin_draw_signin {} {
  global comprobacion Frases config allfonts

  .main.text configure -state normal
  .main.text delete 0.0 end
  .main.text tag conf signin -font "$allfonts(2) bold" -justify center -fore #000000
  .main.text insert end "\n\n\n\n"
  .main.text insert end "$Frases(28)..." signin
  .main.text insert end "\n"
  .main.text configure -state disabled
  if {($comprobacion==0)&&($config(no_auto_update)==0)} {
    set comprobacion 1
    msn4lin_comprobar 0
  }
}

###############################################################################

proc msn4lin_draw_login {} {
  global config password login_request Frases allfonts

  if {[info exists login_request]} {
    raise .login
    return 0
  }

  set login_request true
  toplevel .login
  bind .login <Destroy> {if {"%W" == ".login"} { unset login_request } }

  wm geometry .login -0+100
  wm title .login $Frases(29)
  wm resizable .login false false
  wm transient .login .
  canvas .login.c -width 410 -height 170
  pack .login.c -expand true -fill both

  entry .login.c.signin -width 22 -bd 1 -font "$allfonts(2)" -bg #FFFFFF
  entry .login.c.password -width 22 -bd 1 -font "$allfonts(2)" -show "*" -bg #FFFFFF
  button .login.c.ok -text $Frases(35) -command "login_ok 0" -font "$allfonts(1)"
  button .login.c.cancel -text $Frases(36) -command "grab release .login;destroy .login" -font "$allfonts(1)"

  checkbutton .login.c.remember -variable config(save_password) -text $Frases(30) -highlightthickness 0 \
     -font "$allfonts(2)" -selectcolor #FFFFFF

  .login.c create text 210 10 -font "$allfonts(4) bold" -anchor ne -text "$Frases(31): "
  .login.c create text 210 80 -font "$allfonts(4) bold" -anchor ne -text "$Frases(32): "
  .login.c create text 210 37 -font "$allfonts(2)" -anchor ne -text "$Frases(33): "
  .login.c create text 210 37 -font "$allfonts(2)" -anchor nw -text "$Frases(59)\n$Frases(60)\n$Frases(61)"
  .login.c create window 210 10 -window .login.c.signin -anchor nw
  .login.c create window 210 80 -window .login.c.password -anchor nw
  .login.c create window 10 110 -window .login.c.remember -anchor nw
  .login.c create window 195 140 -window .login.c.ok -anchor ne
  .login.c create window 205 140 -window .login.c.cancel -anchor nw

  .login.c.signin insert 0 $config(login)
  .login.c.password insert 0 $password

  bind .login.c.password <Return> "login_ok 0"

  tkwait visibility .login
  set x [expr ([winfo vrootwidth .login] - [winfo width .login]) / 2]
  set y [expr ([winfo vrootheight .login] - [winfo height .login]) / 2]
  wm geometry .login +${x}+${y}
  grab set .login
}

###############################################################################

proc msn4lin_comprobar { mostrar } {
  global version Frases allfonts

  catch { [ exec ./comprobar ]}

  set antigua 0
  set encontrado 1

  if {([file readable "msn4lin.ver"] == 0) ||
      ([file isfile "msn4lin.ver"] == 0)} {
    set encontrado 0
  } else {
    set file_id [open "msn4lin.ver" r]
    gets $file_id tmp_data
    if { $tmp_data != $version } {
      set antigua 1
    }
    close $file_id
  }

  if { ($mostrar == 1) || ($antigua == 1) } {
    toplevel .comprobar
    wm geometry .comprobar +100+100
    wm title .comprobar $Frases(5)
    wm resizable .comprobar false false
    wm transient .comprobar .
    canvas .comprobar.c -width 410 -height 140
    pack .comprobar.c -expand true -fill both

    checkbutton .comprobar.c.remember -variable config(no_auto_update) -text $Frases(67) \
      -highlightthickness 0 -font "$allfonts(2)" -selectcolor #FFFFFF
    .comprobar.c create window 205 80 -window .comprobar.c.remember -anchor n

    tkwait visibility .comprobar
    if { $encontrado== 0} {
      .comprobar.c create text 205 10 -font "$allfonts(4) bold" -anchor n -text $Frases(37)
      .comprobar.c create text 205 30 -font "$allfonts(4) bold" -anchor n -text $Frases(38)
      .comprobar.c create text 205 55 -font "$allfonts(4) bold" -anchor n -text $Frases(39)
      button .comprobar.c.cancel -text $Frases(15) -command "save_config;grab release .comprobar;destroy .comprobar" -font "$allfonts(1)"
      .comprobar.c create window 205 105 -window .comprobar.c.cancel -anchor n
    } else {
      if { $antigua == 1 } {
        .comprobar.c create text 205 25 -font "$allfonts(4) bold" -anchor n -text $Frases(41)
        .comprobar.c create text 205 45 -font "$allfonts(4) bold" -anchor n -text $Frases(40)
        button .comprobar.c.ok -text $Frases(35) -command "msn4lin_update" -font "$allfonts(1)"
        button .comprobar.c.cancel -text $Frases(36) -command "save_config;grab release .comprobar;destroy .comprobar" -font "$allfonts(1)"
        .comprobar.c create window 150 105 -window .comprobar.c.ok -anchor n
        .comprobar.c create window 260 105 -window .comprobar.c.cancel -anchor n
      } else {
        .comprobar.c create text 205 35 -font "$allfonts(4) bold" -anchor n -text $Frases(42)
        button .comprobar.c.cancel -text $Frases(15) -command "save_config;grab release .comprobar;destroy .comprobar" -font "$allfonts(1)"
        .comprobar.c create window 205 105 -window .comprobar.c.cancel -anchor n
      }
    }
    set x [expr ([winfo vrootwidth .comprobar] - [winfo width .comprobar]) / 2]
    set y [expr ([winfo vrootheight .comprobar] - [winfo height .comprobar]) / 2]
    wm geometry .comprobar +${x}+${y}
    grab set .comprobar
  }
}

###############################################################################

proc msn4lin_pre_font {} {
  global Frases allfonts

  toplevel .previo

  bind .previo <Destroy> {if {"%W" == ".previo"} { grab release .previo } }

  set tmp_font [.choosefont.c.font get]
  set tmp_size [.choosefont.c.size get]

  wm geometry .previo +0+0
  wm title .previo $Frases(5)
  wm resizable .previo false false
  wm transient .previo .
  canvas .previo.c -width 365 -height 170
  pack .previo.c -expand true -fill both

  tkwait visibility .previo

  .previo.c create text 90 10 -font "$tmp_font $tmp_size" -anchor center -text $Frases(74)
  .previo.c create text 90 30 -font "$tmp_font -$tmp_size" -anchor center -text $Frases(74)
  .previo.c create text 90 50 -font "$tmp_font $tmp_size" -anchor center -text $Frases(74)
  .previo.c create text 90 70 -font "$tmp_font [expr $tmp_size + 1]" -anchor center -text $Frases(74)
  .previo.c create text 90 90 -font "$tmp_font [expr $tmp_size + 2]" -anchor center -text $Frases(74)
  .previo.c create text 90 110 -font "$tmp_font [expr $tmp_size + 3]" -anchor center -text $Frases(74)

  .previo.c create text 275 10 -font "$tmp_font $tmp_size bold" -anchor center -text $Frases(74)
  .previo.c create text 275 30 -font "$tmp_font -$tmp_size bold" -anchor center -text $Frases(74)
  .previo.c create text 275 50 -font "$tmp_font $tmp_size bold" -anchor center -text $Frases(74)
  .previo.c create text 275 70 -font "$tmp_font [expr $tmp_size + 1] bold" -anchor center -text $Frases(74)
  .previo.c create text 275 90 -font "$tmp_font [expr $tmp_size + 2] bold" -anchor center -text $Frases(74)
  .previo.c create text 275 110 -font "$tmp_font [expr $tmp_size + 3] bold" -anchor center -text $Frases(74)

  button .previo.c.ok -text $Frases(15) -command "destroy .previo" -font "$allfonts(1)"
  .previo.c create window 182 135 -window .previo.c.ok -anchor n

  bind .previo <Escape> {
    destroy .previo
  }

  grab set .previo
}

###############################################################################

proc msn4lin_grab_font {} {
  global config
  set config(fontname) [.choosefont.c.font get]
  set config(fontsize) [.choosefont.c.size get]
  save_config
  load_fonts
  msn4lin_reboot
}

###############################################################################

proc msn4lin_choose_font {} {
  global Frases allfonts config choosefont_request

  if {[info exists choosefont_request]} {
    raise .choosefont
    return 0
  }
  set choosefont_request true
  toplevel .choosefont
  bind .choosefont <Destroy> {if {"%W" == ".choosefont"} { unset choosefont_request } }

  wm geometry .choosefont +0+0
  wm title .choosefont $Frases(69)
  wm resizable .choosefont false false
  wm transient .choosefont .
  canvas .choosefont.c -width 410 -height 150
  pack .choosefont.c -expand true -fill both
  tkwait visibility .choosefont

  entry .choosefont.c.font -width 22 -bd 1 -font "Helvetica 12" -bg #FFFFFF
  entry .choosefont.c.size -width 5 -bd 1 -font "Helvetica 12" -bg #FFFFFF
  .choosefont.c create window 190 20 -window .choosefont.c.font -anchor w
  .choosefont.c create window 190 50 -window .choosefont.c.size -anchor w
  .choosefont.c create text 185 20 -font "Helvetica 12" -anchor e -text "$Frases(75): "
  .choosefont.c create text 185 50 -font "Helvetica 12" -anchor e -text "$Frases(76): "
  .choosefont.c create text 205 75 -font "Helvetica 12" -anchor center -text "$Frases(77)"
  .choosefont.c create text 205 95 -font "Tahoma 11" -anchor center -text "$Frases(78)"

  .choosefont.c.font insert 0 $config(fontname)
  .choosefont.c.size insert 0 $config(fontsize)

  button .choosefont.c.ok -text $Frases(35) -command "msn4lin_grab_font;destroy .choosefont" -font "Helvetica 12"
  button .choosefont.c.cancel -text $Frases(36) -command "destroy .choosefont" -font "Helvetica 12"
  button .choosefont.c.visual -text $Frases(73) -command "msn4lin_pre_font" -font "Helvetica 12"
  .choosefont.c create window 140 115 -window .choosefont.c.ok -anchor ne
  .choosefont.c create window 205 115 -window .choosefont.c.cancel -anchor n
  .choosefont.c create window 265 115 -window .choosefont.c.visual -anchor nw

  set x [expr ([winfo vrootwidth .choosefont] - [winfo width .choosefont]) / 2]
  set y [expr ([winfo vrootheight .choosefont] - [winfo height .choosefont]) / 2]
  wm geometry .choosefont +${x}+${y}

  bind .choosefont <Escape> {
    destroy .choosefont
  }

}

###############################################################################

proc msn4lin_update {} {
  catch { [ exec ./actualizar ]}
}

###############################################################################

proc switch_conectados {} {
  global mostrar_conectados
  if {$mostrar_conectados != 0}  {
    set mostrar_conectados 0
  } else {
    set mostrar_conectados 1
  }
  list_users_refresh
}

###############################################################################

proc switch_desconectados {} {
  global mostrar_desconectados
  if {$mostrar_desconectados != 0}  {
    set mostrar_desconectados 0
  } else {
    set mostrar_desconectados 1
  }
  list_users_refresh
}

###############################################################################

proc msn4lin_draw_online {} {
  global user_stat login list_users list_states user_info list_bl mostrar_desconectados mostrar_conectados Frases allfonts

  set my_name [urldecode [lindex $user_info 4]]
  set my_state_no [lsearch $list_states "$user_stat *"]
  set my_state [lindex $list_states $my_state_no]
  set my_state_desc [lindex $my_state 1]
  set my_colour [lindex $my_state 2]
  set my_image_type [lindex $my_state 4]

  .main.text configure -state normal
  .main.text delete 0.0 end

  .main.text tag conf mystatus -fore $my_colour -font "$allfonts(6) bold"
  .main.text tag bind mystatus <Button-1> "tk_popup .my_menu %X %Y"
  .main.text tag bind mystatus <Button-3> "tk_popup .my_menu %X %Y"

  .main.text tag conf online -font "$allfonts(2) bold" -fore #0A246A
  .main.text tag conf offline -font "$allfonts(2) bold" -fore #0A246A
  .main.text tag conf texto -font "$allfonts(2)" -fore #808080

  .main.text insert end "        $Frases(11):\n " texto
  .main.text image create end -image ${my_image_type}h -pady 2
  .main.text image create end -image flechanegra -pady 2
  .main.text insert end "  $my_name " mystatus
  .main.text tag conf estado -font "$allfonts(2)" -fore #000000 
  .main.text insert end "($Frases($my_state_desc))\n" estado

  set conectados 0
  set desconectados 0

  for {set i 0} {$i < [llength $list_users]} {incr i} {
    if {([lindex [lindex $list_users $i] 2] != 7) && ([lindex [lindex $list_users $i] 2] !=8)} {
      incr conectados
    } else {
      incr desconectados
    }
  }

  .main.text tag bind online <Button-1> "switch_conectados"
  .main.text tag bind online <Enter> ".main.text tag conf online -under true;.main.text conf -cursor hand2"
  .main.text tag bind online <Leave> ".main.text tag conf online -under false;.main.text conf -cursor left_ptr"

  if {$mostrar_conectados == 1} {
    .main.text image create end -image flechaar -pady 2 -padx 3
  } else {
    .main.text image create end -image flechaab -pady 2 -padx 3
  }

  if ($conectados>0) {
    .main.text insert end " $Frases(43) ($conectados)\n" online
  } else {
    .main.text insert end " $Frases(43)\n" online
    .main.text insert end "    $Frases(44)\n" texto
  }

  if {$mostrar_desconectados == 1} {
    .main.text image create end -image flechaar -pady 2 -padx 3
  } else {
    .main.text image create end -image flechaab -pady 2 -padx 3
  }


  .main.text tag bind offline <Button-1> "switch_desconectados"
  .main.text tag bind offline <Enter> ".main.text tag conf offline -under true;.main.text conf -cursor hand2"
  .main.text tag bind offline <Leave> ".main.text tag conf offline -under false;.main.text conf -cursor left_ptr"
  .main.text insert end " $Frases(45) ($desconectados)\n" offline

  foreach user $list_users {
    set user_login [lindex $user 0]
    set user_name [lindex $user 1]
    set user_state_no [lindex $user 2]
    set state [lindex $list_states $user_state_no]
    set state_code [lindex $state 0]
    if {(!(($mostrar_desconectados == 0) && ($state_code=="FLN")) && !(($mostrar_conectados == 0) && ($state_code!="FLN")))}  {
      if {($state_code != "NLN") && ($state_code !="FLN")} {
        set state_desc " ($Frases([lindex $state 1]))"
      } else {
        set state_desc ""
      }
      set colour [lindex $state 2]
      set section [lindex $state 3]
      set image_type [lindex $state 4]
      if {[lsearch $list_bl "$user_login *"] != -1} {
        set image_type "blocked"
        if {$state_desc == ""} {
          set state_desc " ($Frases(46))"
        }
      }
      .main.text tag conf $user_login -fore $colour -font "$allfonts(2)"
      .main.text insert $section.last "$user_name$state_desc\n" $user_login
      .main.text image create $section.last -image $image_type -pady 2 -padx 3
      .main.text insert $section.last "  "
      .main.text tag bind $user_login <Enter> ".main.text tag conf $user_login -under true;.main.text conf -cursor hand2"
      .main.text tag bind $user_login <Leave> ".main.text tag conf $user_login -under false;.main.text conf -cursor left_ptr"

      if {$state_code!="FLN"} {
        .main.text tag bind $user_login <Double-Button-1> "msn4lin_chat_user $user_login"
      } else {
        .main.text tag bind $user_login <Double-Button-1> "sendMail $user_login"
      }

      .main.text tag bind $user_login <Button-3> "show_umenu $user_login %X %Y $state_code"
    }
  }
  .main.text configure -state disabled
}

###############################################################################

proc block_user {user_login} {
  write_ns_sock REM "AL ${user_login}"
  write_ns_sock ADD "BL ${user_login} ${user_login}"
}

###############################################################################

proc unblock_user {user_login} {
  write_ns_sock REM "BL ${user_login}"
  write_ns_sock LST "RL"
}

###############################################################################

proc delete_user {user_login} {
  write_ns_sock REM "FL ${user_login}"
  write_ns_sock REM "AL ${user_login}"
}

###############################################################################

proc show_umenu {user_login x y estado} {
  global list_bl Frases allfonts

  set blocked [lsearch $list_bl "${user_login} *"]
  .user_menu delete 0 end

  if {$estado!="FLN"} {
    .user_menu add command -label $Frases(48) -command "msn4lin_chat_user ${user_login}" -font "$allfonts(2) bold"
    .user_menu add command -label "$Frases(49) ($user_login)" -command "sendMail $user_login" -font "$allfonts(2)"
  } else {
    .user_menu add command -label $Frases(48) -command "msn4lin_chat_user ${user_login}" -font "$allfonts(2)" -state disabled
    .user_menu add command -label "$Frases(49) ($user_login)" -command "sendMail $user_login" -font "$allfonts(2) bold"
  }
  .user_menu add separator

  if {$blocked == -1} {
    .user_menu add command -label $Frases(50) -command  "block_user ${user_login}" -font "$allfonts(2)"
  } else {
    .user_menu add command -label $Frases(51) -command  "unblock_user ${user_login}" -font "$allfonts(2)"
  }
  .user_menu add command -label $Frases(52) -command "delete_user ${user_login}" -font "$allfonts(2)"

  tk_popup .user_menu $x $y
}

###############################################################################

proc login_ok {configuracion} {
  global config password

  if {$configuracion==0} {
    set config(login) [.login.c.signin get]
    set password [.login.c.password get]
  }
  grab release .login
  destroy .login
  msn4lin_ns_connect
}

###############################################################################

proc msn4lin_draw_msgwin {} {
   global images_folder sb_num sb_list Frases allfonts

   incr sb_num
   set name "sb$sb_num"
   set win_name "msg_[string tolower ${name}]"

   lappend sb_list "$name"
   sb set $name name $name
   sb set $name sock ""
   sb set $name data [list]
   sb set $name users [list]
   sb set $name typers [list]
   sb set $name title "Instant Message"

   toplevel .${win_name}
   wm title .${win_name} "Instant Message"
   wm group .${win_name} ""

   menu .${win_name}.menu -tearoff 0 -type menubar -background #C0C0C0 \
      -borderwidth 0 -activeborderwidth -0
   .${win_name}.menu add cascade -label MSN4LIN -menu .${win_name}.menu.msn
   .${win_name}.menu add cascade -label Invite -menu .${win_name}.menu.invite \
      -state disabled

   menu .${win_name}.menu.msn -tearoff 0 -type normal -background #C0C0C0
   .${win_name}.menu.msn add command -label "Close this chat" \
      -command "destroy .${win_name}"

   menu .${win_name}.menu.invite -tearoff 0 -type normal -background #C0C0C0
   .${win_name}.menu.invite add separator
   .${win_name}.menu.invite add command -label "$Frases(16)..." -state disabled
#   bind .${win_name}.menu <<MenuSelect>> "msn4lin_msgwin_umenu $name"
   bind .${win_name}.menu <Enter> "msn4lin_msgwin_umenu $name"

   .${win_name} conf -menu .${win_name}.menu

   frame .${win_name}.top
   text .${win_name}.top.text -borderwidth 0 -width 30 -height 1 -wrap word -yscrollcommand ".${win_name}.top.ys set"
   scrollbar .${win_name}.top.ys -command ".${win_name}.top.text yview"
   text .${win_name}.text -background white -width 50 -height 15 -wrap word -yscrollcommand ".${win_name}.ys set"
   scrollbar .${win_name}.ys -command ".${win_name}.text yview"
   text .${win_name}.status -width 30 -height 1 -wrap none
   frame .${win_name}.in
   text .${win_name}.in.input -background white -width 25 -height 3 -wrap word -font "$allfonts(2)"
   button .${win_name}.in.send -text $Frases(56) -width 5 -command "sb_enter $name .${win_name}.in.input" -font "$allfonts(2)"

   pack .${win_name}.top -side top -fill x
   pack .${win_name}.status -side bottom -fill x
   pack .${win_name}.in -side bottom -fill x
   pack .${win_name}.ys -side right -fill y
   pack .${win_name}.text -expand true -fill both

   pack .${win_name}.top.text -side left -expand true -fill x
   pack .${win_name}.in.send -side right -fill y
   pack .${win_name}.in.input -side left -expand true -fill x

   .${win_name}.top.text configure -state disabled
   .${win_name}.text configure -state disabled
   .${win_name}.status configure -state disabled
   .${win_name}.in.send configure -state disabled
   .${win_name}.in.input configure -state disabled

   .${win_name}.text tag configure green -foreground darkgreen -background white
   .${win_name}.text tag configure red -foreground red -background white
   .${win_name}.text tag configure white -foreground white -background black

   bind .${win_name}.in.input <Return> "sb_enter $name %W; break"
   bind .${win_name}.in.input <Alt-s> "sb_enter $name %W; break"
   bind .${win_name}.in.input <Tab> "focus .${win_name}.in.send; break"
   bind .${win_name}.in.send <Return> "sb_enter $name .${win_name}.in.input; break"
   bind .${win_name}.in.input <Control-Return> {%W insert end "\n"; break}
   bind .${win_name} <Destroy> "msn4lin_destroyed_msgwin $name %W"

#   pack .${win_name}.top.ys -side right -fill y
#   pack forget .${win_name}.top.ys

   return ${name}

}

###############################################################################

proc msn4lin_destroyed_msgwin {name winpath} {
   global sb_list ${name}_info config
   set win_name "msg_[string tolower ${name}]"

   if {"${winpath}" != ".${win_name}"} {
      return 0
   }

   set idx [lsearch -exact $sb_list $name]
   if {$idx == -1} {
      status_log "tried to destroy unknown SB $name\n" white
      return 0
   }

   set sb_list [lreplace $sb_list $idx $idx]
   if {[sb get $name stat] != "d"} {
      puts [sb get $name sock] "OUT"
      close [sb get $name sock]
   }
   if {$config(keep_logs) && [sb exists $name log_fcid]} {		;# LOGS!
      close [sb get $name log_fcid]
   }
   unset ${name}_info

}

###############################################################################

proc msn4lin_show_typers {name} {
   global list_users allfonts
   set win_name "msg_[string tolower ${name}]"
   .${win_name}.status configure -state normal
   .${win_name}.status delete 0.0 end

   set num_typers [sb length $name typers]
   if {$num_typers == 0} {
      #TODO last msg received
      set statusmsg ""
   } else {
      if {$num_typers == 1} {
         set is_are "est"
      } else {
         set is_are "estn"
      }
      upvar #0 [sb name $name typers] typers_list
      set statusmsg ""
      foreach login $typers_list {
         set idx [sb search $name users "$login *"]
         set usrinfo [sb index $name users $idx]
         set user_name [lindex $usrinfo 1]
         set statusmsg "${statusmsg}${user_name}, "
      }
      set statusmsg [string replace $statusmsg end-1 end " $is_are escribiendo un mensaje."]
   }

   .${win_name}.status insert end $statusmsg
   .${win_name}.status configure -state disabled -font "$allfonts(1)"
}

###############################################################################

proc msn4lin_msgwin_title {name} {
  global Frases
  upvar #0 [sb name $name users] users_list
  set win_name "msg_[string tolower ${name}]"

  if {[llength $users_list]} {
    set title ""
    set topmsg "$Frases(57):      "
    foreach usrinfo $users_list {
      set user_login [lindex $usrinfo 0]
      set user_name [lindex $usrinfo 1]
      set title "${title}${user_name}, "
      set topmsg "${topmsg}${user_name} <${user_login}>, "
    }
    set title [string replace $title end-1 end ": conversacin"]
    set topmsg [string replace $topmsg end-1 end]
  } else {
    set title $Frases(58)
    set topmsg "No other users are connected to this session!"
  }
  wm title .${win_name} ${title}
  sb set $name title ${title}

  msn4lin_msgwin_top $name $topmsg
}

###############################################################################

proc msn4lin_msgwin_flicker {name count} {
  global Frases
  set win_name "msg_[string tolower ${name}]"

  if { ($count==20) && ([string equal [focus] ".msg_${name}.in.input"] != 1) } {
    playMp3 "type.mp3"
  }

  incr count -1
  catch {
    if {[expr $count % 2]} {
      wm title .${win_name} $Frases(34)
    } else {
      wm title .${win_name} [sb get $name title]
    }
  }

  if {$count > 0} {
    after 500 msn4lin_msgwin_flicker $name $count
  }
}

###############################################################################

proc msn4lin_msgwin_top {name txt} {
  global allfonts
  set win_name "msg_[string tolower ${name}]"

  .${win_name}.top.text configure -state normal -font "$allfonts(2) bold"
  .${win_name}.top.text delete 0.0 end
  .${win_name}.top.text insert end $txt
  .${win_name}.top.text configure -state disabled
}

###############################################################################

proc msn4lin_win_write {name txt {colour ""}} {
  global emotions config allfonts

  set win_name "msg_[string tolower ${name}]"

  .${win_name}.text configure -state normal   -font "$allfonts(2)"

  .${win_name}.text mark set new_text_start end
  .${win_name}.text insert end "$txt" $colour

  if {$config(keep_logs) && [sb exists $name log_fcid]} {	;# LOGS!
    puts -nonewline [sb get $name log_fcid] $txt
  }
  foreach emotion $emotions {
    set symbol [lindex $emotion 0]
    set file [lindex $emotion 1]
    set chars [string length $symbol]
    while {[set pos [.${win_name}.text search -exact -nocase $symbol new_text_start end]] != ""} {
      set posyx [split $pos "."]
      set endpos "[lindex $posyx 0].[expr [lindex $posyx 1] + $chars]"
      .${win_name}.text delete $pos $endpos
      .${win_name}.text image create $pos -image $file -pady 1 -padx 1
    }
  }

  .${win_name}.text yview moveto 1.0
  .${win_name}.text configure -state disabled
}

###############################################################################

proc msn4lin_draw_addcontact {} {
   global addcontact_request Frases allfonts

   if {[info exists addcontact_request]} {
      raise .addcontact
      return 0
   }

   set addcontact_request true
   toplevel .addcontact -width 480 -height 150
   bind .addcontact <Destroy> {
      if {"%W" == ".addcontact"} {
         unset addcontact_request
      }
   }

   wm geometry .addcontact +0+0
   wm title .addcontact $Frases(12)
   wm resizable .addcontact false false
   wm transient .addcontact .
   canvas .addcontact.c -width 480 -height 150
   pack .addcontact.c -expand true -fill both

   entry .addcontact.c.email -width 40 -bd 1 -font "$allfonts(4)" -bg #FFFFFF
   button .addcontact.c.next -text $Frases(35) -command addcontact_next -font "$allfonts(1)"
   button .addcontact.c.cancel -text $Frases(36) -command "grab release .addcontact;destroy .addcontact" -font "$allfonts(1)"

   .addcontact.c create text 15 10 -font "$allfonts(3) bold" -anchor nw -text "$Frases(70)"
   .addcontact.c create text 70 60 -font "$allfonts(2)" -anchor ne -text "$Frases(33): "
   .addcontact.c create text 70 60 -font "$allfonts(2)" -anchor nw -text "$Frases(59)\n$Frases(60)\n$Frases(61)"
   .addcontact.c create window 15 35 -window .addcontact.c.email -anchor nw
   .addcontact.c create window 235 120 -window .addcontact.c.next -anchor ne
   .addcontact.c create window 245 120 -window .addcontact.c.cancel -anchor nw

   bind .addcontact.c.email <Return> "addcontact_next"

  tkwait visibility .addcontact
  set x [expr ([winfo vrootwidth .addcontact] - [winfo width .addcontact]) / 2]
  set y [expr ([winfo vrootheight .addcontact] - [winfo height .addcontact]) / 2]
  wm geometry .addcontact +${x}+${y}
  grab set .addcontact
}

###############################################################################

proc addcontact_next {} {
   set tmp_email [.addcontact.c.email get]
   write_ns_sock "ADD" "FL $tmp_email $tmp_email"
   grab release .addcontact
   destroy .addcontact
}

###############################################################################

proc msn4lin_proxy {} {
  global configuring_proxy config Frases allfonts

  if {[info exists configuring_proxy]} {
    raise .proxy_conf
    return 0
  }

  set configuring_proxy true
  toplevel .proxy_conf -width 400 -height 150
  bind .proxy_conf <Destroy> {
    if {"%W" == ".proxy_conf"} {
      unset configuring_proxy
    }
  }
  wm geometry .proxy_conf +100+100
  wm title .proxy_conf $Frases(14)
  wm resizable .proxy_conf false false
  wm transient .proxy_conf .
  canvas .proxy_conf.c -width 400 -height 140
  pack .proxy_conf.c -expand true -fill both

  entry .proxy_conf.c.server -width 20 -bd 1 -font "$allfonts(2) bold" -bg #FFFFFF
  entry .proxy_conf.c.port -width 5 -bd 1 -font "$allfonts(2) bold" -bg #FFFFFF
  button .proxy_conf.c.ok -text $Frases(35) -command proxy_conf_ok -font "$allfonts(1)"
  button .proxy_conf.c.cancel -text $Frases(36) -command "grab release .proxy_conf;destroy .proxy_conf" -font "$allfonts(1)"

  .proxy_conf.c create text 200 15 -font "$allfonts(6) bold" -anchor center -text "Configure HTTP Proxy support"
  .proxy_conf.c create text 100 35 -font "$allfonts(2)" -anchor ne -text "$Frases(63): "
  .proxy_conf.c create text 100 60 -font "$allfonts(2)" -anchor ne -text "$Frases(64): "
  .proxy_conf.c create text 200 90 -font "$allfonts(2)" -anchor center -text $Frases(71)
  .proxy_conf.c create window 100 35 -window .proxy_conf.c.server -anchor nw
  .proxy_conf.c create window 100 60 -window .proxy_conf.c.port -anchor nw
  .proxy_conf.c create window 195 120 -window .proxy_conf.c.ok -anchor e
  .proxy_conf.c create window 205 120 -window .proxy_conf.c.cancel -anchor w

  set proxy_data [split $config(proxy) ":"]
  .proxy_conf.c.server insert 0 [lindex $proxy_data 0]
  .proxy_conf.c.port insert 0 [lindex $proxy_data 1]

  tkwait visibility .proxy_conf

  set x [expr ([winfo vrootwidth .proxy_conf] - [winfo width .proxy_conf]) / 2]
  set y [expr ([winfo vrootheight .proxy_conf] - [winfo height .proxy_conf]) / 2]
  wm geometry .proxy_conf +${x}+${y}

  grab set .proxy_conf
}

###############################################################################

proc proxy_conf_ok {} {
   global config

   set config(proxy) [join [list [.proxy_conf.c.server get] [.proxy_conf.c.port get]] ":"]
   grab release .proxy_conf
   destroy .proxy_conf
}

###############################################################################

proc newcontact {new_login new_name} {
   global newc_allow_block newc_add_to_list newc_exit list_fl Frases allfonts

   set newc_allow_block "allow"
   set newc_exit ""

   if {[lsearch $list_fl "$new_login *"] != -1} {
      set add_stat "disabled"
      set newc_add_to_list 0
   } else {
      set add_stat "normal"
      set newc_add_to_list 1
   }
   toplevel .newc

   wm geometry .newc -0+100
   wm title .newc "$new_name - Msn4Lin"
   wm transient .newc .
   canvas .newc.c -width 500 -height 150
   pack .newc.c -expand true -fill both

   button .newc.c.ok -text $Frases(35) -command "set newc_exit ok;grab release .newc;destroy .newc"
   button .newc.c.cancel -text $Frases(36) -command "grab release .newc;destroy .newc"

  radiobutton .newc.c.allow -variable newc_allow_block -text "Allow this person to see when you are online and contact you" \
     -highlightthickness 0 -activeforeground #FFFFFF -selectcolor #FFFFFF -value allow -font "$allfonts(2)"
  radiobutton .newc.c.block -variable newc_allow_block \
     -text "Block this person from seeing you are online and contacting you" \
     -highlightthickness 0 -activeforeground #FFFFFF -selectcolor #FFFFFF -value block -font "$allfonts(2)"
   checkbutton .newc.c.add -var newc_add_to_list -state $add_stat -font "$allfonts(2)"\
      -text "Add this person to my contact list" -highlightthickness 0 -activeforeground #FFFFFF -selectcolor #FFFFFF

   .newc.c create text 30 5 -anchor nw -justify left -width 460 -font "$allfonts(2) bold" \
        -text "$new_name ($new_login) has added you to his/her contact list."
   .newc.c create text 30 40 -anchor nw -text "Do you want to:" -font "$allfonts(2)"
   .newc.c create window 40 58 -window .newc.c.allow -anchor nw
   .newc.c create window 40 76 -window .newc.c.block -anchor nw
   .newc.c create window 30 94 -window .newc.c.add -anchor nw
   .newc.c create window 245 120 -window .newc.c.ok -anchor ne
   .newc.c create window 255 120 -window .newc.c.cancel -anchor nw

   tkwait visibility .newc
   grab set .newc
}

###############################################################################

proc msn4lin_draw_notify {} {
   global notify_id allfonts

   toplevel .notify -width 150 -height 100
   wm title .notify "Msn4Lin notify"
   wm overrideredirect .notify 1
   wm geometry .notify -10-60
   wm transient .notify .
   wm state .notify withdrawn

   canvas .notify.c -width 150 -height 100 -relief ridge -borderwidth 2 -bg #FFFFFF
   pack .notify.c

   set notify_id [.notify.c create text 75 50 -font "$allfonts(1)" -justify center]
}

###############################################################################

proc msn4lin_update_notify {} {
   global list_notify notify_id

   set notify_text ""
   set cursec [clock seconds]
   set items [expr [llength $list_notify] -1]
   for {set idx $items} {$idx >= 0} {incr idx -1} {
      set notify_item [lindex $list_notify $idx]
      set msg [lindex $notify_item 0]
      set msgsec [lindex $notify_item 1]
      if {$msgsec < $cursec} {
         set list_notify [lreplace $list_notify $idx $idx]
      } else {
         set notify_text "\n\n$msg${notify_text}"
      }
   }

   set notify_text [string range ${notify_text} 2 end]
   .notify.c dchars $notify_id 0 end
   .notify.c insert $notify_id 0 $notify_text

   if {[string length $notify_text] > 0} {
      wm state .notify normal
   } else {
      wm state .notify withdrawn
   }

   wm geometry .notify -10-60
   raise .notify
   after 1000 msn4lin_update_notify
}

###############################################################################

proc msn4lin_notify_add {msg {sec 10}} {
   global list_notify

   lappend list_notify [list $msg [expr [clock seconds] + $sec]]
}

###############################################################################

proc msn4lin_change_name {} {
  global change_name Frases allfonts

  if {[info exists change_name]} {
    raise .change_name
    return 0
  }

  set change_name true
  toplevel .change_name -width 480 -height 100
  bind .change_name <Destroy> {
    if {"%W" == ".change_name"} {
      unset change_name
    }
  }
  wm geometry .change_name +100+100
  wm title .change_name $Frases(13)
  wm resizable .change_name false false
  canvas .change_name.c -width 480 -height 100
  pack .change_name.c -expand true -fill both
  tkwait visibility .change_name

  entry .change_name.c.name -width 60 -bd 1 -font "$allfonts(2)" -bg #FFFFFF
  button .change_name.c.ok -text $Frases(35) -command change_name_ok -font "$allfonts(1)"
  button .change_name.c.cancel -text $Frases(36) -command "destroy .change_name" -font "$allfonts(1)"

  .change_name.c create text 15 10 -font "$allfonts(1) bold" -anchor nw -text $Frases(72)
  .change_name.c create window 15 35 -window .change_name.c.name -anchor nw
  .change_name.c create window 235 65 -window .change_name.c.ok -anchor ne
  .change_name.c create window 245 65 -window .change_name.c.cancel -anchor nw

  bind .change_name.c.name <Return> "change_name_ok"

  set x [expr ([winfo vrootwidth .change_name] - [winfo width .change_name]) / 2]
  set y [expr ([winfo vrootheight .change_name] - [winfo height .change_name]) / 2]
  wm geometry .change_name +${x}+${y}
  grab set .change_name
}

###############################################################################

proc change_name_ok {} {
   global config

   set new_name [.change_name.c.name get]
   if {$new_name != ""} {
      write_ns_sock "REA" "$config(login) [urlencode $new_name]"
   }
   destroy .change_name
}

###############################################################################

proc msn4lin_msgwin_umenu {name} {
   global list_users
   set win_name "msg_[string tolower ${name}]"

   .${win_name}.menu.invite delete 0 end
   .${win_name}.menu.invite add separator
   .${win_name}.menu.invite add command -label "Other..." -state disabled

   foreach user_info $list_users {
      set user_login [lindex $user_info 0]
      set user_state_no [lindex $user_info 2]
      if {($user_state_no < 7) &&
          ([sb search $name users "$user_login *"] == -1)} {
         set user_name [lindex $user_info 1]
	 .${win_name}.menu.invite insert 0 command \
            -command "msn4lin_invite_user $name $user_login;puts $user_login" \
	    -label "$user_name <$user_login>"
      }
   }
}

###############################################################################

proc msn4lin_logout {} {
   puts -nonewline [sb get ns sock] "OUT\r\n"
   status_log "Logging out!!\n"
}

###############################################################################

proc change_my_status {new_status} {
   write_ns_sock "CHG" $new_status
   status_log "Changing status to $new_status\n" red
}

###############################################################################

proc msn4lin_sb_sessionclosed {sbn} {
   set win_name "msg_[string tolower ${sbn}]"

   status_log "$sbn: SESSION CLOSED\n" red
   sb set $sbn stat "d"
   .${win_name}.menu entryconfigure 1 -state disabled
   set items [expr [sb length $sbn users] -1]
   sb set $sbn last_user [sb index $sbn users 0]
   for {set idx $items} {$idx >= 0} {incr idx -1} {
      set user_info [sb index $sbn users $idx]
      sb ldel $sbn users $idx
      .${win_name}.in.send configure -state disabled
      msn4lin_win_write $sbn "[lindex $user_info 0] cerr la conversacin!\n" green
      msn4lin_msgwin_title $sbn
      bind .${win_name}.in.input <Key> "msn4lin_reconnect ${sbn}"
      bind .${win_name}.in.input <Return> "msn4lin_reconnect ${sbn}; break"
   }
}

###############################################################################

proc read_sb_sock {sbn} {
  set sb_sock [sb get $sbn sock]
  if {[eof $sb_sock]} {
    close $sb_sock
    msn4lin_sb_sessionclosed $sbn
  } else {
    gets $sb_sock tmp_data
    sb append $sbn data $tmp_data
    set log [string map {\r ""} $tmp_data]
    #status_log "$sbn: RECV: $log\n" green
    if {[string range $tmp_data 0 2] == "MSG"} {
      set recv [split $tmp_data]
      fconfigure $sb_sock -blocking 1
      set msg_data [read $sb_sock [lindex $recv 3]]
      fconfigure $sb_sock -blocking 0
      sb append $sbn data $msg_data
    }
  }
}

###############################################################################

proc write_sb_sock {sbn cmd param {handler ""}} {
   global trid
   incr trid

   puts [sb get $sbn sock] "$cmd $trid $param\r"
   status_log "$sbn: SEND: $cmd $trid $param\n" red
   if {$handler != ""} {
      global list_cmdhnd
      lappend list_cmdhnd [list $trid $handler]
   }
}

###############################################################################

proc sb {do sbn var {value ""}} {
   global ${sbn}_info
   set sb_tmp "${sbn}_info(${var})"
   upvar #0 $sb_tmp sb_data

   switch $do {
      name {
	 return $sb_tmp
      }
      set {
         set sb_data $value
	 return 0
      }
      get {
	 return $sb_data
      }
      append {
         lappend sb_data $value
      }
      index {
         return [lindex $sb_data $value]
      }
      ldel {
         set sb_data [lreplace $sb_data $value $value]
      }
      length {
         return [llength $sb_data]
      }
      search {
         return [lsearch $sb_data $value]
      }
      exists {
         return [info exists $sb_tmp]
      }
      unset {
         unset $sb_tmp
      }
   }

}

###############################################################################

proc read_ns_sock {} {
   global ns_data ns_stat

   set ns_sock [sb get ns sock]
   if {[eof $ns_sock]} {
      close $ns_sock
      sb set ns stat "d"
      status_log "Closing NS socket!\n" red
      msn4lin_draw_offline
   } else {
      gets $ns_sock tmp_data
      sb append ns data $tmp_data
      set log [string map {\r ""} $tmp_data]
      status_log "RECV: $log\n" green

      if {[string range $tmp_data 0 2] == "MSG"} {
         set recv [split $tmp_data]
	 fconfigure $ns_sock -blocking 1
	 set msg_data [read $ns_sock [lindex $recv 3]]
	 fconfigure $ns_sock -blocking 0
         sb append ns data $msg_data
      }
   }

}

###############################################################################

proc write_ns_sock {cmd param {handler ""}} {
   global trid
   incr trid

   puts -nonewline [sb get ns sock] "$cmd $trid $param\r\n"
   status_log "SEND: $cmd $trid $param\n" red
   if {$handler != ""} {
      global list_cmdhnd
      lappend list_cmdhnd [list $trid $handler]
   }

}

###############################################################################

proc proc_sb {} {
   global sb_list

   foreach sbn $sb_list {
      while {[sb length $sbn data]} {
         set item [split [sb index $sbn data 0]]

         set result [msn4lin_sb_handler $sbn $item]
         if {$result == 0} {
	    sb ldel $sbn data 0
         } else {
            status_log "problem processing SB data!!\n" red
	    return 0
         } ;# if

      } ;# while
   } ;# foreach

   after 250 proc_sb
}

###############################################################################

proc proc_ns {} {

   while {[sb length ns data]} {

      set item [split [sb index ns data 0]]

      set result [msn4lin_ns_handler $item]
      if {$result == 0} {
	 sb ldel ns data 0
      } else {
         status_log "problem processing NS data!!\n" red
	 return 0
      }

   }

   after 100 proc_ns
}

###############################################################################

proc msn4lin_msg_parse {msg hname bname} {
   upvar $hname headers
   upvar $bname body

   set head_len [string first "\r\n\r\n" $msg]
   set head [string range $msg 0 [expr $head_len - 1]]
   set body [string range $msg [expr $head_len + 4] [string length $msg]]

   set head [string map {"\r" ""} $head]
   set head_lines [split $head "\n"]
   foreach line $head_lines {
      set colpos [string first ":" $line]
      set attribute [string tolower [string range $line 0 [expr $colpos-1]]]
      set value [string range $line [expr $colpos+2] [string length $line]]
      array set headers [list $attribute $value]
   }

}

###############################################################################

proc msn4lin_sb_msg {sb_name recv} {
  global Frases
  set msg [sb index $sb_name data 1]
  sb ldel $sb_name data 1
  array set headers {}
  set body ""
  msn4lin_msg_parse $msg headers body

  set content [lindex [array get headers content-type] 1]

  if {[string range $content 0 9] == "text/plain"} {
    msn4lin_win_write $sb_name " [urldecode [lindex $recv 2]] $Frases(55):\n" red
    msn4lin_win_write $sb_name "   [urldecode $body]\n"
    set idx [sb search $sb_name typers [lindex $recv 1]]
    sb ldel $sb_name typers $idx
    msn4lin_show_typers $sb_name
    msn4lin_msgwin_flicker $sb_name 20
  } elseif {[string range $content 0 19] == "text/x-msmsgscontrol"} {
#    status_log "$msg\n" white
    set typer [array get headers typinguser]
    if {[llength $typer]} {
      set typer [lindex $typer 1]
      set idx [sb search $sb_name typers "$typer"]
      if {$idx == -1} {
        sb append $sb_name typers $typer
      } else {
        sb ldel $sb_name typers $idx
      }
      msn4lin_show_typers $sb_name
    }
  } else {
    status_log "=== UNKNOWN MSG ===\n$msg\n" white
  }
}

###############################################################################

proc msn4lin_update_users {sb_name recv} {
   global config Frases

   switch [lindex $recv 0] {
      BYE { if {[sb get $sb_name stat] != "d"} {
         msn4lin_win_write $sb_name "[lindex $recv 1] $Frases(54)\n" green
	 set leaves [sb search $sb_name users "[lindex $recv 1] *"]
	 sb ldel $sb_name users $leaves
	 sb set $sb_name last_user [lindex $recv 1]
      } }
      IRO {
         sb set $sb_name stat "o"
         set win_name "msg_[string tolower ${sb_name}]"
         .${win_name}.text image create end -image online -pady 1 -padx 1
         set usr_login [lindex $recv 4]
         set usr_name [urldecode [lindex $recv 5]]
         sb append $sb_name users [list $usr_login $usr_name]
         msn4lin_win_write $sb_name " $Frases(53)\n------\n" black
      }
      JOI {
         sb set $sb_name stat "o"

         set win_name "msg_[string tolower ${sb_name}]"
         .${win_name}.text image create end -image online -pady 1 -padx 1

         set usr_login [lindex $recv 1]
         set usr_name [urldecode [lindex $recv 2]]
         sb append $sb_name users [list $usr_login $usr_name]
         msn4lin_win_write $sb_name " $Frases(53)\n------\n" black
      }
   }

   if {[sb exists $sb_name log_fcid]} {
      close [sb get $sb_name log_fcid]
      sb unset $sb_name log_fcid
   }
   if {$config(keep_logs) && [sb length $sb_name users]} {	;# LOGS!
      global log_dir
      upvar #0 [sb name $sb_name users] tmp_users_list
      set users_list [lsort $tmp_users_list]
      set file_name ""
      foreach usrinfo $users_list {
         set user_email [split [lindex $usrinfo 0] "@"]
	 set user_login [lindex $user_email 0]
         set file_name "${file_name}-${user_login}"
      }
      set file_name [string range ${file_name} 1 end]
      sb set $sb_name log_fcid [open "${log_dir}/${file_name}" a+]
   }

   msn4lin_msgwin_title $sb_name
   set win_name "msg_[string tolower ${sb_name}]"
   if {[sb length $sb_name users] > 0} {
      .${win_name}.in.input configure -state normal
      .${win_name}.in.send configure -state normal
      .${win_name}.menu entryconfigure 1 -state normal
      bind .${win_name}.in.input <Key> ""
      bind .${win_name}.in.input <Return> "sb_enter $sb_name %W; break"
   } else {
      if {[sb get $sb_name stat] != "d"} { sb set $sb_name stat "n" }
      .${win_name}.in.send configure -state disabled
      bind .${win_name}.in.input <Key> "msn4lin_reconnect ${sb_name}"
      bind .${win_name}.in.input <Return> "msn4lin_reconnect ${sb_name}; break"
   }
}

###############################################################################

proc msn4lin_sb_handler {sb_name item} {
   global list_cmdhnd

   set ret_trid [lindex $item 1]
   set idx [lsearch $list_cmdhnd "$ret_trid *"]
   if {$idx != -1} {		;# Command has a handler associated!
      eval "[lindex [lindex $list_cmdhnd $idx] 1] \"$item\""
      status_log "evaluating handler for $ret_trid\n"
      return 0
   } else {
   switch [lindex $item 0] {
      MSG {
	 msn4lin_sb_msg $sb_name $item
	 return 0
      }
      BYE -
      JOI -
      IRO {
	 msn4lin_update_users $sb_name $item
	 return 0
      }
      CAL {
	 return 0
      }
      ANS {
         status_log "$sb_name: [join $item]\n" green
	 return 0
      }
      default {
         status_log "$sb_name: UNKNOWN SB input!! --> [join $item]\n" red
	 return 0
      }
   }
   }
}

###############################################################################

proc msn4lin_invite_user {name user} {
   status_log "$name: Inviting  $user\n" green
   write_sb_sock $name "CAL" $user
}

###############################################################################

proc msn4lin_chat_user {user} {
   set name [msn4lin_draw_msgwin]
   sb set $name stat "r"
   sb set $name invite $user

   status_log "$name: CHAT1 Chatting $user\n" green
   write_ns_sock "XFR" "SB" "msn4lin_open_sb $name"
   msn4lin_msgwin_top $name "Requesting a chat session..."
}

###############################################################################

proc msn4lin_rng {recv} {
   global config

   set sbn [msn4lin_draw_msgwin]
   sb set $sbn serv [split [lindex $recv 2] ":"]
   sb set $sbn connected "msn4lin_conn_ans $sbn"
   sb set $sbn readable "read_sb_sock $sbn"
   sb set $sbn auth_cmd "ANS"
   sb set $sbn auth_param "$config(login) [lindex $recv 4] [lindex $recv 1]"

   status_log "$sbn: ANS1 answering [lindex $recv 5]\n" green
   msn4lin_msgwin_top $sbn "Answering chat session from [lindex $recv 5]..."
   msn4lin_socket $sbn
   return 0
}

###############################################################################

proc msn4lin_open_sb {sbn recv} {
   global config

   if {[lindex $recv 4] != "CKI"} {
      status_log "$sbn: Unknown SP requested!\n" red
      return 1
   }
   sb set $sbn serv [split [lindex $recv 3] ":"]
   sb set $sbn connected "msn4lin_conn_sb $sbn"
   sb set $sbn readable "read_sb_sock $sbn"
   sb set $sbn auth_cmd "USR"
   sb set $sbn auth_param "$config(login) [lindex $recv 5]"

   status_log "$sbn: CHAT2: connecting to Switch Board [lindex $recv 3]\n"
   msn4lin_msgwin_top $sbn "Connecting to Switch Board..."
   msn4lin_socket $sbn
}

###############################################################################

proc msn4lin_conn_sb {name} {
   fileevent [sb get $name sock] writable {}
   sb set $name stat "a"
   set cmd [sb get $name auth_cmd]; set param [sb get $name auth_param]
   write_sb_sock $name $cmd $param "msn4lin_connected_sb $name"
   msn4lin_msgwin_top $name "Authenticating..."
}

###############################################################################

proc msn4lin_conn_ans {name} {
   fileevent [sb get $name sock] writable {}
   sb set $name stat "a"
   set cmd [sb get $name auth_cmd]; set param [sb get $name auth_param]
   write_sb_sock $name $cmd $param
   msn4lin_msgwin_top $name "Authenticating..."
}

###############################################################################

proc msn4lin_connected_sb {name recv} {
   sb set $name stat "i"
   if {[sb exists $name invite]} {
      msn4lin_invite_user $name [sb get $name invite]
      msn4lin_msgwin_top $name "Waiting for [sb get $name invite] to join chat..."
   }
}

###############################################################################

proc msn4lin_reconnect {name} {
   if {[sb get $name stat] == "n"} {
      sb set $name stat "i"
      msn4lin_invite_user $name [lindex [sb get $name last_user] 0]
      msn4lin_msgwin_top $name \
         "Waiting for [sb get $name last_user] to rejoin chat..."
   } elseif {[sb get $name stat] == "d"} {
      sb set $name stat "rc"
      sb set $name invite [lindex [sb get $name last_user] 0]
      write_ns_sock "XFR" "SB" "msn4lin_open_sb $name"
      msn4lin_msgwin_top $name "Reconnecting to server..."
   }
}

###############################################################################

proc msn4lin_ns_handler {item} {
   global list_cmdhnd

   set ret_trid [lindex $item 1]
   set idx [lsearch $list_cmdhnd "$ret_trid *"]
   if {$idx != -1} {		;# Command has a handler associated!
      eval "[lindex [lindex $list_cmdhnd $idx] 1] \"$item\""
      status_log "evaluating handler for $ret_trid\n"
      return 0
   } else {
   switch [lindex $item 0] {
      VER -
      INF -
      USR {
	 return [msn4lin_auth $item]
      }
      XFR {
	 if {[lindex $item 2] == "NS"} {
	    set tmp_ns [split [lindex $item 3] ":"]
            sb set ns serv $tmp_ns
            status_log "got a NS transfer!\n"
            status_log "reconnecting to [lindex $tmp_ns 0]\n"
            msn4lin_ns_connect
            return 0
	 } else {
            status_log "got an unknown transfer!!\n" red
            return 0
	 }
      }
      RNG {
         return [msn4lin_rng $item]
      }
      REA {
         global user_info
         set user_info $item
	 msn4lin_draw_online
	 return 0
      }
      ADD -
      LST {
         msn4lin_listupdate $item
         return 0
      }
      REM {
         msn4lin_listdel $item
         return 0
      }
      MSG {
         msn4lin_ns_msg $item
	 return 0
      }
      FLN -
      ILN -
      NLN {
         msn4lin_change_state $item
	 return 0
      }
      CHG {
	 global user_stat
	 set user_stat [lindex $item 2]
	 msn4lin_draw_online
	 return 0
      }
      GTC -
      BLP -
      SYN {
	 return 0
      }
      default {
         status_log "RECV: [join $item]\n" green
         status_log "Got unknown NS input!! --> [lindex $item 0]\n" red
	 return 0
      }
    }
  }
}

###############################################################################

proc msn4lin_change_state {recv} {
  global list_fl list_users Frases

  if {[lindex $recv 0] == "FLN"} {
    set user [lindex $recv 1]
    set user_name ""
    set substate "FLN"
  } else {
    if {[lindex $recv 0] == "ILN"} {
      set user [lindex $recv 3]
      set user_name [urldecode [lindex $recv 4]]
      set substate [lindex $recv 2]
    } else {
      set user [lindex $recv 2]
      set user_name [urldecode [lindex $recv 3]]
      set substate [lindex $recv 1]
    }
  }

  set idx [lsearch $list_users "$user *"]
  if {$idx != -1} {
    global list_users list_states

    set user_data [lindex $list_users $idx]
    if {$user_name == ""} {
       set user_name [urldecode [lindex $user_data 1]]
    }

    if {[lindex $user_data 2] < 7} {
# Tengo que mirarlo, pero si no lo pongo no da fallo, proximamente se corregira bien
      .main_menu.msg delete "[urldecode [lindex $user_data 1]] <$user>"
    } elseif {[lindex $recv 0] == "NLN"} {
# User was offline, now online
      playMp3 "online.mp3"
      msn4lin_notify_add "$user_name\n$Frases(82)"
    }

    if {$substate != "FLN"} {
      .main_menu.msg insert 0 command -label "$user_name <$user>" -command "msn4lin_chat_user $user"
    }

    set state_no [lsearch $list_states "$substate *"]

    set list_users [lreplace $list_users $idx $idx [list $user $user_name $state_no]]
    set list_users [lsort -decreasing -index 2 [lsort -decreasing -index 1 $list_users]]

    msn4lin_draw_online
  } else {
    puts "PANIC!"
  }
}

###############################################################################

proc msn4lin_ns_msg {recv} {
  global Frases
  set msg [sb index ns data 1]
  sb ldel ns data 1
  status_log "[lindex $recv 2] ([lindex $recv 1]) $Frases(55):\n" red
  status_log "$msg\n" red
  status_log "=========================================\n" red
}

###############################################################################

proc list_users_refresh {} {
  global list_fl list_users list_states

  set list_users_new [list]
  set fln [lsearch $list_states "FLN *"]

  foreach user $list_fl {
    set user_login [lindex $user 0]
    set user_name [lindex $user 1]
    set idx [lsearch $list_users "$user_login *"]
    if {$idx != -1} {
      lappend list_users_new [lindex $list_users $idx]
    } else {
      lappend list_users_new [list $user_login $user_name $fln]
    }
  }

  set list_users [lsort -decreasing -index 2 [lsort -decreasing -index 1 $list_users_new]]
  msn4lin_draw_online
}

###############################################################################

proc lists_compare {} {
  global list_fl list_al list_bl list_rl
  global newc_allow_block newc_add_to_list newc_exit
  set list_albl [lsort [concat $list_al $list_bl]]
  set list_rl [lsort $list_rl]

  foreach x $list_rl {
    if {[lsearch $list_albl "[lindex $x 0] *"] == -1} {
      status_log "$x in your RL list but not in your AL/BL list!\n" white
      newcontact [lindex $x 0] [lindex $x 1]
      tkwait window .newc
      if {$newc_exit == "ok"} {
        if {$newc_allow_block == "allow"} {
          write_ns_sock "ADD" "AL [lindex $x 0] [urlencode [lindex $x 1]]"
        } else {
          write_ns_sock "ADD" "BL [lindex $x 0] [urlencode [lindex $x 1]]"
        }
        if {$newc_add_to_list} {
          write_ns_sock "ADD" "FL [lindex $x 0] [urlencode [lindex $x 1]]"
        }
      } ;# if clicked on OK!
    } ;# NOT in AL/BL
  }
}

###############################################################################

proc msn4lin_listupdate {recv} {
   global list_fl list_al list_bl list_rl

   set list_name "list_[string tolower [lindex $recv 2]]"

   if {([lindex $recv 4] <= 1) && ([lindex $recv 0] == "LST")} {
      set $list_name [list]
      status_log "clearing $list_name\n"
   }

   if {[lindex $recv 0] == "ADD"} {		;# FIX: guess I should really
      set recv [linsert $recv 4 "1" "1"]	;# get it out of here!!
   }

   if {[lindex $recv 4] != 0} {
      set contact_info ""
      set user [lindex $recv 6]
      lappend contact_info $user
      lappend contact_info [urldecode [lindex $recv 7]]
      lappend $list_name $contact_info
   }

   if {[lindex $recv 4] == [lindex $recv 5]} {
      lists_compare		;# FIX: hmm, maybe I should not run it always!
      list_users_refresh
   }
}

###############################################################################

proc show_list {list_name} {
   upvar #0 $list_name the_list

   status_log "$list_name\n" red
   foreach x $the_list {
      status_log "$x\n"
   }
}

###############################################################################

proc msn4lin_listdel {recv} {
   write_ns_sock "LST" "[lindex $recv 2]"
}

###############################################################################

proc msn4lin_auth {{recv ""}} {
   switch [sb get ns stat] {
      c {
         write_ns_sock "VER" "MSNP2"
	 sb set ns stat "v"
	 return 0
      }
      v {
         if {[lindex $recv 0] != "VER"} {
	    status_log "was expecting VER reply but got a [lindex $recv 0]\n" red
	    return 1
	 } elseif {[lsearch -exact $recv "MSNP2"] != -1} {
            write_ns_sock "INF" ""
	    sb set ns stat "i"
	    return 0
	 } else {
	    status_log "could not negotiate protocol!\n" red
	    return 1
	 }
      }
      i {
         if {[lindex $recv 0] != "INF"} {
	    status_log "was expecting INF reply but got a [lindex $recv 0]\n" red
            return 1
         } elseif {[lsearch -exact $recv "MD5"] != -1} {
            global config
            write_ns_sock "USR" "MD5 I $config(login)"
            sb set ns stat "u"
            return 0
         } else {
            status_log "could not negotiate authentication method!\n" red
            return 1
         }
      }
      u {
         if {([lindex $recv 0] != "USR") || \
            ([lindex $recv 2] != "MD5") || \
            ([lindex $recv 3] != "S")} {
            status_log "was expecting USR x MD5 S xxxxx but got something else!\n" red
            return 1
         }
         write_ns_sock "USR" "MD5 S [get_password 'MD5' [lindex $recv 4]]"
         sb set ns stat "us"
         return 0
      }
      us {
         if {[lindex $recv 0] != "USR"} {
            status_log "was expecting USR reply but got a [lindex $recv 0]\n" red
            return 1
         }
         if {[lindex $recv 2] != "OK"} {
            status_log "error authenticating with server!\n" red
            return 1
         }
         global user_info
         set user_info $recv
         sb set ns stat "a"
	 save_config						;# CONFIG
	 write_ns_sock "SYN" "0"
	 write_ns_sock "CHG" "NLN"
         .main_menu entryconfigure 1 -state normal
         .main_menu.msn entryconfigure 2 -state normal
         .main_menu.msn entryconfigure 3 -state normal
         .main_menu.msn entryconfigure 5 -state normal
         .main_menu.msn entryconfigure 7 -state normal
	 return 0
      }
   }

}

###############################################################################

proc sb_enter { sbn name } {
   global trid user_info Frases

   set content [lindex [array get headers content-type] 1]
   set txt [$name get 0.0 end-1c]
   if {[string length $txt] < 1} { return 0 }
   set sock [sb get $sbn sock]
   if {[string index $txt 0] == "/"} {
      set cmd [string range $txt 1 [string length $txt]]
      puts $sock $cmd
   } elseif {[sb length $sbn users]} {
      set txt_send [string map {"\n" "\r\n"} $txt]
      set msg "MIME-Version: 1.0\r\nContent-Type: text/plain\r\n\r\n"
      set msg "$msg$txt_send"
      set msg_len [string length $msg]
      incr trid
      puts $sock "MSG $trid U $msg_len"
      puts -nonewline $sock $msg
      msn4lin_win_write $sbn " [urldecode [lindex $user_info 4]] $Frases(55):\n" green
      msn4lin_win_write $sbn "   [urldecode $txt]\n"
   } else {
      status_log "$sbn: trying to send, but no users connected to same SB session\n" white
      return 0
   }
   $name delete 0.0 end
   focus ${name}
}

###############################################################################

proc ns_enter {} {
   puts -nonewline [sb get ns sock] "[.status.enter get]\r\n"
   status_log "SEND: [.status.enter get]\n" red
   .status.enter delete 0 end
}

###############################################################################

proc msn4lin_socket {name} {
   global config

   if {$config(proxy) != ""} {
      set proxy_serv [split $config(proxy) ":"]
      set tmp_serv [lindex $proxy_serv 0]
      set tmp_port [lindex $proxy_serv 1]
      set next "msn4lin_proxy_connect $name"
      set readable_handler "msn4lin_proxy_read $name"
      sb set $name stat "pw"
   } else {
      set tmp_serv [lindex [sb get $name serv] 0]
      set tmp_port [lindex [sb get $name serv] 1]
      set readable_handler [sb get $name readable]
      set next [sb get $name connected]
      sb set $name stat "cw"
   }

   set sock [socket -async $tmp_serv $tmp_port]
   sb set $name sock $sock
   fconfigure $sock -buffering none -translation {binary binary} -blocking 0
   fileevent $sock readable $readable_handler
   fileevent $sock writable $next
}

###############################################################################

proc msn4lin_proxy_read {name} {
  global proxy_header

  set sock [sb get $name sock]
  if {[eof $sock]} {
    close $sock
    sb set $name stat "d"
    status_log "PROXY: $name CLOSED\n" red
  } else {
    if {[gets $sock tmp_data] != -1} {
      global proxy_header
      set tmp_data [string map {\r ""} $tmp_data]
      lappend proxy_header $tmp_data
      status_log "PROXY RECV: $tmp_data\n"
      if {$tmp_data == ""} {
        set proxy_status [split [lindex $proxy_header 0]]
        if {[lindex $proxy_status 1] != "200"} {
          close $sock
          sb set $name stat "d"
          status_log "PROXY CLOSED: [lindex $proxy_header 0]\n"
          if {$name == "ns"} msn4lin_draw_offline ;# maybe should be passed
          return 1
        }
        status_log "PROXY ESTABLISHED: running [sb get $name connected]\n"
        fileevent [sb get $name sock] readable [sb get $name readable]
        eval [sb get $name connected]
      }
    }
  }
}

###############################################################################

proc msn4lin_proxy_connect {name} {
  fileevent [sb get $name sock] writable {}
  sb set $name stat "pc"
  set tmp_data "CONNECT [join [sb get $name serv] ":"] HTTP/1.0"
  status_log "PROXY SEND: $tmp_data\n"
  puts -nonewline [sb get $name sock] "$tmp_data\r\n\r\n"
}

###############################################################################

proc msn4lin_ns_connected {} {
  fileevent [sb get ns sock] writable {}
  sb set ns stat "c"
  msn4lin_auth
}

###############################################################################

proc msn4lin_sb_connected {name} {
  global Frases
  fileevent [sb get $name sock] writable {}
  sb set $name stat "c"
  write_sb_sock $name [sb get $name auth_cmd] [sb get $name auth_param]
  msn4lin_msgwin_top $name "$Frases(62)..."
}

###############################################################################

proc msn4lin_ns_connect {} {
  global config version

  if {[sb get ns stat] != "d"} {
    fileevent [sb get ns sock] readable {}
    close [sb get ns sock]
  }

  .main_menu.msn entryconfigure 0 -state disabled
  .main_menu.msn entryconfigure 1 -state disabled
  .main_menu.msn entryconfigure 9 -state disabled

  wm title . "Msn4Lin $version"
  msn4lin_draw_signin

  sb set ns data [list]
  sb set ns connected "msn4lin_ns_connected"
  sb set ns readable "read_ns_sock"

  msn4lin_socket ns
}

###############################################################################

proc get_password {method data} {
  global password

  set pass [::md5::md5 $data$password]
  return $pass
}

###############################################################################

proc urldecode {str} {
#  By BorSanZa

#  puts $str
#  for {set x 0} {$x<[string length $str]} {incr x} {
#    puts "[scan [string index $str $x] %c] [string index $str $x]"
#  }

  for {set x 0} {$x<[string length $str]} {incr x} {
    switch [scan [string index $str $x] %c] {
      10 {
        # le aado al 10 espacios despues para que quede bonito
        set str [string replace $str $x $x "[format %c 10]   "]
        set x [expr $x + 3]
      }
      13 {
        # quito el 13 del enter pq en las kde parece que no le gusta
        set str [string replace $str $x $x " "]
      }
      # $
      36 {
        set str [string replace $str $x $x "[format %c 92][format %c 36]"]
        incr x
      }
      # %
      37 {
        set hexa 0
        set cont 0
        while {([expr $x + 1] < [string length $str]) && 
          (([scan [string index $str [expr $x + 1]] %c] > 47 )&&([scan [string index $str [expr $x + 1]] %c] < 58 ) || 
           ([scan [string index $str [expr $x + 1]] %c] > 64 )&&([scan [string index $str [expr $x + 1]] %c] < 71 ) ||
           ([scan [string index $str [expr $x + 1]] %c] > 96 )&&([scan [string index $str [expr $x + 1]] %c] < 103))&&($cont<2)} {
          incr cont
          set str [string replace $str $x $x]
          set hexa [expr $hexa * 16]
          set a [scan [string index $str $x] %c]
          if {$a>96} {
            set a [expr $a - 39]
          } else {
            if {$a>64} {
              set a [expr $a - 7]
            }
          }
          set a [expr $a - 48]
          set hexa [expr $hexa + $a]
        }
        if {$cont==0} {
          set str [string replace $str $x $x "[format %c 37]"]
        } else {
          set str [string replace $str $x $x [format %c $hexa]]
        }
      }
      # +
      43 {
        set str [string replace $str $x $x "[format %c 43]"]
      }
      # [
      91 {
        set str [string replace $str $x $x "[format %c 92][format %c 91]"]
        incr x
      }
      # /
      92 {
        set str [string replace $str $x $x "[format %c 92][format %c 92]"]
        incr x
      }
      # ]
      93 {
        set str [string replace $str $x $x "[format %c 92][format %c 93]"]
        incr x
      }
      194 {
        set str [string replace $str $x $x]
      }
      195 {
        set str [string replace $str $x [expr $x + 1] [format %c [expr 64 + [scan [string index $str [expr $x + 1]] %c]]]]
      }
      203 {
        set str [string replace $str $x [expr $x + 1] [format %c [expr 19 + [scan [string index $str [expr $x + 1]] %c]]]]
      }
      # Simbolo del euro
      226 {
        if {([scan [string index $str [expr $x + 1]] %c]==130)&&([scan [string index $str [expr $x + 2]] %c]==172)} {
          set str [string replace $str $x [expr $x + 2] "E"]
        }
      }
    }
  }

#  for {set x 0} {$x<[string length $str]} {incr x} {
#    puts "[scan [string index $str $x] %c] [string index $str $x]"
#  }

  return [subst $str]
}

###############################################################################

proc urlencode {str} {
   global url_map
   regsub -all \[)\] $str  str
   regsub -all \[^a-zA-Z0-9\] $str {$url_map(&)} str
   regsub -all  $str {\)} str
   return [subst -nobackslashes -nocommands $str]
}

###############################################################################

proc load_fonts {} {
  global allfonts config

  set allfonts(1) "$config(fontname) $config(fontsize)"
  set allfonts(2) "$config(fontname) -$config(fontsize)"
  set allfonts(3) "$config(fontname) [expr $config(fontsize) + 1]"
  set allfonts(4) "$config(fontname) [expr $config(fontsize) + 2]"
  set allfonts(5) "$config(fontname) [expr $config(fontsize) + 3]"
  set allfonts(6) "$config(fontname) [expr $config(fontsize) + 4]"
}

###############################################################################

proc playMp3 {archivo} {
  global sounds_folder

  if { [catch { exec mpg321 ${sounds_folder}/$archivo -q & } ] == 1 } {
    catch { exec mpg123 ${sounds_folder}/$archivo -q & }
  }
}

###############################################################################

proc sendMail {persona {asunto ""}} {
  catch { exec kmail $persona -s $asunto & }
}

###############################################################################

proc openNavigator {page} {
  catch { exec konqueror $page &}
}

###############################################################################
###############################################################################
###############################################################################

create_dir $HOME
create_dir $log_dir
sb set ns name ns
sb set ns sock ""
sb set ns data [list]
sb set ns serv [split $config(start_ns_server) ":"]
sb set ns stat "d"

load_config
load_lang_disponibles
load_lang
load_fonts

msn4lin_draw_main
msn4lin_draw_notify

after 500 proc_ns
after 750 proc_sb

after 1000 msn4lin_update_notify

if {$version != $config(last_client_version)} {
  msn4lin_draw_about2
}
save_config
