<?php if (!defined('PmWiki')) exit();

//
// Copyright (C) Julian I. Kamil <julian.kamil@gmail.com>
// No warranty is provided.  Use at your own risk.
//
// Author: Julian I. Kamil <julian.kamil@gmail.com>
// Created: 2005/07/16
// Description:
//     This is a PmWiki plugin that adds a markup
//     to define multilinks.  A multilink is a link
//     with multiple destinations that is rendered
//     as a popup menu.
//
// History:
//     2004/07/16  jik  Created.
//     2004/07/17  jik  Added code to degrade gracefully
//                      in non Firefox browsers.
//                 jik  Added Google and Wikipedia links
//                      in the multilink edit page.
//                 jik  Added a default for empty n.
//     2004/07/18  jik  Fixed the URL generation for
//                      relative (Wiki) addresses.
//     2004/07/21  jik  Replaced the UA string with Gecko
//                      but excluded Safari.
//
// Initials:
//     jik  Julian I. Kamil <julian.kamil@gmail.com>
//

SDV($HandleActions['mlinkedit'],'HandleMLinkEdit');
SDV($ActionTitleFmt['mlinkedit'],'| $[Edit multilink]');

$HTMLStylesFmt['mlink'] = <<< EOT

.multilink { margin-left: 2px; padding-right: 4px; margin-right: 2px; }
.multilink ul { padding: 0px; margin: 0px; display: inline; position: relative; border: 1px solid #ccc; }
.multilink ul li { list-style: none; display: inline; padding: 0px; margin: 0px; padding-left: 4px;}
.multilink ul li:hover ul { display: block; background: #444; }
.multilink ul li:hover { color: black; background: #ddd; }
.multilink ul li ul { display: none; position: absolute; padding: 0px 0px 4px 0px; left: -2px; top: -2px; z-index: 9;}
.multilink ul li ul li { display: block; padding: 0px 8px 0px 8px;}
.multilink ul li ul li:hover { color: white; background: #444; }

.p0 { color: #eee; text-decoration: underline; }
.p0 a, .p0 a:visited, .p0 a:hover { color: #eee; text-decoration: none; }
.p1, .p1 a, .p1 a:visited { color: #ccc; }
.p2, .p2 a, .p2 a:visited { color: #aaa; }
.p3, .p3 a, .p3 a:visited { color: #888; }
.p4, .p4 a, .p4 a:visited { color: #777; }
.p5, .p5 a, .p5 a:visited { color: #666; }
.p6, .p6 a, .p6 a:visited { color: #555; }

.p1 a:hover,
.p2 a:hover,
.p3 a:hover,
.p4 a:hover,
.p5 a:hover,
.p6 a:hover
{ color: white; text-decoration: none; }

.pseudo_multilink { border: 1px solid #ccc; padding: 1px 2px 1px 2px;}
.extra_link, .extra_link a { font-size: 8pt; }

.multilink_field_title { font-size: 8pt; color: #888; }
.odd_row { background-color: #edf3fe; }

EOT;

function MLink($title) {
    global $MlinkShade, $MlinkGoogle, $MlinkWikipedia;
    global $Group, $Name;

    $o_title = $title;

    $title = str_replace(".", " ", $title);
    $t = MakePageName("mlink", $title);
    $t = str_replace("mlink.", "", $t);

    if (empty($_REQUEST['n'])) {
	$n = "Main.HomePage";
    }
    else {
	$n = $_REQUEST['n'];
    }

    $mlink =  "{$n}.{$t}.mlink";
    $mlink_edit = "<a href=\"{$_SERVER['PHP_SELF']}?mlink={$mlink}&action=mlinkedit\">edit</a>";
    $mlink_title_edit = "<a href=\"{$_SERVER['PHP_SELF']}?mlink={$mlink}&action=mlinkedit\">{$title}</a>";

    if (!empty($MlinkGoogle)) {
        $google_link = "[<a href=\"{$MlinkGoogle}{$title}\">Google</a>]";
    }

    if (!empty($MlinkWikipedia)) {
        $wikipedia_link ="[<a href=\"{$MlinkWikipedia}{$title}\">Wikipedia</a>]";
    }

    if (eregi("Gecko", $_SERVER['HTTP_USER_AGENT'])) {
	$in_fx = TRUE;
    }

    if (eregi("Safari", $_SERVER['HTTP_USER_AGENT'])) {
	$in_fx = FALSE;
    }

    if ($in_fx) {
	$output .= <<< EOT

<span class="multilink">
    <ul>
        <li>{$title}
            <ul>
                <li class="p0">{$title} ({$mlink_edit} {$google_link} {$wikipedia_link})</li>
EOT;

	if (PageExists($mlink)) {
	    $page = ReadPage($mlink);
	    ksort($page);
        
	    $real_index = 0;

	    foreach ($page as $index => $line) {
		if (is_int($index)) {
		    $by_bar = explode("|", $line);

		    if ($MlinkShade) {
			$real_index = ($real_index < 6) ? ($real_index + 1) : 6;
		    }
		    else {
			$real_index = 1;
		    }

		    if (! empty($by_bar[2])) {
			$destination_name = $by_bar[2];
			$tooltips_code = "title=\"$by_bar[1]\"";
		    }
		    else {
			$destination_name = $by_bar[1];
			$tooltips_code = "";
		    }

                    if ($by_bar[0] === 'a') {
                        $output .= "<li class=\"p{$real_index}\"><a href=\"{$by_bar[1]}\" {$tooltips_code}>{$destination_name}</a></li>";
                    }
                    else if ($by_bar[0] === 'r') {
                        $link = MakeLink("{$Group}.{$Name}", $by_bar[1]);
                        $output .= "<li class=\"p{$real_index}\">{$link}</li>";
                    }
                    else {
                        $output .= "<li class=\"p{$real_index}\">{$destination_name}</li>";
                    }
		}
	    }
	}

	$output .= <<< EOT

            </ul>
        </li>
    </ul>
</span>
EOT;
    }
    else {
	if (PageExists($mlink)) {
	    $page = ReadPage($mlink);
	    ksort($page);

	    foreach ($page as $index => $line) {
		if (is_int($index)) {
		    $by_bar = explode("|", $line);
		    $tooltip .= "{$index}:{$by_bar[1]}\r";
		}
	    }
	}

	$tooltip .= "IN Firefox THIS IS A FULL-FEATURED MULTILINK\rSWITCH TO Firefox NOW";

	return "<span class=\"pseudo_multilink\" title=\"{$tooltip}\">{$mlink_title_edit}</span>";
    }

    return $output;
}

function HandleMLinkEdit($pagename) {
    global $MlinkShade, $MlinkGoogle, $MlinkWikipedia;

    $mlink = $_GET['mlink'];
    $self_link = "{$_SERVER['PHP_SELF']}?mlink={$mlink}&action=mlinkedit";
    $by_dot = explode(".", $mlink);
    $new_pagename = "MultilinkEdit." . "{$by_dot[2]}Of{$by_dot[0]}{$by_dot[1]}";

    if (!empty($MlinkGoogle)) {
        $google_link = "<a href=\"{$MlinkGoogle}{$by_dot[2]}\">Google</a>";
	$extra_links = "&nbsp; [<span class=\"extra_link\">{$google_link}</span>]";
    }

    if (!empty($MlinkWikipedia)) {
        $wikipedia_link ="<a href=\"{$MlinkWikipedia}{$by_dot[2]}\">Wikipedia</a>";
	$extra_links .= "&nbsp; [<span class=\"extra_link\">{$wikipedia_link}</span>]";
    }

    $action_do = empty($_GET['do']) ? $_POST['do'] : $_GET['do'];

    if ($action_do === "submit") {
        foreach ($_POST as $index => $value) {
            if (preg_match('/^i\\d+$/', $index, $matches)) {
                $numeric_index = $_POST[$index];
                $t_value = $_POST["t{$numeric_index}"];
                $d_value = $_POST["d{$numeric_index}"];
                $s_value = $_POST["s{$numeric_index}"];

                if (! empty($d_value)) {
                    if (empty($t_value)) {
                        $t_value = 'a';
                    }

		    if (!empty($s_value)) {
			$page[$numeric_index] = "{$t_value}|{$d_value}|{$s_value}";
		    }
		    else {
			$page[$numeric_index] = "{$t_value}|{$d_value}";
		    }
                }
            }
        }

        WritePage($mlink, $page);
        header('Location: ' . $self_link);

        return;
    }
    else if ($action_do === "delete") {
        $deleted_index = $_GET['index'];
        $page = ReadPage($mlink);
        unset($page[$deleted_index]);
        WritePage($mlink, $page);
        header('Location: ' . $self_link);
        return;
    }
    else if ($action_do === "moveup") {
        $moved_index = $_GET['index'];

        if ($moved_index == 1) {
            header('Location: ' . $self_link);
            return;
        }

        $displaced_index = $moved_index - 1;
        $page = ReadPage($mlink);
        $moved = $page[$moved_index];
        $displaced = $page[$displaced_index];
        $page[$displaced_index] = $moved;

        if (!empty($displaced)) {
            $page[$moved_index] = $displaced;
        }
        else {
            unset($page[$moved_index]);
        }

        WritePage($mlink, $page);
        header('Location: ' . $self_link);
        return;
    }
    else if ($action_do === "movedown") {
        $moved_index = $_GET['index'];
        $displaced_index = $moved_index + 1;
        $page = ReadPage($mlink);
        $moved = $page[$moved_index];
        $displaced = $page[$displaced_index];
        $page[$displaced_index] = $moved;

        if (!empty($displaced)) {
            $page[$moved_index] = $displaced;
        }
        else {
            unset($page[$moved_index]);
        }

        WritePage($mlink, $page);
        header('Location: ' . $self_link);
        return;
    }

    $output .= <<< EOT
<script language="JavaScript" type="text/javascript">
    <!--
    function saveChanges() {
        document.mlink_edit_form.submit();
    }
    -->
</script>
EOT;

    $output .= "
<h1 align=\"center\">Multilink Targets</h1>
<form name=\"mlink_edit_form\" action=\"{$self_link}&do=submit\" method=\"post\" >
<table align=\"center\">
<tr>
<td colspan=\"6\" align=\"center\">
<a href=\"javascript:history.go(-1)\" class=\"extra_link\">{$by_dot[0]} &raquo; {$by_dot[1]}</a> &raquo; <strong>{$by_dot[2]}</strong>
{$extra_links}
</td>
</tr>";

    $new_index = 1;
    $odd_row = TRUE;

    $row_class = array(
	TRUE => "odd_row",
	FALSE => "even_row"
	);

    if (PageExists($mlink)) {
        $page = ReadPage($mlink);
        ksort($page);

        foreach ($page as $index => $line) {
            if (is_int($index)) {
                $by_bar = explode("|", $line);
                $ac = $rc = "";
		$this_row_class = $row_class[$odd_row];
		$odd_row = (!$odd_row);

                if ($by_bar[0] === "r") {
                    $link = "{$_SERVER['PHP_SELF']}?n=$by_bar[1]";
                    $rc = "checked";
                }
                else {
                    $link = $by_bar[1];
                    $ac = "checked";
                }

                $output .= "
<tr valign=\"top\" class=\"{$this_row_class}\">
<td><a href=\"{$self_link}&do=moveup&index={$index}\">&uarr;</a></td>
<td><a href=\"{$self_link}&do=movedown&index={$index}\">&darr;</a></td>
<td align=\"right\">
<input type=\"hidden\" name=\"i{$index}\" value=\"{$index}\" />{$index}
</td>
<td>
<input type=\"radio\" name=\"t{$index}\" {$ac} value=\"a\" />a
<input type=\"radio\" name=\"t{$index}\" {$rc} value=\"r\" />r
</td>
<td>
<a href=\"{$link}\">{$by_bar[1]}</a><br />
<span class=\"multilink_field_title\">Target destination address:</span><br />
<input type=\"text\" name=\"d{$index}\" value=\"{$by_bar[1]}\" size=\"80\" /><br />
<span class=\"multilink_field_title\">Target description:</span><br />
<input type=\"text\" name=\"s{$index}\" value=\"{$by_bar[2]}\" size=\"80\" />
</td>
<td><a href=\"{$self_link}&do=delete&index={$index}\">X</a></td>
</tr>";
            
                if ($index >= $new_index) {
                    $new_index = $index + 1;
                }
            }
        }
    }

    $this_row_class = $row_class[$odd_row];

    $output .= "
<input type=\"hidden\" name=\"i{$new_index}\" value=\"{$new_index}\" />
<tr valign=\"top\" class=\"{$this_row_class}\">
<td>&uarr;</td>
<td>&darr;</td>
<td align=\"right\">{$new_index}</td>
<td>
<input type=\"radio\" name=\"t{$new_index}\" value=\"a\" />a
<input type=\"radio\" name=\"t{$new_index}\" value=\"r\" />r
</td>
<td>
New target<br />
<span class=\"multilink_field_title\">New target destination address:</span><br />
<input type=\"text\" name=\"d{$new_index}\" value=\"\" size=\"80\" /><br />
<span class=\"multilink_field_title\">New target description:</span><br />
<input type=\"text\" name=\"s{$new_index}\" value=\"\" size=\"80\" />
</td>
<td>X</td>
</tr>
<tr>
<td colspan=\"6\" align=\"center\"><a href=\"javascript:saveChanges()\">Save Changes</a></td>
</tr>
</table>
</form>";

    global 
        $DefaultPageTextFmt, $FmtV, $HandleBrowseFmt,
        $PageStartFmt, $PageEndFmt, $PageRedirectFmt;

    $FmtV['$PageText'] = 
        MarkupToHTML($pagename, '(:groupheader:)') 
        . $output
        . MarkupToHTML($pagename, '(:groupfooter:)') 
        ;

    SDV(
        $HandleBrowseFmt, 
        array(&$PageStartFmt, &$PageRedirectFmt, '$PageText', &$PageEndFmt)
        );

    PrintFmt($new_pagename, $HandleBrowseFmt);
}

## [[target = *]]
Markup('[[=','<[[',"/\\[\\[([^|\\]]+)\\s*\\=\\s*\\*\\s*\\]\\]/e","Keep(MLink('$1'),'L')");
?>