# Plugin for TWiki Collaboration Platform, http://TWiki.org/
#
# Copyright (C) 2000-2003 Andrea Sterbini, a.sterbini@flashnet.it
# Copyright (C) 2001-2004 Peter Thoeny, peter@thoeny.com
#
# 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; either version 2
# of the License, or (at your option) any later version.
#
# 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, published at 
# http://www.gnu.org/copyleft/gpl.html
#
# =========================
#
# This is an empty TWiki plugin. Use it as a template
# for your own plugins; see TWiki.TWikiPlugins for details.
#
# Each plugin is a package that may contain these functions:        VERSION:
#
#   earlyInitPlugin         ( )                                     1.020
#   initPlugin              ( $topic, $web, $user, $installWeb )    1.000
#   initializeUserHandler   ( $loginName, $url, $pathInfo )         1.010
#   registrationHandler     ( $web, $wikiName, $loginName )         1.010
#   beforeCommonTagsHandler ( $text, $topic, $web )                 1.024
#   commonTagsHandler       ( $text, $topic, $web )                 1.000
#   afterCommonTagsHandler  ( $text, $topic, $web )                 1.024
#   startRenderingHandler   ( $text, $web )                         1.000
#   outsidePREHandler       ( $text )                               1.000
#   insidePREHandler        ( $text )                               1.000
#   endRenderingHandler     ( $text )                               1.000
#   beforeEditHandler       ( $text, $topic, $web )                 1.010
#   afterEditHandler        ( $text, $topic, $web )                 1.010
#   beforeSaveHandler       ( $text, $topic, $web )                 1.010
#   afterSaveHandler        ( $text, $topic, $web, $errors )        1.020
#   writeHeaderHandler      ( $query )                              1.010  Use only in one Plugin
#   redirectCgiQueryHandler ( $query, $url )                        1.010  Use only in one Plugin
#   getSessionValueHandler  ( $key )                                1.010  Use only in one Plugin
#   setSessionValueHandler  ( $key, $value )                        1.010  Use only in one Plugin
#
# initPlugin is required, all other are optional. 
# For increased performance, all handlers except initPlugin are
# disabled. To enable a handler remove the leading DISABLE_ from
# the function name. Remove disabled handlers you do not need.
#
# NOTE: To interact with TWiki use the official TWiki functions 
# in the TWiki::Func module. Do not reference any functions or
# variables elsewhere in TWiki!!


# =========================
package TWiki::Plugins::GoolprojectPlugin;    # change the package name and $pluginName!!!

# =========================
use vars qw(
        $web $topic $user $installWeb $VERSION $pluginName
        $debug $exampleCfgVar
    );

$VERSION = '1.021';
$pluginName = 'GoolprojectPlugin';  # Name of this Plugin
# =========================
sub initPlugin
{
    ( $topic, $web, $user, $installWeb ) = @_;

    # check for Plugins.pm versions
    if( $TWiki::Plugins::VERSION < 1.021 ) {
        TWiki::Func::writeWarning( "Version mismatch between $pluginName and Plugins.pm" );
        return 0;
    }

    # Get plugin debug flag
    $debug = TWiki::Func::getPluginPreferencesFlag( "DEBUG" );

    # Get plugin preferences, the variable defined by:          * Set EXAMPLE = ...
    $exampleCfgVar = TWiki::Func::getPluginPreferencesValue( "EXAMPLE" ) || "default";

    # Plugin correctly initialized
    TWiki::Func::writeDebug( "- TWiki::Plugins::${pluginName}::initPlugin( $web.$topic ) is OK" ) if $debug;
    return 1;
}

# =========================
sub commonTagsHandler
{
### my ( $text, $topic, $web ) = @_;   # do not uncomment, use $_[0], $_[1]... instead

    TWiki::Func::writeDebug( "- ${pluginName}::commonTagsHandler( $_[2].$_[1] )" ) if $debug;

    # This is the place to define customized tags and variables
    # Called by TWiki::handleCommonTags, after %INCLUDE:"..."%

    # do custom extension rule, like for example:
    # $_[0] =~ s/%XYZ%/&handleXyz()/ge;
    # $_[0] =~ s/%XYZ{(.*?)}%/&handleXyz($1)/ge;
    $_[0] =~ s/%MKINPUTFORM{(.*?)}%/&handleMkInputForm($1, $_[1])/ge;
    $_[0] =~ s/%SELECT{(.*?)}%/&handleSelect($1, $_[1], $_[2])/ge;
}

