package require msgcat

namespace eval openurl {

    ::msgcat::mcload [file join [file dirname [info script]] msgs]

    set options(browsers) [list \
	firefox "Firefox" \
	galeon "Galeon" \
	konqueror "Konqueror" \
	mozilla-firefox "Mozilla Firefox" \
	mozilla-firebird "Mozilla Firebird" \
	mozilla "Mozilla" \
	netscape "Netscape" \
	iexplorer "Internet Explorer" \
	opera "Opera" \
	lynx "Lynx" \
	links "Links" \
	elinks "Elinks"]
}

proc openurl::open_url {brname brpath command} {
    set url [::plugins::urls::encode_url [eval $command]]

    switch -- $brname {
	firefox -
	mozilla-firefox -
	mozilla-firebird -
	mozilla -
	netscape {
	    if {[catch {eval exec $brpath -remote \"openURL($url, new-tab)\"}]} {
		exec $brpath $url &
	    }
	}
	galeon {
	    exec $brpath --new-tab $url &
	}
	opera {
		exec $brpath -newpage $url &
	}
	links -
	elinks -
	lynx {
	    exec xterm -e $brpath $url &
	}
	default {
	    exec $brpath $url &
	}
    }
}

proc openurl::add_chat_win_popup_menu {m chatwin X Y x y} {
    variable options

    set tags [$chatwin tag names "@$x,$y"]
    set idx1 [lsearch $tags url]
    set idx2 [lsearch $tags xep]
    switch -glob -- [expr {$idx1 >= 0}]/[expr {$idx2 >= 0}] {
	0/0 {
	    return
	}
	1/* {
	    set command [list ::plugins::urls::get_url $chatwin $x $y]
	}
	default {
	    set command [list ::plugins::xeps::get_xep $chatwin $x $y]
	}
    }
    set mb [menu $m.openurl -tearoff 0]
    foreach {brname brdesc} $options(browsers) {
	if {[llength [set e [auto_execok $brname]]] > 0} {
	    $mb add command \
	    	-label $brdesc \
		-command [list [namespace current]::open_url \
			       $brname [lindex $e 0] $command]
	}
    }
    $m add cascade -label [::msgcat::mc "Open URL with"] -menu $mb
}

hook::add chat_win_popup_menu_hook \
    [namespace current]::openurl::add_chat_win_popup_menu 5