# =========================
sub handleMkInputForm
{
    my($theArgs, $curtopic, $curweb) = @_;
    my $attrTemplate = TWiki::Func::extractNameValuePair( $theArgs, "template") || "TaskTemplate";
    my $attrParent = TWiki::Func::extractNameValuePair( $theArgs, "parent") || "GoolProjectAdministration";
    my $templText = TWiki::Func::readTopicText($curweb, $attrTemplate, "","0");
    if ($templText =~ /.*(<form.*?name="new".*?<\/form>).*/s ) {
	$templText = $1;
    };
    # Expand variables in the templatetopic to get the value of the formfields
    $templText = TWiki::Func::expandCommonVariables($templText, $attrTemplate);
    # Define the name based on the template
    my $name="";
    my $parentName="";
    my $timestamp="\%GMTIME{\"\$ye\$mo\$day\$hour\$min\$sec\"}\%";
    if ($attrTemplate=~ /.*Template$/) {
	    # Extract kind of template and make it postfix of new name
	    if ($attrTemplate=~ /.*([[:upper:]].*?)Template$/ ){
	    	$name = $name.$1;
	    };
	    # Extract name of Parent without timestamp
	    if ($attrParent=~ /.*?[[:digit:]]*([[:alpha:]]*)/){
		$parentName= $1;
	    };
    }
    else {
	    if ($attrTemplate=~ /.*([[:upper:]][[:lower:]]*?)[[:digit:]]*$/){
	        $parentName= $1;
	    };
	    $name = $parentName."Template"; # A normal topic was given as template, so generate a template out of it.
	    $timestamp = ""; # Not needed for templates
    };
    # Define new inputfield with a Javascript to generate a topicname from the title
    my $input = "<input type=\"text\" name=\"Title\" size=\"50\" value=\"\" onblur=\"var sIn = this.value; var sOut = ''; var chgUpper = true; for ( var i = 0; i < sIn.length; i++ ) { var ch = sIn.charAt( i ); var ch2 = ''; if((ch=='&#224;')||(ch=='&#225;')||(ch=='&#226;')||(ch=='&#227;')||(ch=='&#229;') ) { ch = 'a'; } if( (ch=='&#232;')||(ch=='&#233;')||(ch=='&#234;') ) { ch = 'e'; } if( ch=='&#231;') { ch = 'c'; } if( ch=='&#241;') { ch = 'n'; } if( (ch=='&#242;')||(ch=='&#243;')||(ch=='&#244;') ) { ch = 'o'; } if( ch=='&#228;') { ch = 'a'; ch2 = 'e'; } if( ch=='&#246;') { ch = 'o'; ch2 = 'e'; } if( (ch=='&#249;')||(ch=='&#250;')||(ch=='&#251;') ) { ch = 'o'; } if( ch=='&#252;') { ch = 'u'; ch2 = 'e'; } if( ch=='&#196;') { ch = 'A'; ch2 = 'e'; } if( ch=='&#214;') { ch = 'O'; ch2 = 'e'; } if( ch=='&#220;') { ch = 'U'; ch2 = 'e'; } if( ch=='&#223;') { ch = 's'; ch2 = 's'; } if( ((ch>='a')&&(ch<='z')) || ((ch>='A')&&(ch<='Z')) ) { if( chgUpper ) { ch = ch.toUpperCase(); chgUpper = false; } sOut+=ch; if( ch2!='') { sOut+=ch2; } } else { if( ch==' ' ) { chgUpper = true; } } } this.form.topic.value=''+sOut+'".$name.$timestamp."';\" />".$name;
    # if exist: Substitute title inputfield from templatetopic text with new inputfield
    if ($templText =~ /.*(<input.*?name="Title".*?\/>).*/) {
	    $templText =~ s/$1/$input/;
    };
    # Substitute topic and topicparent inputfields with new inputfields
    $input = "<input type=\"hidden\" name=\"topic\" size=\"50\" value=\"".$parentName.$name.$timestamp."\" \/>";
    if ($templText =~ /.*(<input.*?name="topic".*?\/>).*/) {
	    $templText =~ s/$1/$input/;
    };
    $input = "<input type=\"hidden\" name=\"topicparent\" value=\"".$attrParent."\" \/>";
    if ($templText =~ /.*(<input.*?name="topicparent".*?\/>).*/) {
	    $templText =~ s/$1/$input/;
    };
    # Substitute onlynewtopic and submit inputfields with new inputfields - not nessesary 
    $input = "<input type=\"hidden\" name=\"onlynewtopic\" value=\"on\" \/>";
    if ($templText =~ /.*(<input.*?name="onlynewtopic".*?\/>).*/) {
	    $templText =~ s/$1/$input/;
			        };
    $input = "<input name=\"save\" type=\"submit\" value=\"Save\" disabled=\"disabled\"\/>";
    if ($templText =~ /.*(<input.*?name="save".*?\/>).*/) {
	    $templText =~ s/$1/$input/;
    };
    
    # Expand Vsriables
    $templText = TWiki::Func::expandCommonVariables($templText, $curtopic);
return $templText;
}
# =========================
sub handleSelect
{
	my $options = "";
	my ($theArgs, $currtopic, $currweb) = @_;
	my $prefVar = TWiki::Func::extractNameValuePair( $theArgs, "var" ) || "DEFAULT";
	my $sep = TWiki::Func::extractNameValuePair( $theArgs, "separator" ) || ", ";
	my $defaultOption = TWiki::Func::extractNameValuePair( $theArgs, "option" ) || "";
#	my $searchoption = TWiki::Func::extractNameValuePair( $theArgs, "searchoption" ) || "";
	my @catlist = split /$sep/, TWiki::Func::getPluginPreferencesValue("$prefVar");  
	foreach (@catlist){
		if ($_ ne $defaultOption){
			$options = $options."<option>".$_."</option>";
		} else {
			$options = $options."<option selected=\"selected\">".$defaultOption."</option>";
		};	
	};
	$options = "<select ".$theArgs." >".$options."</select>";
	return $options;
}    
# =========================

1;
